repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/VisualStudio/CSharp/Test/CodeModel/MockTextManagerAdapter.TextPoint.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { internal partial class MockTextManagerAdapter { internal sealed class TextPoint : EnvDTE.TextPoint { private readonly VirtualTreePoint _point; public TextPoint(VirtualTreePoint point) { _point = point; } public int AbsoluteCharOffset { get { return _point.Position; } } public bool AtEndOfDocument { get { return _point.Position == _point.Text.Length; } } public bool AtEndOfLine { get { return _point.Position == _point.GetContainingLine().End; } } public bool AtStartOfDocument { get { return _point.Position == 0; } } public bool AtStartOfLine { get { return _point.Position == _point.GetContainingLine().Start; } } public EnvDTE.EditPoint CreateEditPoint() { throw new NotImplementedException(); } public EnvDTE.DTE DTE { get { throw new NotImplementedException(); } } public int DisplayColumn { get { throw new NotImplementedException(); } } public bool EqualTo(EnvDTE.TextPoint point) { return AbsoluteCharOffset == point.AbsoluteCharOffset; } public bool GreaterThan(EnvDTE.TextPoint point) { return AbsoluteCharOffset > point.AbsoluteCharOffset; } public bool LessThan(EnvDTE.TextPoint point) { return AbsoluteCharOffset < point.AbsoluteCharOffset; } public int Line { get { // These line numbers start at 1! return _point.GetContainingLine().LineNumber + 1; } } public int LineCharOffset { get { var result = _point.Position - _point.GetContainingLine().Start + 1; if (_point.IsInVirtualSpace) { result += _point.VirtualSpaces; } return result; } } public int LineLength { get { var line = _point.GetContainingLine(); return line.End - line.Start; } } public EnvDTE.TextDocument Parent { get { return CreateEditPoint().Parent; } } public bool TryToShow(EnvDTE.vsPaneShowHow how, object pointOrCount) { throw new NotImplementedException(); } public EnvDTE.CodeElement get_CodeElement(EnvDTE.vsCMElement scope) { throw new NotImplementedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel { internal partial class MockTextManagerAdapter { internal sealed class TextPoint : EnvDTE.TextPoint { private readonly VirtualTreePoint _point; public TextPoint(VirtualTreePoint point) { _point = point; } public int AbsoluteCharOffset { get { return _point.Position; } } public bool AtEndOfDocument { get { return _point.Position == _point.Text.Length; } } public bool AtEndOfLine { get { return _point.Position == _point.GetContainingLine().End; } } public bool AtStartOfDocument { get { return _point.Position == 0; } } public bool AtStartOfLine { get { return _point.Position == _point.GetContainingLine().Start; } } public EnvDTE.EditPoint CreateEditPoint() { throw new NotImplementedException(); } public EnvDTE.DTE DTE { get { throw new NotImplementedException(); } } public int DisplayColumn { get { throw new NotImplementedException(); } } public bool EqualTo(EnvDTE.TextPoint point) { return AbsoluteCharOffset == point.AbsoluteCharOffset; } public bool GreaterThan(EnvDTE.TextPoint point) { return AbsoluteCharOffset > point.AbsoluteCharOffset; } public bool LessThan(EnvDTE.TextPoint point) { return AbsoluteCharOffset < point.AbsoluteCharOffset; } public int Line { get { // These line numbers start at 1! return _point.GetContainingLine().LineNumber + 1; } } public int LineCharOffset { get { var result = _point.Position - _point.GetContainingLine().Start + 1; if (_point.IsInVirtualSpace) { result += _point.VirtualSpaces; } return result; } } public int LineLength { get { var line = _point.GetContainingLine(); return line.End - line.Start; } } public EnvDTE.TextDocument Parent { get { return CreateEditPoint().Parent; } } public bool TryToShow(EnvDTE.vsPaneShowHow how, object pointOrCount) { throw new NotImplementedException(); } public EnvDTE.CodeElement get_CodeElement(EnvDTE.vsCMElement scope) { throw new NotImplementedException(); } } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created in owning compilation. All requests for /// anonymous type symbols go via the instance of this class. /// </summary> internal sealed partial class AnonymousTypeManager : CommonAnonymousTypeManager { internal AnonymousTypeManager(CSharpCompilation compilation) { Debug.Assert(compilation != null); this.Compilation = compilation; } /// <summary> /// Current compilation /// </summary> public CSharpCompilation Compilation { get; } /// <summary> /// Given anonymous type descriptor provided constructs an anonymous type symbol. /// </summary> public NamedTypeSymbol ConstructAnonymousTypeSymbol(AnonymousTypeDescriptor typeDescr) { return new AnonymousTypePublicSymbol(this, typeDescr); } /// <summary> /// Get a symbol of constructed anonymous type property by property index /// </summary> internal static PropertySymbol GetAnonymousTypeProperty(NamedTypeSymbol type, int index) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Properties[index]; } /// <summary> /// Retrieves anonymous type properties types /// </summary> internal static ImmutableArray<TypeWithAnnotations> GetAnonymousTypePropertyTypesWithAnnotations(NamedTypeSymbol type) { Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; var fields = anonymous.TypeDescriptor.Fields; return fields.SelectAsArray(f => f.TypeWithAnnotations); } /// <summary> /// Given an anonymous type and new field types construct a new anonymous type symbol; /// a new type symbol will reuse type descriptor from the constructed type with new type arguments. /// </summary> public static NamedTypeSymbol ConstructAnonymousTypeSymbol(NamedTypeSymbol type, ImmutableArray<TypeWithAnnotations> newFieldTypes) { Debug.Assert(!newFieldTypes.IsDefault); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeSymbol(anonymous.TypeDescriptor.WithNewFieldsTypes(newFieldTypes)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created in owning compilation. All requests for /// anonymous type symbols go via the instance of this class. /// </summary> internal sealed partial class AnonymousTypeManager : CommonAnonymousTypeManager { internal AnonymousTypeManager(CSharpCompilation compilation) { Debug.Assert(compilation != null); this.Compilation = compilation; } /// <summary> /// Current compilation /// </summary> public CSharpCompilation Compilation { get; } /// <summary> /// Given anonymous type descriptor provided constructs an anonymous type symbol. /// </summary> public NamedTypeSymbol ConstructAnonymousTypeSymbol(AnonymousTypeDescriptor typeDescr) { return new AnonymousTypePublicSymbol(this, typeDescr); } /// <summary> /// Get a symbol of constructed anonymous type property by property index /// </summary> internal static PropertySymbol GetAnonymousTypeProperty(NamedTypeSymbol type, int index) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Properties[index]; } /// <summary> /// Retrieves anonymous type properties types /// </summary> internal static ImmutableArray<TypeWithAnnotations> GetAnonymousTypePropertyTypesWithAnnotations(NamedTypeSymbol type) { Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; var fields = anonymous.TypeDescriptor.Fields; return fields.SelectAsArray(f => f.TypeWithAnnotations); } /// <summary> /// Given an anonymous type and new field types construct a new anonymous type symbol; /// a new type symbol will reuse type descriptor from the constructed type with new type arguments. /// </summary> public static NamedTypeSymbol ConstructAnonymousTypeSymbol(NamedTypeSymbol type, ImmutableArray<TypeWithAnnotations> newFieldTypes) { Debug.Assert(!newFieldTypes.IsDefault); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeSymbol(anonymous.TypeDescriptor.WithNewFieldsTypes(newFieldTypes)); } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Workspaces/Core/Portable/Workspace/Host/Mef/ExportWorkspaceServiceAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ExportWorkspaceServiceAttribute : ExportAttribute { /// <summary> /// The assembly qualified name of the service's type. /// </summary> public string ServiceType { get; } /// <summary> /// The layer that the service is specified for; ServiceLayer.Default, etc. /// </summary> public string Layer { get; } /// <summary> /// Declares a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace. /// </summary> /// <param name="serviceType">The type that will be used to retrieve the service from a <see cref="HostWorkspaceServices"/>.</param> /// <param name="layer">The layer that the service is specified for; <see cref="ServiceLayer.Default" />, etc.</param> public ExportWorkspaceServiceAttribute(Type serviceType, string layer = ServiceLayer.Default) : base(typeof(IWorkspaceService)) { if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } this.ServiceType = serviceType.AssemblyQualifiedName; this.Layer = layer ?? throw new ArgumentNullException(nameof(layer)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ExportWorkspaceServiceAttribute : ExportAttribute { /// <summary> /// The assembly qualified name of the service's type. /// </summary> public string ServiceType { get; } /// <summary> /// The layer that the service is specified for; ServiceLayer.Default, etc. /// </summary> public string Layer { get; } /// <summary> /// Declares a <see cref="IWorkspaceService"/> implementation for inclusion in a MEF-based workspace. /// </summary> /// <param name="serviceType">The type that will be used to retrieve the service from a <see cref="HostWorkspaceServices"/>.</param> /// <param name="layer">The layer that the service is specified for; <see cref="ServiceLayer.Default" />, etc.</param> public ExportWorkspaceServiceAttribute(Type serviceType, string layer = ServiceLayer.Default) : base(typeof(IWorkspaceService)) { if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } this.ServiceType = serviceType.AssemblyQualifiedName; this.Layer = layer ?? throw new ArgumentNullException(nameof(layer)); } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Emit/NoPia/EmbeddedField.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.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols #If Not DEBUG Then Imports FieldSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.FieldSymbol #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedField Inherits EmbeddedTypesManager.CommonEmbeddedField Public Sub New(containingType As EmbeddedType, underlyingField As FieldSymbolAdapter) MyBase.New(containingType, underlyingField) End Sub Friend Overrides ReadOnly Property TypeManager As EmbeddedTypesManager Get Return ContainingType.TypeManager End Get End Property Protected Overrides Function GetCustomAttributesToEmit(moduleBuilder As PEModuleBuilder) As IEnumerable(Of VisualBasicAttributeData) Return UnderlyingField.AdaptedFieldSymbol.GetCustomAttributesToEmit(moduleBuilder.CompilationState) End Function Protected Overrides Function GetCompileTimeValue(context As EmitContext) As MetadataConstant Return UnderlyingField.GetMetadataConstantValue(context) End Function Protected Overrides ReadOnly Property IsCompileTimeConstant As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsMetadataConstant End Get End Property Protected Overrides ReadOnly Property IsNotSerialized As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsNotSerialized End Get End Property Protected Overrides ReadOnly Property IsReadOnly As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsReadOnly End Get End Property Protected Overrides ReadOnly Property IsRuntimeSpecial As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.HasRuntimeSpecialName End Get End Property Protected Overrides ReadOnly Property IsSpecialName As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.HasSpecialName End Get End Property Protected Overrides ReadOnly Property IsStatic As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsShared End Get End Property Protected Overrides ReadOnly Property IsMarshalledExplicitly As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsMarshalledExplicitly End Get End Property Protected Overrides ReadOnly Property MarshallingInformation As Cci.IMarshallingInformation Get Return UnderlyingField.AdaptedFieldSymbol.MarshallingInformation End Get End Property Protected Overrides ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte) Get Return UnderlyingField.AdaptedFieldSymbol.MarshallingDescriptor End Get End Property Protected Overrides ReadOnly Property TypeLayoutOffset As Integer? Get Return UnderlyingField.AdaptedFieldSymbol.TypeLayoutOffset End Get End Property Protected Overrides ReadOnly Property Visibility As Cci.TypeMemberVisibility Get Return PEModuleBuilder.MemberVisibility(UnderlyingField.AdaptedFieldSymbol) End Get End Property Protected Overrides ReadOnly Property Name As String Get Return UnderlyingField.AdaptedFieldSymbol.MetadataName End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols #If Not DEBUG Then Imports FieldSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.FieldSymbol #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedField Inherits EmbeddedTypesManager.CommonEmbeddedField Public Sub New(containingType As EmbeddedType, underlyingField As FieldSymbolAdapter) MyBase.New(containingType, underlyingField) End Sub Friend Overrides ReadOnly Property TypeManager As EmbeddedTypesManager Get Return ContainingType.TypeManager End Get End Property Protected Overrides Function GetCustomAttributesToEmit(moduleBuilder As PEModuleBuilder) As IEnumerable(Of VisualBasicAttributeData) Return UnderlyingField.AdaptedFieldSymbol.GetCustomAttributesToEmit(moduleBuilder.CompilationState) End Function Protected Overrides Function GetCompileTimeValue(context As EmitContext) As MetadataConstant Return UnderlyingField.GetMetadataConstantValue(context) End Function Protected Overrides ReadOnly Property IsCompileTimeConstant As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsMetadataConstant End Get End Property Protected Overrides ReadOnly Property IsNotSerialized As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsNotSerialized End Get End Property Protected Overrides ReadOnly Property IsReadOnly As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsReadOnly End Get End Property Protected Overrides ReadOnly Property IsRuntimeSpecial As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.HasRuntimeSpecialName End Get End Property Protected Overrides ReadOnly Property IsSpecialName As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.HasSpecialName End Get End Property Protected Overrides ReadOnly Property IsStatic As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsShared End Get End Property Protected Overrides ReadOnly Property IsMarshalledExplicitly As Boolean Get Return UnderlyingField.AdaptedFieldSymbol.IsMarshalledExplicitly End Get End Property Protected Overrides ReadOnly Property MarshallingInformation As Cci.IMarshallingInformation Get Return UnderlyingField.AdaptedFieldSymbol.MarshallingInformation End Get End Property Protected Overrides ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte) Get Return UnderlyingField.AdaptedFieldSymbol.MarshallingDescriptor End Get End Property Protected Overrides ReadOnly Property TypeLayoutOffset As Integer? Get Return UnderlyingField.AdaptedFieldSymbol.TypeLayoutOffset End Get End Property Protected Overrides ReadOnly Property Visibility As Cci.TypeMemberVisibility Get Return PEModuleBuilder.MemberVisibility(UnderlyingField.AdaptedFieldSymbol) End Get End Property Protected Overrides ReadOnly Property Name As String Get Return UnderlyingField.AdaptedFieldSymbol.MetadataName End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/Core/Portable/Syntax/ChildSyntaxList.Enumerator.cs
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis { public partial struct ChildSyntaxList { /// <summary>Enumerates the elements of a <see cref="ChildSyntaxList" />.</summary> public struct Enumerator { private SyntaxNode? _node; private int _count; private int _childIndex; internal Enumerator(SyntaxNode node, int count) { _node = node; _count = count; _childIndex = -1; } // PERF: Initialize an Enumerator directly from a SyntaxNode without going // via ChildNodesAndTokens. This saves constructing an intermediate ChildSyntaxList internal void InitializeFrom(SyntaxNode node) { _node = node; _count = CountNodes(node.Green); _childIndex = -1; } /// <summary>Advances the enumerator to the next element of the <see cref="ChildSyntaxList" />.</summary> /// <returns>true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.</returns> [MemberNotNullWhen(true, nameof(_node))] public bool MoveNext() { var newIndex = _childIndex + 1; if (newIndex < _count) { _childIndex = newIndex; Debug.Assert(_node != null); return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> /// <returns>The element in the <see cref="ChildSyntaxList" /> at the current position of the enumerator.</returns> public SyntaxNodeOrToken Current { get { Debug.Assert(_node is object); return ItemInternal(_node, _childIndex); } } /// <summary>Sets the enumerator to its initial position, which is before the first element in the collection.</summary> public void Reset() { _childIndex = -1; } internal bool TryMoveNextAndGetCurrent(out SyntaxNodeOrToken current) { if (!MoveNext()) { current = default; return false; } current = ItemInternal(_node, _childIndex); return true; } internal SyntaxNode? TryMoveNextAndGetCurrentAsNode() { while (MoveNext()) { var nodeValue = ItemInternalAsNode(_node, _childIndex); if (nodeValue != null) { return nodeValue; } } return null; } } private class EnumeratorImpl : IEnumerator<SyntaxNodeOrToken> { private Enumerator _enumerator; internal EnumeratorImpl(SyntaxNode node, int count) { _enumerator = new Enumerator(node, count); } /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <returns> /// The element in the collection at the current position of the enumerator. /// </returns> public SyntaxNodeOrToken Current { get { return _enumerator.Current; } } /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <returns> /// The element in the collection at the current position of the enumerator. /// </returns> object IEnumerator.Current { get { return _enumerator.Current; } } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { return _enumerator.MoveNext(); } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> public void Reset() { _enumerator.Reset(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void 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.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis { public partial struct ChildSyntaxList { /// <summary>Enumerates the elements of a <see cref="ChildSyntaxList" />.</summary> public struct Enumerator { private SyntaxNode? _node; private int _count; private int _childIndex; internal Enumerator(SyntaxNode node, int count) { _node = node; _count = count; _childIndex = -1; } // PERF: Initialize an Enumerator directly from a SyntaxNode without going // via ChildNodesAndTokens. This saves constructing an intermediate ChildSyntaxList internal void InitializeFrom(SyntaxNode node) { _node = node; _count = CountNodes(node.Green); _childIndex = -1; } /// <summary>Advances the enumerator to the next element of the <see cref="ChildSyntaxList" />.</summary> /// <returns>true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.</returns> [MemberNotNullWhen(true, nameof(_node))] public bool MoveNext() { var newIndex = _childIndex + 1; if (newIndex < _count) { _childIndex = newIndex; Debug.Assert(_node != null); return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> /// <returns>The element in the <see cref="ChildSyntaxList" /> at the current position of the enumerator.</returns> public SyntaxNodeOrToken Current { get { Debug.Assert(_node is object); return ItemInternal(_node, _childIndex); } } /// <summary>Sets the enumerator to its initial position, which is before the first element in the collection.</summary> public void Reset() { _childIndex = -1; } internal bool TryMoveNextAndGetCurrent(out SyntaxNodeOrToken current) { if (!MoveNext()) { current = default; return false; } current = ItemInternal(_node, _childIndex); return true; } internal SyntaxNode? TryMoveNextAndGetCurrentAsNode() { while (MoveNext()) { var nodeValue = ItemInternalAsNode(_node, _childIndex); if (nodeValue != null) { return nodeValue; } } return null; } } private class EnumeratorImpl : IEnumerator<SyntaxNodeOrToken> { private Enumerator _enumerator; internal EnumeratorImpl(SyntaxNode node, int count) { _enumerator = new Enumerator(node, count); } /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <returns> /// The element in the collection at the current position of the enumerator. /// </returns> public SyntaxNodeOrToken Current { get { return _enumerator.Current; } } /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <returns> /// The element in the collection at the current position of the enumerator. /// </returns> object IEnumerator.Current { get { return _enumerator.Current; } } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { return _enumerator.MoveNext(); } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> public void Reset() { _enumerator.Reset(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { } } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/Core/Portable/Operations/ControlFlowGraph.cs
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis { /// <summary> /// Control flow graph representation for a given executable code block <see cref="OriginalOperation"/>. /// This graph contains a set of <see cref="BasicBlock"/>s, with an entry block, zero /// or more intermediate basic blocks and an exit block. /// Each basic block contains zero or more <see cref="BasicBlock.Operations"/> and /// explicit <see cref="ControlFlowBranch"/>(s) to other basic block(s). /// </summary> public sealed partial class ControlFlowGraph { private readonly ControlFlowGraphBuilder.CaptureIdDispenser _captureIdDispenser; private readonly ImmutableDictionary<IMethodSymbol, (ControlFlowRegion region, ILocalFunctionOperation operation, int ordinal)> _localFunctionsMap; private ControlFlowGraph?[]? _lazyLocalFunctionsGraphs; private readonly ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)> _anonymousFunctionsMap; private ControlFlowGraph?[]? _lazyAnonymousFunctionsGraphs; internal ControlFlowGraph(IOperation originalOperation, ControlFlowGraph? parent, ControlFlowGraphBuilder.CaptureIdDispenser captureIdDispenser, ImmutableArray<BasicBlock> blocks, ControlFlowRegion root, ImmutableArray<IMethodSymbol> localFunctions, ImmutableDictionary<IMethodSymbol, (ControlFlowRegion region, ILocalFunctionOperation operation, int ordinal)> localFunctionsMap, ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)> anonymousFunctionsMap) { Debug.Assert(parent != null == (originalOperation.Kind == OperationKind.LocalFunction || originalOperation.Kind == OperationKind.AnonymousFunction)); Debug.Assert(captureIdDispenser != null); Debug.Assert(!blocks.IsDefault); Debug.Assert(blocks.First().Kind == BasicBlockKind.Entry); Debug.Assert(blocks.Last().Kind == BasicBlockKind.Exit); Debug.Assert(root != null); Debug.Assert(root.Kind == ControlFlowRegionKind.Root); Debug.Assert(root.FirstBlockOrdinal == 0); Debug.Assert(root.LastBlockOrdinal == blocks.Length - 1); Debug.Assert(!localFunctions.IsDefault); Debug.Assert(localFunctionsMap != null); Debug.Assert(localFunctionsMap.Count == localFunctions.Length); Debug.Assert(localFunctions.Distinct().Length == localFunctions.Length); Debug.Assert(anonymousFunctionsMap != null); #if DEBUG foreach (IMethodSymbol method in localFunctions) { Debug.Assert(method.MethodKind == MethodKind.LocalFunction); Debug.Assert(localFunctionsMap.ContainsKey(method)); } #endif OriginalOperation = originalOperation; Parent = parent; Blocks = blocks; Root = root; LocalFunctions = localFunctions; _localFunctionsMap = localFunctionsMap; _anonymousFunctionsMap = anonymousFunctionsMap; _captureIdDispenser = captureIdDispenser; } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block root <paramref name="node"/>. /// </summary> /// <param name="node">Root syntax node for an executable code block.</param> /// <param name="semanticModel">Semantic model for the syntax tree containing the <paramref name="node"/>.</param> /// <param name="cancellationToken">Optional cancellation token.</param> /// <returns> /// Returns null if <see cref="SemanticModel.GetOperation(SyntaxNode, CancellationToken)"/> returns null for the given <paramref name="node"/> and <paramref name="semanticModel"/>. /// Otherwise, returns a <see cref="ControlFlowGraph"/> for the executable code block. /// </returns> public static ControlFlowGraph? Create(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken = default) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (semanticModel == null) { throw new ArgumentNullException(nameof(semanticModel)); } IOperation? operation = semanticModel.GetOperation(node, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); return operation == null ? null : CreateCore(operation, nameof(operation), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="body"/>. /// </summary> /// <param name="body">Root operation block, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IBlockOperation body, CancellationToken cancellationToken = default) { return CreateCore(body, nameof(body), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="initializer"/>. /// </summary> /// <param name="initializer">Root field initializer operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IFieldInitializerOperation initializer, CancellationToken cancellationToken = default) { return CreateCore(initializer, nameof(initializer), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="initializer"/>. /// </summary> /// <param name="initializer">Root property initializer operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IPropertyInitializerOperation initializer, CancellationToken cancellationToken = default) { return CreateCore(initializer, nameof(initializer), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="initializer"/>. /// </summary> /// <param name="initializer">Root parameter initializer operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IParameterInitializerOperation initializer, CancellationToken cancellationToken = default) { return CreateCore(initializer, nameof(initializer), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="constructorBody"/>. /// </summary> /// <param name="constructorBody">Root constructor body operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IConstructorBodyOperation constructorBody, CancellationToken cancellationToken = default) { return CreateCore(constructorBody, nameof(constructorBody), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="methodBody"/>. /// </summary> /// <param name="methodBody">Root method body operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IMethodBodyOperation methodBody, CancellationToken cancellationToken = default) { return CreateCore(methodBody, nameof(methodBody), cancellationToken); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters internal static ControlFlowGraph CreateCore(IOperation operation, string argumentNameForException, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (operation == null) { throw new ArgumentNullException(argumentNameForException); } if (operation.Parent != null) { throw new ArgumentException(CodeAnalysisResources.NotARootOperation, argumentNameForException); } if (((Operation)operation).OwningSemanticModel == null) { throw new ArgumentException(CodeAnalysisResources.OperationHasNullSemanticModel, argumentNameForException); } try { ControlFlowGraph controlFlowGraph = ControlFlowGraphBuilder.Create(operation); Debug.Assert(controlFlowGraph.OriginalOperation == operation); return controlFlowGraph; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Log a Non-fatal-watson and then ignore the crash in the attempt of getting flow graph. Debug.Assert(false, "\n" + e.ToString()); } return null; } /// <summary> /// Original operation, representing an executable code block, from which this control flow graph was generated. /// Note that <see cref="BasicBlock.Operations"/> in the control flow graph are not in the same operation tree as /// the original operation. /// </summary> public IOperation OriginalOperation { get; } /// <summary> /// Optional parent control flow graph for this graph. /// Non-null for a control flow graph generated for a local function or a lambda. /// Null otherwise. /// </summary> public ControlFlowGraph? Parent { get; } /// <summary> /// Basic blocks for the control flow graph. /// </summary> public ImmutableArray<BasicBlock> Blocks { get; } /// <summary> /// Root (<see cref="ControlFlowRegionKind.Root"/>) region for the graph. /// </summary> public ControlFlowRegion Root { get; } /// <summary> /// Local functions declared within <see cref="OriginalOperation"/>. /// </summary> public ImmutableArray<IMethodSymbol> LocalFunctions { get; } /// <summary> /// Creates a control flow graph for the given <paramref name="localFunction"/>. /// </summary> public ControlFlowGraph GetLocalFunctionControlFlowGraph(IMethodSymbol localFunction, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); if (localFunction is null) { throw new ArgumentNullException(nameof(localFunction)); } if (!TryGetLocalFunctionControlFlowGraph(localFunction, cancellationToken, out var controlFlowGraph)) { throw new ArgumentOutOfRangeException(nameof(localFunction)); } return controlFlowGraph; } internal bool TryGetLocalFunctionControlFlowGraph(IMethodSymbol localFunction, CancellationToken cancellationToken, [NotNullWhen(true)] out ControlFlowGraph? controlFlowGraph) { if (!_localFunctionsMap.TryGetValue(localFunction, out (ControlFlowRegion enclosing, ILocalFunctionOperation operation, int ordinal) info)) { controlFlowGraph = null; return false; } Debug.Assert(localFunction == LocalFunctions[info.ordinal]); if (_lazyLocalFunctionsGraphs == null) { Interlocked.CompareExchange(ref _lazyLocalFunctionsGraphs, new ControlFlowGraph[LocalFunctions.Length], null); } ref ControlFlowGraph? localFunctionGraph = ref _lazyLocalFunctionsGraphs[info.ordinal]; if (localFunctionGraph == null) { Debug.Assert(localFunction == info.operation.Symbol); ControlFlowGraph graph = ControlFlowGraphBuilder.Create(info.operation, this, info.enclosing, _captureIdDispenser); Debug.Assert(graph.OriginalOperation == info.operation); Interlocked.CompareExchange(ref localFunctionGraph, graph, null); } controlFlowGraph = localFunctionGraph; Debug.Assert(controlFlowGraph.Parent == this); return true; } /// <summary> /// Creates a control flow graph for the given <paramref name="anonymousFunction"/>. /// </summary> public ControlFlowGraph GetAnonymousFunctionControlFlowGraph(IFlowAnonymousFunctionOperation anonymousFunction, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); if (anonymousFunction is null) { throw new ArgumentNullException(nameof(anonymousFunction)); } if (!TryGetAnonymousFunctionControlFlowGraph(anonymousFunction, cancellationToken, out ControlFlowGraph? controlFlowGraph)) { throw new ArgumentOutOfRangeException(nameof(anonymousFunction)); } return controlFlowGraph; } internal bool TryGetAnonymousFunctionControlFlowGraph(IFlowAnonymousFunctionOperation anonymousFunction, CancellationToken cancellationToken, [NotNullWhen(true)] out ControlFlowGraph? controlFlowGraph) { if (!_anonymousFunctionsMap.TryGetValue(anonymousFunction, out (ControlFlowRegion enclosing, int ordinal) info)) { controlFlowGraph = null; return false; } if (_lazyAnonymousFunctionsGraphs == null) { Interlocked.CompareExchange(ref _lazyAnonymousFunctionsGraphs, new ControlFlowGraph[_anonymousFunctionsMap.Count], null); } ref ControlFlowGraph? anonymousFlowGraph = ref _lazyAnonymousFunctionsGraphs[info.ordinal]; if (anonymousFlowGraph == null) { var anonymous = (FlowAnonymousFunctionOperation)anonymousFunction; ControlFlowGraph graph = ControlFlowGraphBuilder.Create(anonymous.Original, this, info.enclosing, _captureIdDispenser, in anonymous.Context); Debug.Assert(graph.OriginalOperation == anonymous.Original); Interlocked.CompareExchange(ref anonymousFlowGraph, graph, null); } controlFlowGraph = anonymousFlowGraph; Debug.Assert(controlFlowGraph!.Parent == this); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FlowAnalysis { /// <summary> /// Control flow graph representation for a given executable code block <see cref="OriginalOperation"/>. /// This graph contains a set of <see cref="BasicBlock"/>s, with an entry block, zero /// or more intermediate basic blocks and an exit block. /// Each basic block contains zero or more <see cref="BasicBlock.Operations"/> and /// explicit <see cref="ControlFlowBranch"/>(s) to other basic block(s). /// </summary> public sealed partial class ControlFlowGraph { private readonly ControlFlowGraphBuilder.CaptureIdDispenser _captureIdDispenser; private readonly ImmutableDictionary<IMethodSymbol, (ControlFlowRegion region, ILocalFunctionOperation operation, int ordinal)> _localFunctionsMap; private ControlFlowGraph?[]? _lazyLocalFunctionsGraphs; private readonly ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)> _anonymousFunctionsMap; private ControlFlowGraph?[]? _lazyAnonymousFunctionsGraphs; internal ControlFlowGraph(IOperation originalOperation, ControlFlowGraph? parent, ControlFlowGraphBuilder.CaptureIdDispenser captureIdDispenser, ImmutableArray<BasicBlock> blocks, ControlFlowRegion root, ImmutableArray<IMethodSymbol> localFunctions, ImmutableDictionary<IMethodSymbol, (ControlFlowRegion region, ILocalFunctionOperation operation, int ordinal)> localFunctionsMap, ImmutableDictionary<IFlowAnonymousFunctionOperation, (ControlFlowRegion region, int ordinal)> anonymousFunctionsMap) { Debug.Assert(parent != null == (originalOperation.Kind == OperationKind.LocalFunction || originalOperation.Kind == OperationKind.AnonymousFunction)); Debug.Assert(captureIdDispenser != null); Debug.Assert(!blocks.IsDefault); Debug.Assert(blocks.First().Kind == BasicBlockKind.Entry); Debug.Assert(blocks.Last().Kind == BasicBlockKind.Exit); Debug.Assert(root != null); Debug.Assert(root.Kind == ControlFlowRegionKind.Root); Debug.Assert(root.FirstBlockOrdinal == 0); Debug.Assert(root.LastBlockOrdinal == blocks.Length - 1); Debug.Assert(!localFunctions.IsDefault); Debug.Assert(localFunctionsMap != null); Debug.Assert(localFunctionsMap.Count == localFunctions.Length); Debug.Assert(localFunctions.Distinct().Length == localFunctions.Length); Debug.Assert(anonymousFunctionsMap != null); #if DEBUG foreach (IMethodSymbol method in localFunctions) { Debug.Assert(method.MethodKind == MethodKind.LocalFunction); Debug.Assert(localFunctionsMap.ContainsKey(method)); } #endif OriginalOperation = originalOperation; Parent = parent; Blocks = blocks; Root = root; LocalFunctions = localFunctions; _localFunctionsMap = localFunctionsMap; _anonymousFunctionsMap = anonymousFunctionsMap; _captureIdDispenser = captureIdDispenser; } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block root <paramref name="node"/>. /// </summary> /// <param name="node">Root syntax node for an executable code block.</param> /// <param name="semanticModel">Semantic model for the syntax tree containing the <paramref name="node"/>.</param> /// <param name="cancellationToken">Optional cancellation token.</param> /// <returns> /// Returns null if <see cref="SemanticModel.GetOperation(SyntaxNode, CancellationToken)"/> returns null for the given <paramref name="node"/> and <paramref name="semanticModel"/>. /// Otherwise, returns a <see cref="ControlFlowGraph"/> for the executable code block. /// </returns> public static ControlFlowGraph? Create(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken = default) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (semanticModel == null) { throw new ArgumentNullException(nameof(semanticModel)); } IOperation? operation = semanticModel.GetOperation(node, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); return operation == null ? null : CreateCore(operation, nameof(operation), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="body"/>. /// </summary> /// <param name="body">Root operation block, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IBlockOperation body, CancellationToken cancellationToken = default) { return CreateCore(body, nameof(body), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="initializer"/>. /// </summary> /// <param name="initializer">Root field initializer operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IFieldInitializerOperation initializer, CancellationToken cancellationToken = default) { return CreateCore(initializer, nameof(initializer), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="initializer"/>. /// </summary> /// <param name="initializer">Root property initializer operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IPropertyInitializerOperation initializer, CancellationToken cancellationToken = default) { return CreateCore(initializer, nameof(initializer), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="initializer"/>. /// </summary> /// <param name="initializer">Root parameter initializer operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IParameterInitializerOperation initializer, CancellationToken cancellationToken = default) { return CreateCore(initializer, nameof(initializer), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="constructorBody"/>. /// </summary> /// <param name="constructorBody">Root constructor body operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IConstructorBodyOperation constructorBody, CancellationToken cancellationToken = default) { return CreateCore(constructorBody, nameof(constructorBody), cancellationToken); } /// <summary> /// Creates a <see cref="ControlFlowGraph"/> for the given executable code block <paramref name="methodBody"/>. /// </summary> /// <param name="methodBody">Root method body operation, which must have a null parent.</param> /// <param name="cancellationToken">Optional cancellation token.</param> public static ControlFlowGraph Create(Operations.IMethodBodyOperation methodBody, CancellationToken cancellationToken = default) { return CreateCore(methodBody, nameof(methodBody), cancellationToken); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters internal static ControlFlowGraph CreateCore(IOperation operation, string argumentNameForException, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (operation == null) { throw new ArgumentNullException(argumentNameForException); } if (operation.Parent != null) { throw new ArgumentException(CodeAnalysisResources.NotARootOperation, argumentNameForException); } if (((Operation)operation).OwningSemanticModel == null) { throw new ArgumentException(CodeAnalysisResources.OperationHasNullSemanticModel, argumentNameForException); } try { ControlFlowGraph controlFlowGraph = ControlFlowGraphBuilder.Create(operation); Debug.Assert(controlFlowGraph.OriginalOperation == operation); return controlFlowGraph; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Log a Non-fatal-watson and then ignore the crash in the attempt of getting flow graph. Debug.Assert(false, "\n" + e.ToString()); } return null; } /// <summary> /// Original operation, representing an executable code block, from which this control flow graph was generated. /// Note that <see cref="BasicBlock.Operations"/> in the control flow graph are not in the same operation tree as /// the original operation. /// </summary> public IOperation OriginalOperation { get; } /// <summary> /// Optional parent control flow graph for this graph. /// Non-null for a control flow graph generated for a local function or a lambda. /// Null otherwise. /// </summary> public ControlFlowGraph? Parent { get; } /// <summary> /// Basic blocks for the control flow graph. /// </summary> public ImmutableArray<BasicBlock> Blocks { get; } /// <summary> /// Root (<see cref="ControlFlowRegionKind.Root"/>) region for the graph. /// </summary> public ControlFlowRegion Root { get; } /// <summary> /// Local functions declared within <see cref="OriginalOperation"/>. /// </summary> public ImmutableArray<IMethodSymbol> LocalFunctions { get; } /// <summary> /// Creates a control flow graph for the given <paramref name="localFunction"/>. /// </summary> public ControlFlowGraph GetLocalFunctionControlFlowGraph(IMethodSymbol localFunction, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); if (localFunction is null) { throw new ArgumentNullException(nameof(localFunction)); } if (!TryGetLocalFunctionControlFlowGraph(localFunction, cancellationToken, out var controlFlowGraph)) { throw new ArgumentOutOfRangeException(nameof(localFunction)); } return controlFlowGraph; } internal bool TryGetLocalFunctionControlFlowGraph(IMethodSymbol localFunction, CancellationToken cancellationToken, [NotNullWhen(true)] out ControlFlowGraph? controlFlowGraph) { if (!_localFunctionsMap.TryGetValue(localFunction, out (ControlFlowRegion enclosing, ILocalFunctionOperation operation, int ordinal) info)) { controlFlowGraph = null; return false; } Debug.Assert(localFunction == LocalFunctions[info.ordinal]); if (_lazyLocalFunctionsGraphs == null) { Interlocked.CompareExchange(ref _lazyLocalFunctionsGraphs, new ControlFlowGraph[LocalFunctions.Length], null); } ref ControlFlowGraph? localFunctionGraph = ref _lazyLocalFunctionsGraphs[info.ordinal]; if (localFunctionGraph == null) { Debug.Assert(localFunction == info.operation.Symbol); ControlFlowGraph graph = ControlFlowGraphBuilder.Create(info.operation, this, info.enclosing, _captureIdDispenser); Debug.Assert(graph.OriginalOperation == info.operation); Interlocked.CompareExchange(ref localFunctionGraph, graph, null); } controlFlowGraph = localFunctionGraph; Debug.Assert(controlFlowGraph.Parent == this); return true; } /// <summary> /// Creates a control flow graph for the given <paramref name="anonymousFunction"/>. /// </summary> public ControlFlowGraph GetAnonymousFunctionControlFlowGraph(IFlowAnonymousFunctionOperation anonymousFunction, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); if (anonymousFunction is null) { throw new ArgumentNullException(nameof(anonymousFunction)); } if (!TryGetAnonymousFunctionControlFlowGraph(anonymousFunction, cancellationToken, out ControlFlowGraph? controlFlowGraph)) { throw new ArgumentOutOfRangeException(nameof(anonymousFunction)); } return controlFlowGraph; } internal bool TryGetAnonymousFunctionControlFlowGraph(IFlowAnonymousFunctionOperation anonymousFunction, CancellationToken cancellationToken, [NotNullWhen(true)] out ControlFlowGraph? controlFlowGraph) { if (!_anonymousFunctionsMap.TryGetValue(anonymousFunction, out (ControlFlowRegion enclosing, int ordinal) info)) { controlFlowGraph = null; return false; } if (_lazyAnonymousFunctionsGraphs == null) { Interlocked.CompareExchange(ref _lazyAnonymousFunctionsGraphs, new ControlFlowGraph[_anonymousFunctionsMap.Count], null); } ref ControlFlowGraph? anonymousFlowGraph = ref _lazyAnonymousFunctionsGraphs[info.ordinal]; if (anonymousFlowGraph == null) { var anonymous = (FlowAnonymousFunctionOperation)anonymousFunction; ControlFlowGraph graph = ControlFlowGraphBuilder.Create(anonymous.Original, this, info.enclosing, _captureIdDispenser, in anonymous.Context); Debug.Assert(graph.OriginalOperation == anonymous.Original); Interlocked.CompareExchange(ref anonymousFlowGraph, graph, null); } controlFlowGraph = anonymousFlowGraph; Debug.Assert(controlFlowGraph!.Parent == this); return true; } } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/EditorFeatures/Core/Host/IPreviewDialogService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Host; namespace Microsoft.CodeAnalysis.Editor.Host { /// <summary> /// Displays the Preview Changes Dialog comparing two solutions. /// </summary> internal interface IPreviewDialogService : IWorkspaceService { /// <summary> /// Presents the user a preview of the changes, based on a textual diff /// between <paramref name="newSolution"/> and <paramref name="oldSolution"/>. /// </summary> /// <param name="title">The title of the preview changes dialog.</param> /// <param name="helpString">The keyword used by F1 help in the dialog.</param> /// <param name="description">Text to display above the treeview in the dialog.</param> /// <param name="topLevelName">The name of the root item in the treeview in the dialog.</param> /// <param name="topLevelGlyph">The <see cref="Glyph"/> of the root item in the treeview.</param> /// <param name="newSolution">The changes to preview.</param> /// <param name="oldSolution">The baseline solution.</param> /// <param name="showCheckBoxes">Whether or not preview dialog should display item checkboxes.</param> /// <returns>Returns <paramref name="oldSolution"/> with the changes selected in the dialog /// applied. Returns null if cancelled.</returns> Solution PreviewChanges( string title, string helpString, string description, string topLevelName, Glyph topLevelGlyph, Solution newSolution, Solution oldSolution, bool showCheckBoxes = 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 Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.Host { /// <summary> /// Displays the Preview Changes Dialog comparing two solutions. /// </summary> internal interface IPreviewDialogService : IWorkspaceService { /// <summary> /// Presents the user a preview of the changes, based on a textual diff /// between <paramref name="newSolution"/> and <paramref name="oldSolution"/>. /// </summary> /// <param name="title">The title of the preview changes dialog.</param> /// <param name="helpString">The keyword used by F1 help in the dialog.</param> /// <param name="description">Text to display above the treeview in the dialog.</param> /// <param name="topLevelName">The name of the root item in the treeview in the dialog.</param> /// <param name="topLevelGlyph">The <see cref="Glyph"/> of the root item in the treeview.</param> /// <param name="newSolution">The changes to preview.</param> /// <param name="oldSolution">The baseline solution.</param> /// <param name="showCheckBoxes">Whether or not preview dialog should display item checkboxes.</param> /// <returns>Returns <paramref name="oldSolution"/> with the changes selected in the dialog /// applied. Returns null if cancelled.</returns> Solution PreviewChanges( string title, string helpString, string description, string topLevelName, Glyph topLevelGlyph, Solution newSolution, Solution oldSolution, bool showCheckBoxes = true); } }
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Compilers/VisualBasic/Portable/Symbols/Tuples/TuplePropertySymbol.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.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property of a tuple type (such as (int, byte).SomeProperty) ''' that is backed by a property within the tuple underlying type. ''' </summary> Friend NotInheritable Class TuplePropertySymbol Inherits WrappedPropertySymbol Private ReadOnly _containingType As TupleTypeSymbol Private _lazyParameters As ImmutableArray(Of ParameterSymbol) Public Overrides ReadOnly Property IsTupleProperty As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property TupleUnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return Me._underlyingProperty.Type End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._underlyingProperty.TypeCustomModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._underlyingProperty.RefCustomModifiers End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Dim isDefault As Boolean = Me._lazyParameters.IsDefault If isDefault Then InterlockedOperations.Initialize(Of ParameterSymbol)(Me._lazyParameters, Me.CreateParameters()) End If Return Me._lazyParameters End Get End Property Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of MethodSymbol)(Me._underlyingProperty.GetMethod) End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of MethodSymbol)(Me._underlyingProperty.SetMethod) End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of FieldSymbol)(Me._underlyingProperty.AssociatedField) End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get Return Me._underlyingProperty.ExplicitInterfaceImplementations End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me._containingType End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return Me._underlyingProperty.IsOverloads End Get End Property Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean Get Return Me._underlyingProperty.IsMyGroupCollectionProperty End Get End Property Public Sub New(container As TupleTypeSymbol, underlyingProperty As PropertySymbol) MyBase.New(underlyingProperty) Me._containingType = container End Sub Private Function CreateParameters() As ImmutableArray(Of ParameterSymbol) Return Me._underlyingProperty.Parameters.SelectAsArray(Of ParameterSymbol)(Function(p) New TupleParameterSymbol(Me, p)) End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = MyBase.GetUseSiteInfo MyBase.MergeUseSiteInfo(useSiteInfo, Me._underlyingProperty.GetUseSiteInfo()) Return useSiteInfo End Function Public Overrides Function GetHashCode() As Integer Return Me._underlyingProperty.GetHashCode() End Function Public Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, TuplePropertySymbol)) End Function Public Overloads Function Equals(other As TuplePropertySymbol) As Boolean Return other Is Me OrElse (other IsNot Nothing AndAlso TypeSymbol.Equals(Me._containingType, other._containingType, TypeCompareKind.ConsiderEverything) AndAlso Me._underlyingProperty = other._underlyingProperty) End Function Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me._underlyingProperty.GetAttributes() 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.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property of a tuple type (such as (int, byte).SomeProperty) ''' that is backed by a property within the tuple underlying type. ''' </summary> Friend NotInheritable Class TuplePropertySymbol Inherits WrappedPropertySymbol Private ReadOnly _containingType As TupleTypeSymbol Private _lazyParameters As ImmutableArray(Of ParameterSymbol) Public Overrides ReadOnly Property IsTupleProperty As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property TupleUnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return Me._underlyingProperty.Type End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._underlyingProperty.TypeCustomModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return Me._underlyingProperty.RefCustomModifiers End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Dim isDefault As Boolean = Me._lazyParameters.IsDefault If isDefault Then InterlockedOperations.Initialize(Of ParameterSymbol)(Me._lazyParameters, Me.CreateParameters()) End If Return Me._lazyParameters End Get End Property Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of MethodSymbol)(Me._underlyingProperty.GetMethod) End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of MethodSymbol)(Me._underlyingProperty.SetMethod) End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of FieldSymbol)(Me._underlyingProperty.AssociatedField) End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get Return Me._underlyingProperty.ExplicitInterfaceImplementations End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return Me._containingType End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return Me._underlyingProperty.IsOverloads End Get End Property Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean Get Return Me._underlyingProperty.IsMyGroupCollectionProperty End Get End Property Public Sub New(container As TupleTypeSymbol, underlyingProperty As PropertySymbol) MyBase.New(underlyingProperty) Me._containingType = container End Sub Private Function CreateParameters() As ImmutableArray(Of ParameterSymbol) Return Me._underlyingProperty.Parameters.SelectAsArray(Of ParameterSymbol)(Function(p) New TupleParameterSymbol(Me, p)) End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = MyBase.GetUseSiteInfo MyBase.MergeUseSiteInfo(useSiteInfo, Me._underlyingProperty.GetUseSiteInfo()) Return useSiteInfo End Function Public Overrides Function GetHashCode() As Integer Return Me._underlyingProperty.GetHashCode() End Function Public Overrides Function Equals(obj As Object) As Boolean Return Me.Equals(TryCast(obj, TuplePropertySymbol)) End Function Public Overloads Function Equals(other As TuplePropertySymbol) As Boolean Return other Is Me OrElse (other IsNot Nothing AndAlso TypeSymbol.Equals(Me._containingType, other._containingType, TypeCompareKind.ConsiderEverything) AndAlso Me._underlyingProperty = other._underlyingProperty) End Function Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me._underlyingProperty.GetAttributes() End Function End Class End Namespace
-1
dotnet/roslyn
55,841
Remove CallerArgumentExpression feature flag
Relates to test plan https://github.com/dotnet/roslyn/issues/52745
Youssef1313
2021-08-24T05:10:22Z
2021-08-24T22:42:15Z
9f6960a9e370365f5206985e727d2e855fde076d
87f6fdf02ebaeddc2982de1a100783dc9f435267
Remove CallerArgumentExpression feature flag. Relates to test plan https://github.com/dotnet/roslyn/issues/52745
./src/Tools/AnalyzerRunner/DiagnosticAnalyzerRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using static AnalyzerRunner.Program; namespace AnalyzerRunner { public sealed class DiagnosticAnalyzerRunner { private readonly Workspace _workspace; private readonly Options _options; private readonly ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> _analyzers; public DiagnosticAnalyzerRunner(Workspace workspace, Options options) { _workspace = workspace; _options = options; var analyzers = GetDiagnosticAnalyzers(options.AnalyzerPath); _analyzers = FilterAnalyzers(analyzers, options); } public bool HasAnalyzers => _analyzers.Any(pair => pair.Value.Any()); private static Solution SetOptions(Solution solution) { // Make sure AD0001 and AD0002 are reported as errors foreach (var projectId in solution.ProjectIds) { var project = solution.GetProject(projectId)!; if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) continue; var modifiedSpecificDiagnosticOptions = project.CompilationOptions.SpecificDiagnosticOptions .SetItem("AD0001", ReportDiagnostic.Error) .SetItem("AD0002", ReportDiagnostic.Error); var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions); solution = solution.WithProjectCompilationOptions(projectId, modifiedCompilationOptions); } return solution; } public async Task RunAsync(CancellationToken cancellationToken) { if (!HasAnalyzers) { return; } var solution = _workspace.CurrentSolution; solution = SetOptions(solution); await GetAnalysisResultAsync(solution, _analyzers, _options, cancellationToken).ConfigureAwait(false); } // Also runs per document analysis, used by AnalyzerRunner CLI tool internal async Task RunAllAsync(CancellationToken cancellationToken) { if (!HasAnalyzers) { return; } var solution = _workspace.CurrentSolution; solution = SetOptions(solution); var stopwatch = PerformanceTracker.StartNew(); var analysisResult = await GetAnalysisResultAsync(solution, _analyzers, _options, cancellationToken).ConfigureAwait(false); var allDiagnostics = analysisResult.Where(pair => pair.Value != null).SelectMany(pair => pair.Value.GetAllDiagnostics()).ToImmutableArray(); Console.WriteLine($"Found {allDiagnostics.Length} diagnostics in {stopwatch.GetSummary(preciseMemory: true)}"); WriteTelemetry(analysisResult); if (_options.TestDocuments) { // Make sure we have a compilation for each project foreach (var project in solution.Projects) { if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) continue; _ = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); } var projectPerformance = new Dictionary<ProjectId, double>(); var documentPerformance = new Dictionary<DocumentId, DocumentAnalyzerPerformance>(); foreach (var projectId in solution.ProjectIds) { var project = solution.GetProject(projectId); if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) { continue; } foreach (var documentId in project.DocumentIds) { var document = project.GetDocument(documentId); if (!_options.TestDocumentMatch(document.FilePath)) { continue; } var currentDocumentPerformance = await TestDocumentPerformanceAsync(_analyzers, project, documentId, _options, cancellationToken).ConfigureAwait(false); Console.WriteLine($"{document.FilePath ?? document.Name}: {currentDocumentPerformance.EditsPerSecond:0.00} ({currentDocumentPerformance.AllocatedBytesPerEdit} bytes)"); documentPerformance.Add(documentId, currentDocumentPerformance); } var sumOfDocumentAverages = documentPerformance.Where(x => x.Key.ProjectId == projectId).Sum(x => x.Value.EditsPerSecond); double documentCount = documentPerformance.Where(x => x.Key.ProjectId == projectId).Count(); if (documentCount > 0) { projectPerformance[project.Id] = sumOfDocumentAverages / documentCount; } } var slowestFiles = documentPerformance.OrderBy(pair => pair.Value.EditsPerSecond).GroupBy(pair => pair.Key.ProjectId); Console.WriteLine("Slowest files in each project:"); foreach (var projectGroup in slowestFiles) { Console.WriteLine($" {solution.GetProject(projectGroup.Key).Name}"); foreach (var pair in projectGroup.Take(5)) { var document = solution.GetDocument(pair.Key); Console.WriteLine($" {document.FilePath ?? document.Name}: {pair.Value.EditsPerSecond:0.00} ({pair.Value.AllocatedBytesPerEdit} bytes)"); } } foreach (var projectId in solution.ProjectIds) { if (!projectPerformance.TryGetValue(projectId, out var averageEditsInProject)) { continue; } var project = solution.GetProject(projectId); Console.WriteLine($"{project.Name} ({project.DocumentIds.Count} documents): {averageEditsInProject:0.00} edits per second"); } } foreach (var group in allDiagnostics.GroupBy(diagnostic => diagnostic.Id).OrderBy(diagnosticGroup => diagnosticGroup.Key, StringComparer.OrdinalIgnoreCase)) { Console.WriteLine($" {group.Key}: {group.Count()} instances"); // Print out analyzer diagnostics like AD0001 for analyzer exceptions if (group.Key.StartsWith("AD", StringComparison.Ordinal)) { foreach (var item in group) { Console.WriteLine(item); } } } if (!string.IsNullOrWhiteSpace(_options.LogFileName)) { WriteDiagnosticResults(analysisResult.SelectMany(pair => pair.Value.GetAllDiagnostics().Select(j => Tuple.Create(pair.Key, j))).ToImmutableArray(), _options.LogFileName); } } private static async Task<DocumentAnalyzerPerformance> TestDocumentPerformanceAsync(ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzers, Project project, DocumentId documentId, Options analyzerOptionsInternal, CancellationToken cancellationToken) { if (!analyzers.TryGetValue(project.Language, out var languageAnalyzers)) { languageAnalyzers = ImmutableArray<DiagnosticAnalyzer>.Empty; } Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var stopwatch = PerformanceTracker.StartNew(); for (int i = 0; i < analyzerOptionsInternal.TestDocumentIterations; i++) { var workspaceAnalyzerOptions = new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution); CompilationWithAnalyzers compilationWithAnalyzers = compilation.WithAnalyzers(languageAnalyzers, new CompilationWithAnalyzersOptions(workspaceAnalyzerOptions, null, analyzerOptionsInternal.RunConcurrent, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: analyzerOptionsInternal.ReportSuppressedDiagnostics)); SyntaxTree tree = await project.GetDocument(documentId).GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); await compilationWithAnalyzers.GetAnalyzerSyntaxDiagnosticsAsync(tree, cancellationToken).ConfigureAwait(false); await compilationWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(compilation.GetSemanticModel(tree), null, cancellationToken).ConfigureAwait(false); } return new DocumentAnalyzerPerformance(analyzerOptionsInternal.TestDocumentIterations / stopwatch.Elapsed.TotalSeconds, stopwatch.AllocatedBytes / Math.Max(1, analyzerOptionsInternal.TestDocumentIterations)); } private static void WriteDiagnosticResults(ImmutableArray<Tuple<ProjectId, Diagnostic>> diagnostics, string fileName) { var orderedDiagnostics = diagnostics .OrderBy(tuple => tuple.Item2.Id) .ThenBy(tuple => tuple.Item2.Location.SourceTree?.FilePath, StringComparer.OrdinalIgnoreCase) .ThenBy(tuple => tuple.Item2.Location.SourceSpan.Start) .ThenBy(tuple => tuple.Item2.Location.SourceSpan.End); var uniqueLines = new HashSet<string>(); StringBuilder completeOutput = new StringBuilder(); StringBuilder uniqueOutput = new StringBuilder(); foreach (var diagnostic in orderedDiagnostics) { string message = diagnostic.Item2.ToString(); string uniqueMessage = $"{diagnostic.Item1}: {diagnostic.Item2}"; completeOutput.AppendLine(message); if (uniqueLines.Add(uniqueMessage)) { uniqueOutput.AppendLine(message); } } string directoryName = Path.GetDirectoryName(fileName); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); string extension = Path.GetExtension(fileName); string uniqueFileName = Path.Combine(directoryName, $"{fileNameWithoutExtension}-Unique{extension}"); File.WriteAllText(fileName, completeOutput.ToString(), Encoding.UTF8); File.WriteAllText(uniqueFileName, uniqueOutput.ToString(), Encoding.UTF8); } private static ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> FilterAnalyzers(ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzers, Options options) { return analyzers.ToImmutableDictionary( pair => pair.Key, pair => FilterAnalyzers(pair.Value, options).ToImmutableArray()); } private static IEnumerable<DiagnosticAnalyzer> FilterAnalyzers(IEnumerable<DiagnosticAnalyzer> analyzers, Options options) { if (options.IncrementalAnalyzerNames.Any()) { // AnalyzerRunner is running for IIncrementalAnalyzer testing. DiagnosticAnalyzer testing is disabled // unless /all or /a was used. if (!options.UseAll && options.AnalyzerNames.IsEmpty) { yield break; } } if (options.RefactoringNodes.Any()) { // AnalyzerRunner is running for CodeRefactoringProvider testing. DiagnosticAnalyzer testing is disabled. yield break; } var analyzerTypes = new HashSet<Type>(); foreach (var analyzer in analyzers) { if (!analyzerTypes.Add(analyzer.GetType())) { // Avoid running the same analyzer multiple times continue; } if (options.UseAll) { yield return analyzer; } else if (options.AnalyzerNames.Count == 0) { if (analyzer.SupportedDiagnostics.Any(diagnosticDescriptor => diagnosticDescriptor.IsEnabledByDefault)) { yield return analyzer; } } else if (options.AnalyzerNames.Contains(analyzer.GetType().Name)) { yield return analyzer; } } } private static ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> GetDiagnosticAnalyzers(string path) { if (File.Exists(path)) { return GetDiagnosticAnalyzersFromFile(path); } else if (Directory.Exists(path)) { return Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories) .SelectMany(file => GetDiagnosticAnalyzersFromFile(file)) .ToLookup(analyzers => analyzers.Key, analyzers => analyzers.Value) .ToImmutableDictionary( group => group.Key, group => group.SelectMany(analyzer => analyzer).ToImmutableArray()); } throw new InvalidDataException($"Cannot find {path}."); } private static ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> GetDiagnosticAnalyzersFromFile(string path) { var analyzerReference = new AnalyzerFileReference(Path.GetFullPath(path), AssemblyLoader.Instance); var csharpAnalyzers = analyzerReference.GetAnalyzers(LanguageNames.CSharp); var basicAnalyzers = analyzerReference.GetAnalyzers(LanguageNames.VisualBasic); return ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>>.Empty .Add(LanguageNames.CSharp, csharpAnalyzers) .Add(LanguageNames.VisualBasic, basicAnalyzers); } private static async Task<ImmutableDictionary<ProjectId, AnalysisResult>> GetAnalysisResultAsync( Solution solution, ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzers, Options options, CancellationToken cancellationToken) { var projectDiagnosticBuilder = ImmutableDictionary.CreateBuilder<ProjectId, AnalysisResult>(); for (var i = 0; i < options.Iterations; i++) { var projectDiagnosticTasks = new List<KeyValuePair<ProjectId, Task<AnalysisResult>>>(); // Make sure we analyze the projects in parallel foreach (var project in solution.Projects) { if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) { continue; } if (!analyzers.TryGetValue(project.Language, out var languageAnalyzers) || languageAnalyzers.IsEmpty) { continue; } var resultTask = GetProjectAnalysisResultAsync(languageAnalyzers, project, options, cancellationToken); if (!options.RunConcurrent) { await resultTask.ConfigureAwait(false); } projectDiagnosticTasks.Add(new KeyValuePair<ProjectId, Task<AnalysisResult>>(project.Id, resultTask)); } foreach (var task in projectDiagnosticTasks) { var result = await task.Value.ConfigureAwait(false); if (result == null) { continue; } if (projectDiagnosticBuilder.TryGetValue(task.Key, out var previousResult)) { foreach (var pair in previousResult.AnalyzerTelemetryInfo) { result.AnalyzerTelemetryInfo[pair.Key].ExecutionTime += pair.Value.ExecutionTime; } } projectDiagnosticBuilder[task.Key] = result; } } return projectDiagnosticBuilder.ToImmutable(); } /// <summary> /// Returns a list of all analysis results inside the specific project. This is an asynchronous operation. /// </summary> /// <param name="analyzers">The list of analyzers that should be used</param> /// <param name="project">The project that should be analyzed /// <see langword="false"/> to use the behavior configured for the specified <paramref name="project"/>.</param> /// <param name="cancellationToken">The cancellation token that the task will observe.</param> /// <returns>A list of analysis results inside the project</returns> private static async Task<AnalysisResult> GetProjectAnalysisResultAsync( ImmutableArray<DiagnosticAnalyzer> analyzers, Project project, Options analyzerOptionsInternal, CancellationToken cancellationToken) { WriteLine($"Running analyzers for {project.Name}", ConsoleColor.Gray); if (analyzerOptionsInternal.RunConcurrent) { await Task.Yield(); } try { Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(compilation.SyntaxTrees); var workspaceAnalyzerOptions = new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution); CompilationWithAnalyzers compilationWithAnalyzers = newCompilation.WithAnalyzers(analyzers, new CompilationWithAnalyzersOptions(workspaceAnalyzerOptions, null, analyzerOptionsInternal.RunConcurrent, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: analyzerOptionsInternal.ReportSuppressedDiagnostics)); var analystResult = await compilationWithAnalyzers.GetAnalysisResultAsync(cancellationToken).ConfigureAwait(false); return analystResult; } catch (Exception e) { WriteLine($"Failed to analyze {project.Name} with {e.ToString()}", ConsoleColor.Red); return null; } } internal static void WriteTelemetry(ImmutableDictionary<ProjectId, AnalysisResult> dictionary) { if (dictionary.IsEmpty) { return; } var telemetryInfoDictionary = new Dictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo>(); foreach (var analysisResult in dictionary.Values) { foreach (var pair in analysisResult.AnalyzerTelemetryInfo) { if (!telemetryInfoDictionary.TryGetValue(pair.Key, out var telemetry)) { telemetryInfoDictionary.Add(pair.Key, pair.Value); } else { telemetry.Add(pair.Value); } } } foreach (var pair in telemetryInfoDictionary.OrderBy(x => x.Key.GetType().Name, StringComparer.OrdinalIgnoreCase)) { WriteTelemetry(pair.Key.GetType().Name, pair.Value); } WriteLine($"Execution times (ms):", ConsoleColor.DarkCyan); var longestAnalyzerName = telemetryInfoDictionary.Select(x => x.Key.GetType().Name.Length).Max(); foreach (var pair in telemetryInfoDictionary.OrderBy(x => x.Key.GetType().Name, StringComparer.OrdinalIgnoreCase)) { WriteExecutionTimes(pair.Key.GetType().Name, longestAnalyzerName, pair.Value); } } private static void WriteTelemetry(string analyzerName, AnalyzerTelemetryInfo telemetry) { WriteLine($"Statistics for {analyzerName}:", ConsoleColor.DarkCyan); WriteLine($"Concurrent: {telemetry.Concurrent}", telemetry.Concurrent ? ConsoleColor.White : ConsoleColor.DarkRed); WriteLine($"Execution time (ms): {telemetry.ExecutionTime.TotalMilliseconds}", ConsoleColor.White); WriteLine($"Code Block Actions: {telemetry.CodeBlockActionsCount}", ConsoleColor.White); WriteLine($"Code Block Start Actions: {telemetry.CodeBlockStartActionsCount}", ConsoleColor.White); WriteLine($"Code Block End Actions: {telemetry.CodeBlockEndActionsCount}", ConsoleColor.White); WriteLine($"Compilation Actions: {telemetry.CompilationActionsCount}", ConsoleColor.White); WriteLine($"Compilation Start Actions: {telemetry.CompilationStartActionsCount}", ConsoleColor.White); WriteLine($"Compilation End Actions: {telemetry.CompilationEndActionsCount}", ConsoleColor.White); WriteLine($"Operation Actions: {telemetry.OperationActionsCount}", ConsoleColor.White); WriteLine($"Operation Block Actions: {telemetry.OperationBlockActionsCount}", ConsoleColor.White); WriteLine($"Operation Block Start Actions: {telemetry.OperationBlockStartActionsCount}", ConsoleColor.White); WriteLine($"Operation Block End Actions: {telemetry.OperationBlockEndActionsCount}", ConsoleColor.White); WriteLine($"Semantic Model Actions: {telemetry.SemanticModelActionsCount}", ConsoleColor.White); WriteLine($"Symbol Actions: {telemetry.SymbolActionsCount}", ConsoleColor.White); WriteLine($"Symbol Start Actions: {telemetry.SymbolStartActionsCount}", ConsoleColor.White); WriteLine($"Symbol End Actions: {telemetry.SymbolEndActionsCount}", ConsoleColor.White); WriteLine($"Syntax Node Actions: {telemetry.SyntaxNodeActionsCount}", ConsoleColor.White); WriteLine($"Syntax Tree Actions: {telemetry.SyntaxTreeActionsCount}", ConsoleColor.White); WriteLine($"Additional File Actions: {telemetry.AdditionalFileActionsCount}", ConsoleColor.White); WriteLine($"Suppression Actions: {telemetry.SuppressionActionsCount}", ConsoleColor.White); } private static void WriteExecutionTimes(string analyzerName, int longestAnalyzerName, AnalyzerTelemetryInfo telemetry) { var padding = new string(' ', longestAnalyzerName - analyzerName.Length); WriteLine($"{analyzerName}:{padding} {telemetry.ExecutionTime.TotalMilliseconds,7:0}", ConsoleColor.White); } private struct DocumentAnalyzerPerformance { public DocumentAnalyzerPerformance(double editsPerSecond, long allocatedBytesPerEdit) { EditsPerSecond = editsPerSecond; AllocatedBytesPerEdit = allocatedBytesPerEdit; } public double EditsPerSecond { get; } public long AllocatedBytesPerEdit { get; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using static AnalyzerRunner.Program; namespace AnalyzerRunner { public sealed class DiagnosticAnalyzerRunner { private readonly Workspace _workspace; private readonly Options _options; private readonly ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> _analyzers; public DiagnosticAnalyzerRunner(Workspace workspace, Options options) { _workspace = workspace; _options = options; var analyzers = GetDiagnosticAnalyzers(options.AnalyzerPath); _analyzers = FilterAnalyzers(analyzers, options); } public bool HasAnalyzers => _analyzers.Any(pair => pair.Value.Any()); private static Solution SetOptions(Solution solution) { // Make sure AD0001 and AD0002 are reported as errors foreach (var projectId in solution.ProjectIds) { var project = solution.GetProject(projectId)!; if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) continue; var modifiedSpecificDiagnosticOptions = project.CompilationOptions.SpecificDiagnosticOptions .SetItem("AD0001", ReportDiagnostic.Error) .SetItem("AD0002", ReportDiagnostic.Error); var modifiedCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(modifiedSpecificDiagnosticOptions); solution = solution.WithProjectCompilationOptions(projectId, modifiedCompilationOptions); } return solution; } public async Task RunAsync(CancellationToken cancellationToken) { if (!HasAnalyzers) { return; } var solution = _workspace.CurrentSolution; solution = SetOptions(solution); await GetAnalysisResultAsync(solution, _analyzers, _options, cancellationToken).ConfigureAwait(false); } // Also runs per document analysis, used by AnalyzerRunner CLI tool internal async Task RunAllAsync(CancellationToken cancellationToken) { if (!HasAnalyzers) { return; } var solution = _workspace.CurrentSolution; solution = SetOptions(solution); var stopwatch = PerformanceTracker.StartNew(); var analysisResult = await GetAnalysisResultAsync(solution, _analyzers, _options, cancellationToken).ConfigureAwait(false); var allDiagnostics = analysisResult.Where(pair => pair.Value != null).SelectMany(pair => pair.Value.GetAllDiagnostics()).ToImmutableArray(); Console.WriteLine($"Found {allDiagnostics.Length} diagnostics in {stopwatch.GetSummary(preciseMemory: true)}"); WriteTelemetry(analysisResult); if (_options.TestDocuments) { // Make sure we have a compilation for each project foreach (var project in solution.Projects) { if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) continue; _ = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); } var projectPerformance = new Dictionary<ProjectId, double>(); var documentPerformance = new Dictionary<DocumentId, DocumentAnalyzerPerformance>(); foreach (var projectId in solution.ProjectIds) { var project = solution.GetProject(projectId); if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) { continue; } foreach (var documentId in project.DocumentIds) { var document = project.GetDocument(documentId); if (!_options.TestDocumentMatch(document.FilePath)) { continue; } var currentDocumentPerformance = await TestDocumentPerformanceAsync(_analyzers, project, documentId, _options, cancellationToken).ConfigureAwait(false); Console.WriteLine($"{document.FilePath ?? document.Name}: {currentDocumentPerformance.EditsPerSecond:0.00} ({currentDocumentPerformance.AllocatedBytesPerEdit} bytes)"); documentPerformance.Add(documentId, currentDocumentPerformance); } var sumOfDocumentAverages = documentPerformance.Where(x => x.Key.ProjectId == projectId).Sum(x => x.Value.EditsPerSecond); double documentCount = documentPerformance.Where(x => x.Key.ProjectId == projectId).Count(); if (documentCount > 0) { projectPerformance[project.Id] = sumOfDocumentAverages / documentCount; } } var slowestFiles = documentPerformance.OrderBy(pair => pair.Value.EditsPerSecond).GroupBy(pair => pair.Key.ProjectId); Console.WriteLine("Slowest files in each project:"); foreach (var projectGroup in slowestFiles) { Console.WriteLine($" {solution.GetProject(projectGroup.Key).Name}"); foreach (var pair in projectGroup.Take(5)) { var document = solution.GetDocument(pair.Key); Console.WriteLine($" {document.FilePath ?? document.Name}: {pair.Value.EditsPerSecond:0.00} ({pair.Value.AllocatedBytesPerEdit} bytes)"); } } foreach (var projectId in solution.ProjectIds) { if (!projectPerformance.TryGetValue(projectId, out var averageEditsInProject)) { continue; } var project = solution.GetProject(projectId); Console.WriteLine($"{project.Name} ({project.DocumentIds.Count} documents): {averageEditsInProject:0.00} edits per second"); } } foreach (var group in allDiagnostics.GroupBy(diagnostic => diagnostic.Id).OrderBy(diagnosticGroup => diagnosticGroup.Key, StringComparer.OrdinalIgnoreCase)) { Console.WriteLine($" {group.Key}: {group.Count()} instances"); // Print out analyzer diagnostics like AD0001 for analyzer exceptions if (group.Key.StartsWith("AD", StringComparison.Ordinal)) { foreach (var item in group) { Console.WriteLine(item); } } } if (!string.IsNullOrWhiteSpace(_options.LogFileName)) { WriteDiagnosticResults(analysisResult.SelectMany(pair => pair.Value.GetAllDiagnostics().Select(j => Tuple.Create(pair.Key, j))).ToImmutableArray(), _options.LogFileName); } } private static async Task<DocumentAnalyzerPerformance> TestDocumentPerformanceAsync(ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzers, Project project, DocumentId documentId, Options analyzerOptionsInternal, CancellationToken cancellationToken) { if (!analyzers.TryGetValue(project.Language, out var languageAnalyzers)) { languageAnalyzers = ImmutableArray<DiagnosticAnalyzer>.Empty; } Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var stopwatch = PerformanceTracker.StartNew(); for (int i = 0; i < analyzerOptionsInternal.TestDocumentIterations; i++) { var workspaceAnalyzerOptions = new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution); CompilationWithAnalyzers compilationWithAnalyzers = compilation.WithAnalyzers(languageAnalyzers, new CompilationWithAnalyzersOptions(workspaceAnalyzerOptions, null, analyzerOptionsInternal.RunConcurrent, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: analyzerOptionsInternal.ReportSuppressedDiagnostics)); SyntaxTree tree = await project.GetDocument(documentId).GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); await compilationWithAnalyzers.GetAnalyzerSyntaxDiagnosticsAsync(tree, cancellationToken).ConfigureAwait(false); await compilationWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(compilation.GetSemanticModel(tree), null, cancellationToken).ConfigureAwait(false); } return new DocumentAnalyzerPerformance(analyzerOptionsInternal.TestDocumentIterations / stopwatch.Elapsed.TotalSeconds, stopwatch.AllocatedBytes / Math.Max(1, analyzerOptionsInternal.TestDocumentIterations)); } private static void WriteDiagnosticResults(ImmutableArray<Tuple<ProjectId, Diagnostic>> diagnostics, string fileName) { var orderedDiagnostics = diagnostics .OrderBy(tuple => tuple.Item2.Id) .ThenBy(tuple => tuple.Item2.Location.SourceTree?.FilePath, StringComparer.OrdinalIgnoreCase) .ThenBy(tuple => tuple.Item2.Location.SourceSpan.Start) .ThenBy(tuple => tuple.Item2.Location.SourceSpan.End); var uniqueLines = new HashSet<string>(); StringBuilder completeOutput = new StringBuilder(); StringBuilder uniqueOutput = new StringBuilder(); foreach (var diagnostic in orderedDiagnostics) { string message = diagnostic.Item2.ToString(); string uniqueMessage = $"{diagnostic.Item1}: {diagnostic.Item2}"; completeOutput.AppendLine(message); if (uniqueLines.Add(uniqueMessage)) { uniqueOutput.AppendLine(message); } } string directoryName = Path.GetDirectoryName(fileName); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); string extension = Path.GetExtension(fileName); string uniqueFileName = Path.Combine(directoryName, $"{fileNameWithoutExtension}-Unique{extension}"); File.WriteAllText(fileName, completeOutput.ToString(), Encoding.UTF8); File.WriteAllText(uniqueFileName, uniqueOutput.ToString(), Encoding.UTF8); } private static ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> FilterAnalyzers(ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzers, Options options) { return analyzers.ToImmutableDictionary( pair => pair.Key, pair => FilterAnalyzers(pair.Value, options).ToImmutableArray()); } private static IEnumerable<DiagnosticAnalyzer> FilterAnalyzers(IEnumerable<DiagnosticAnalyzer> analyzers, Options options) { if (options.IncrementalAnalyzerNames.Any()) { // AnalyzerRunner is running for IIncrementalAnalyzer testing. DiagnosticAnalyzer testing is disabled // unless /all or /a was used. if (!options.UseAll && options.AnalyzerNames.IsEmpty) { yield break; } } if (options.RefactoringNodes.Any()) { // AnalyzerRunner is running for CodeRefactoringProvider testing. DiagnosticAnalyzer testing is disabled. yield break; } var analyzerTypes = new HashSet<Type>(); foreach (var analyzer in analyzers) { if (!analyzerTypes.Add(analyzer.GetType())) { // Avoid running the same analyzer multiple times continue; } if (options.UseAll) { yield return analyzer; } else if (options.AnalyzerNames.Count == 0) { if (analyzer.SupportedDiagnostics.Any(diagnosticDescriptor => diagnosticDescriptor.IsEnabledByDefault)) { yield return analyzer; } } else if (options.AnalyzerNames.Contains(analyzer.GetType().Name)) { yield return analyzer; } } } private static ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> GetDiagnosticAnalyzers(string path) { if (File.Exists(path)) { return GetDiagnosticAnalyzersFromFile(path); } else if (Directory.Exists(path)) { return Directory.GetFiles(path, "*.dll", SearchOption.AllDirectories) .SelectMany(file => GetDiagnosticAnalyzersFromFile(file)) .ToLookup(analyzers => analyzers.Key, analyzers => analyzers.Value) .ToImmutableDictionary( group => group.Key, group => group.SelectMany(analyzer => analyzer).ToImmutableArray()); } throw new InvalidDataException($"Cannot find {path}."); } private static ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> GetDiagnosticAnalyzersFromFile(string path) { var analyzerReference = new AnalyzerFileReference(Path.GetFullPath(path), AssemblyLoader.Instance); var csharpAnalyzers = analyzerReference.GetAnalyzers(LanguageNames.CSharp); var basicAnalyzers = analyzerReference.GetAnalyzers(LanguageNames.VisualBasic); return ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>>.Empty .Add(LanguageNames.CSharp, csharpAnalyzers) .Add(LanguageNames.VisualBasic, basicAnalyzers); } private static async Task<ImmutableDictionary<ProjectId, AnalysisResult>> GetAnalysisResultAsync( Solution solution, ImmutableDictionary<string, ImmutableArray<DiagnosticAnalyzer>> analyzers, Options options, CancellationToken cancellationToken) { var projectDiagnosticBuilder = ImmutableDictionary.CreateBuilder<ProjectId, AnalysisResult>(); for (var i = 0; i < options.Iterations; i++) { var projectDiagnosticTasks = new List<KeyValuePair<ProjectId, Task<AnalysisResult>>>(); // Make sure we analyze the projects in parallel foreach (var project in solution.Projects) { if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) { continue; } if (!analyzers.TryGetValue(project.Language, out var languageAnalyzers) || languageAnalyzers.IsEmpty) { continue; } var resultTask = GetProjectAnalysisResultAsync(languageAnalyzers, project, options, cancellationToken); if (!options.RunConcurrent) { await resultTask.ConfigureAwait(false); } projectDiagnosticTasks.Add(new KeyValuePair<ProjectId, Task<AnalysisResult>>(project.Id, resultTask)); } foreach (var task in projectDiagnosticTasks) { var result = await task.Value.ConfigureAwait(false); if (result == null) { continue; } if (projectDiagnosticBuilder.TryGetValue(task.Key, out var previousResult)) { foreach (var pair in previousResult.AnalyzerTelemetryInfo) { result.AnalyzerTelemetryInfo[pair.Key].ExecutionTime += pair.Value.ExecutionTime; } } projectDiagnosticBuilder[task.Key] = result; } } return projectDiagnosticBuilder.ToImmutable(); } /// <summary> /// Returns a list of all analysis results inside the specific project. This is an asynchronous operation. /// </summary> /// <param name="analyzers">The list of analyzers that should be used</param> /// <param name="project">The project that should be analyzed /// <see langword="false"/> to use the behavior configured for the specified <paramref name="project"/>.</param> /// <param name="cancellationToken">The cancellation token that the task will observe.</param> /// <returns>A list of analysis results inside the project</returns> private static async Task<AnalysisResult> GetProjectAnalysisResultAsync( ImmutableArray<DiagnosticAnalyzer> analyzers, Project project, Options analyzerOptionsInternal, CancellationToken cancellationToken) { WriteLine($"Running analyzers for {project.Name}", ConsoleColor.Gray); if (analyzerOptionsInternal.RunConcurrent) { await Task.Yield(); } try { Compilation compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(compilation.SyntaxTrees); var workspaceAnalyzerOptions = new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution); CompilationWithAnalyzers compilationWithAnalyzers = newCompilation.WithAnalyzers(analyzers, new CompilationWithAnalyzersOptions(workspaceAnalyzerOptions, null, analyzerOptionsInternal.RunConcurrent, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: analyzerOptionsInternal.ReportSuppressedDiagnostics)); var analystResult = await compilationWithAnalyzers.GetAnalysisResultAsync(cancellationToken).ConfigureAwait(false); return analystResult; } catch (Exception e) { WriteLine($"Failed to analyze {project.Name} with {e.ToString()}", ConsoleColor.Red); return null; } } internal static void WriteTelemetry(ImmutableDictionary<ProjectId, AnalysisResult> dictionary) { if (dictionary.IsEmpty) { return; } var telemetryInfoDictionary = new Dictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo>(); foreach (var analysisResult in dictionary.Values) { foreach (var pair in analysisResult.AnalyzerTelemetryInfo) { if (!telemetryInfoDictionary.TryGetValue(pair.Key, out var telemetry)) { telemetryInfoDictionary.Add(pair.Key, pair.Value); } else { telemetry.Add(pair.Value); } } } foreach (var pair in telemetryInfoDictionary.OrderBy(x => x.Key.GetType().Name, StringComparer.OrdinalIgnoreCase)) { WriteTelemetry(pair.Key.GetType().Name, pair.Value); } WriteLine($"Execution times (ms):", ConsoleColor.DarkCyan); var longestAnalyzerName = telemetryInfoDictionary.Select(x => x.Key.GetType().Name.Length).Max(); foreach (var pair in telemetryInfoDictionary.OrderBy(x => x.Key.GetType().Name, StringComparer.OrdinalIgnoreCase)) { WriteExecutionTimes(pair.Key.GetType().Name, longestAnalyzerName, pair.Value); } } private static void WriteTelemetry(string analyzerName, AnalyzerTelemetryInfo telemetry) { WriteLine($"Statistics for {analyzerName}:", ConsoleColor.DarkCyan); WriteLine($"Concurrent: {telemetry.Concurrent}", telemetry.Concurrent ? ConsoleColor.White : ConsoleColor.DarkRed); WriteLine($"Execution time (ms): {telemetry.ExecutionTime.TotalMilliseconds}", ConsoleColor.White); WriteLine($"Code Block Actions: {telemetry.CodeBlockActionsCount}", ConsoleColor.White); WriteLine($"Code Block Start Actions: {telemetry.CodeBlockStartActionsCount}", ConsoleColor.White); WriteLine($"Code Block End Actions: {telemetry.CodeBlockEndActionsCount}", ConsoleColor.White); WriteLine($"Compilation Actions: {telemetry.CompilationActionsCount}", ConsoleColor.White); WriteLine($"Compilation Start Actions: {telemetry.CompilationStartActionsCount}", ConsoleColor.White); WriteLine($"Compilation End Actions: {telemetry.CompilationEndActionsCount}", ConsoleColor.White); WriteLine($"Operation Actions: {telemetry.OperationActionsCount}", ConsoleColor.White); WriteLine($"Operation Block Actions: {telemetry.OperationBlockActionsCount}", ConsoleColor.White); WriteLine($"Operation Block Start Actions: {telemetry.OperationBlockStartActionsCount}", ConsoleColor.White); WriteLine($"Operation Block End Actions: {telemetry.OperationBlockEndActionsCount}", ConsoleColor.White); WriteLine($"Semantic Model Actions: {telemetry.SemanticModelActionsCount}", ConsoleColor.White); WriteLine($"Symbol Actions: {telemetry.SymbolActionsCount}", ConsoleColor.White); WriteLine($"Symbol Start Actions: {telemetry.SymbolStartActionsCount}", ConsoleColor.White); WriteLine($"Symbol End Actions: {telemetry.SymbolEndActionsCount}", ConsoleColor.White); WriteLine($"Syntax Node Actions: {telemetry.SyntaxNodeActionsCount}", ConsoleColor.White); WriteLine($"Syntax Tree Actions: {telemetry.SyntaxTreeActionsCount}", ConsoleColor.White); WriteLine($"Additional File Actions: {telemetry.AdditionalFileActionsCount}", ConsoleColor.White); WriteLine($"Suppression Actions: {telemetry.SuppressionActionsCount}", ConsoleColor.White); } private static void WriteExecutionTimes(string analyzerName, int longestAnalyzerName, AnalyzerTelemetryInfo telemetry) { var padding = new string(' ', longestAnalyzerName - analyzerName.Length); WriteLine($"{analyzerName}:{padding} {telemetry.ExecutionTime.TotalMilliseconds,7:0}", ConsoleColor.White); } private struct DocumentAnalyzerPerformance { public DocumentAnalyzerPerformance(double editsPerSecond, long allocatedBytesPerEdit) { EditsPerSecond = editsPerSecond; AllocatedBytesPerEdit = allocatedBytesPerEdit; } public double EditsPerSecond { get; } public long AllocatedBytesPerEdit { get; } } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./docs/compilers/CSharp/Compiler Breaking Changes - post DotNet 5.md
## This document lists known breaking changes in Roslyn after .NET 5. 1. https://github.com/dotnet/roslyn/issues/46044 In C# 9.0 (Visual Studio 16.9), a warning is reported when assigning `default` to, or when casting a possibly `null` value to a type parameter type that is not constrained to value types or reference types. To avoid the warning, the type can be annotated with `?`. ```C# static void F1<T>(object? obj) { T t1 = default; // warning CS8600: Converting possible null value to non-nullable type t1 = (T)obj; // warning CS8600: Converting possible null value to non-nullable type T? t2 = default; // ok t2 = (T?)obj; // ok } ``` 2. https://github.com/dotnet/roslyn/pull/50755 In .NET 5.0.200 (Visual Studio 16.9), if there is a common type between the two branches of a conditional expression, that type is the type of the conditional expression. This is a breaking change from 5.0.103 (Visual Studio 16.8) which due to a bug incorrectly used the target type of the conditional expression as the type even if there was a common type between the two branches. This latest change aligns the compiler behavior with the C# specification and with versions of the compiler before .NET 5.0. ```C# static short F1(bool b) { // 16.7, 16.9 : CS0266: Cannot implicitly convert type 'int' to 'short' // 16.8 : ok // 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0 return b ? 1 : 2; } static object F2(bool b, short? a) { // 16.7, 16.9 : int // 16.8 : short // 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0 return a ?? (b ? 1 : 2); } ``` 3. https://github.com/dotnet/roslyn/issues/52630 In C# 9 (.NET 5, Visual Studio 16.9), it is possible that a record uses a hidden member from a base type as a positional member. In Visual Studio 16.10, this is now an error: ```csharp record Base { public int I { get; init; } } record Derived(int I) // The positional member 'Base.I' found corresponding to this parameter is hidden. : Base { public int I() { return 0; } } ``` 4. In C# 10, method groups are implicitly convertible to `System.Delegate`, and lambda expressions are implicitly convertible to `System.Delegate` and `System.Linq.Expressions.Expression`. This is a breaking change to overload resolution if there exists an overload with a `System.Delegate` or `System.Linq.Expressions.Expression` parameter that is applicable and the closest applicable overload with a strongly-typed delegate parameter is in an enclosing namespace. ```C# class C { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(), C#10: C.M() c.M(() => { }); // C#9: E.M(), C#10: C.M() } void M(System.Delegate d) { } } static class E { public static void M(this object x, System.Action y) { } } ``` 5. In .NET 5 and Visual Studio 16.9 (and earlier), top-level statements could be used in a program containing a type named `Program`. In .NET 6 and Visual Studio 17.0, top-level statements generate a partial declaration of a `Program` class, so any user-defined `Program` type must also be a partial class. ```csharp System.Console.Write("top-level"); Method(); partial class Program { static void Method() { } } ```
## This document lists known breaking changes in Roslyn after .NET 5. 1. https://github.com/dotnet/roslyn/issues/46044 In C# 9.0 (Visual Studio 16.9), a warning is reported when assigning `default` to, or when casting a possibly `null` value to a type parameter type that is not constrained to value types or reference types. To avoid the warning, the type can be annotated with `?`. ```C# static void F1<T>(object? obj) { T t1 = default; // warning CS8600: Converting possible null value to non-nullable type t1 = (T)obj; // warning CS8600: Converting possible null value to non-nullable type T? t2 = default; // ok t2 = (T?)obj; // ok } ``` 2. https://github.com/dotnet/roslyn/pull/50755 In .NET 5.0.200 (Visual Studio 16.9), if there is a common type between the two branches of a conditional expression, that type is the type of the conditional expression. This is a breaking change from 5.0.103 (Visual Studio 16.8) which due to a bug incorrectly used the target type of the conditional expression as the type even if there was a common type between the two branches. This latest change aligns the compiler behavior with the C# specification and with versions of the compiler before .NET 5.0. ```C# static short F1(bool b) { // 16.7, 16.9 : CS0266: Cannot implicitly convert type 'int' to 'short' // 16.8 : ok // 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0 return b ? 1 : 2; } static object F2(bool b, short? a) { // 16.7, 16.9 : int // 16.8 : short // 16.8 -langversion:8 : CS8400: Feature 'target-typed conditional expression' is not available in C# 8.0 return a ?? (b ? 1 : 2); } ``` 3. https://github.com/dotnet/roslyn/issues/52630 In C# 9 (.NET 5, Visual Studio 16.9), it is possible that a record uses a hidden member from a base type as a positional member. In Visual Studio 16.10, this is now an error: ```csharp record Base { public int I { get; init; } } record Derived(int I) // The positional member 'Base.I' found corresponding to this parameter is hidden. : Base { public int I() { return 0; } } ``` 4. In C# 10, method groups are implicitly convertible to `System.Delegate`, and lambda expressions are implicitly convertible to `System.Delegate` and `System.Linq.Expressions.Expression`. This is a breaking change to overload resolution if there exists an overload with a `System.Delegate` or `System.Linq.Expressions.Expression` parameter that is applicable and the closest applicable overload with a strongly-typed delegate parameter is in an enclosing namespace. ```C# class C { static void Main() { var c = new C(); c.M(Main); // C#9: E.M(), C#10: C.M() c.M(() => { }); // C#9: E.M(), C#10: C.M() } void M(System.Delegate d) { } } static class E { public static void M(this object x, System.Action y) { } } ``` 5. In .NET 5 and Visual Studio 16.9 (and earlier), top-level statements could be used in a program containing a type named `Program`. In .NET 6 and Visual Studio 17.0, top-level statements generate a partial declaration of a `Program` class, so any user-defined `Program` type must also be a partial class. ```csharp System.Console.Write("top-level"); Method(); partial class Program { static void Method() { } } ``` 6. https://github.com/dotnet/roslyn/issues/53021 C# will now report an error for a misplaced ```::``` token in explicit interface implementation. In this example code: ``` C# void N::I::M() { } ``` Previous versions of Roslyn wouldn't report any errors. We now report an error for a ```::``` token before M.
1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Compilers/CSharp/Portable/Parser/LanguageParser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; internal partial class LanguageParser : SyntaxParser { // list pools - allocators for lists that are used to build sequences of nodes. The lists // can be reused (hence pooled) since the syntax factory methods don't keep references to // them private readonly SyntaxListPool _pool = new SyntaxListPool(); // Don't need to reset this. private readonly SyntaxFactoryContext _syntaxFactoryContext; // Fields are resettable. private readonly ContextAwareSyntax _syntaxFactory; // Has context, the fields of which are resettable. private int _recursionDepth; private TerminatorState _termState; // Resettable private bool _isInTry; // Resettable private bool _checkedTopLevelStatementsFeatureAvailability; // Resettable // NOTE: If you add new state, you should probably add it to ResetPoint as well. internal LanguageParser( Lexer lexer, CSharp.CSharpSyntaxNode oldTree, IEnumerable<TextChangeRange> changes, LexerMode lexerMode = LexerMode.Syntax, CancellationToken cancellationToken = default(CancellationToken)) : base(lexer, lexerMode, oldTree, changes, allowModeReset: false, preLexIfNotIncremental: true, cancellationToken: cancellationToken) { _syntaxFactoryContext = new SyntaxFactoryContext(); _syntaxFactory = new ContextAwareSyntax(_syntaxFactoryContext); } private static bool IsSomeWord(SyntaxKind kind) { return kind == SyntaxKind.IdentifierToken || SyntaxFacts.IsKeywordKind(kind); } // Parsing rule terminating conditions. This is how we know if it is // okay to abort the current parsing rule when unexpected tokens occur. [Flags] internal enum TerminatorState { EndOfFile = 0, IsNamespaceMemberStartOrStop = 1 << 0, IsAttributeDeclarationTerminator = 1 << 1, IsPossibleAggregateClauseStartOrStop = 1 << 2, IsPossibleMemberStartOrStop = 1 << 3, IsEndOfReturnType = 1 << 4, IsEndOfParameterList = 1 << 5, IsEndOfFieldDeclaration = 1 << 6, IsPossibleEndOfVariableDeclaration = 1 << 7, IsEndOfTypeArgumentList = 1 << 8, IsPossibleStatementStartOrStop = 1 << 9, IsEndOfFixedStatement = 1 << 10, IsEndOfTryBlock = 1 << 11, IsEndOfCatchClause = 1 << 12, IsEndOfFilterClause = 1 << 13, IsEndOfCatchBlock = 1 << 14, IsEndOfDoWhileExpression = 1 << 15, IsEndOfForStatementArgument = 1 << 16, IsEndOfDeclarationClause = 1 << 17, IsEndOfArgumentList = 1 << 18, IsSwitchSectionStart = 1 << 19, IsEndOfTypeParameterList = 1 << 20, IsEndOfMethodSignature = 1 << 21, IsEndOfNameInExplicitInterface = 1 << 22, IsEndOfFunctionPointerParameterList = 1 << 23, IsEndOfFunctionPointerParameterListErrored = 1 << 24, IsEndOfFunctionPointerCallingConvention = 1 << 25, IsEndOfRecordSignature = 1 << 26, } private const int LastTerminatorState = (int)TerminatorState.IsEndOfRecordSignature; private bool IsTerminator() { if (this.CurrentToken.Kind == SyntaxKind.EndOfFileToken) { return true; } for (int i = 1; i <= LastTerminatorState; i <<= 1) { switch (_termState & (TerminatorState)i) { case TerminatorState.IsNamespaceMemberStartOrStop when this.IsNamespaceMemberStartOrStop(): case TerminatorState.IsAttributeDeclarationTerminator when this.IsAttributeDeclarationTerminator(): case TerminatorState.IsPossibleAggregateClauseStartOrStop when this.IsPossibleAggregateClauseStartOrStop(): case TerminatorState.IsPossibleMemberStartOrStop when this.IsPossibleMemberStartOrStop(): case TerminatorState.IsEndOfReturnType when this.IsEndOfReturnType(): case TerminatorState.IsEndOfParameterList when this.IsEndOfParameterList(): case TerminatorState.IsEndOfFieldDeclaration when this.IsEndOfFieldDeclaration(): case TerminatorState.IsPossibleEndOfVariableDeclaration when this.IsPossibleEndOfVariableDeclaration(): case TerminatorState.IsEndOfTypeArgumentList when this.IsEndOfTypeArgumentList(): case TerminatorState.IsPossibleStatementStartOrStop when this.IsPossibleStatementStartOrStop(): case TerminatorState.IsEndOfFixedStatement when this.IsEndOfFixedStatement(): case TerminatorState.IsEndOfTryBlock when this.IsEndOfTryBlock(): case TerminatorState.IsEndOfCatchClause when this.IsEndOfCatchClause(): case TerminatorState.IsEndOfFilterClause when this.IsEndOfFilterClause(): case TerminatorState.IsEndOfCatchBlock when this.IsEndOfCatchBlock(): case TerminatorState.IsEndOfDoWhileExpression when this.IsEndOfDoWhileExpression(): case TerminatorState.IsEndOfForStatementArgument when this.IsEndOfForStatementArgument(): case TerminatorState.IsEndOfDeclarationClause when this.IsEndOfDeclarationClause(): case TerminatorState.IsEndOfArgumentList when this.IsEndOfArgumentList(): case TerminatorState.IsSwitchSectionStart when this.IsPossibleSwitchSection(): case TerminatorState.IsEndOfTypeParameterList when this.IsEndOfTypeParameterList(): case TerminatorState.IsEndOfMethodSignature when this.IsEndOfMethodSignature(): case TerminatorState.IsEndOfNameInExplicitInterface when this.IsEndOfNameInExplicitInterface(): case TerminatorState.IsEndOfFunctionPointerParameterList when this.IsEndOfFunctionPointerParameterList(errored: false): case TerminatorState.IsEndOfFunctionPointerParameterListErrored when this.IsEndOfFunctionPointerParameterList(errored: true): case TerminatorState.IsEndOfFunctionPointerCallingConvention when this.IsEndOfFunctionPointerCallingConvention(): case TerminatorState.IsEndOfRecordSignature when this.IsEndOfRecordSignature(): return true; } } return false; } private static CSharp.CSharpSyntaxNode GetOldParent(CSharp.CSharpSyntaxNode node) { return node != null ? node.Parent : null; } private struct NamespaceBodyBuilder { public SyntaxListBuilder<ExternAliasDirectiveSyntax> Externs; public SyntaxListBuilder<UsingDirectiveSyntax> Usings; public SyntaxListBuilder<AttributeListSyntax> Attributes; public SyntaxListBuilder<MemberDeclarationSyntax> Members; public NamespaceBodyBuilder(SyntaxListPool pool) { Externs = pool.Allocate<ExternAliasDirectiveSyntax>(); Usings = pool.Allocate<UsingDirectiveSyntax>(); Attributes = pool.Allocate<AttributeListSyntax>(); Members = pool.Allocate<MemberDeclarationSyntax>(); } internal void Free(SyntaxListPool pool) { pool.Free(Members); pool.Free(Attributes); pool.Free(Usings); pool.Free(Externs); } } internal CompilationUnitSyntax ParseCompilationUnit() { return ParseWithStackGuard( ParseCompilationUnitCore, () => SyntaxFactory.CompilationUnit( new SyntaxList<ExternAliasDirectiveSyntax>(), new SyntaxList<UsingDirectiveSyntax>(), new SyntaxList<AttributeListSyntax>(), new SyntaxList<MemberDeclarationSyntax>(), SyntaxFactory.Token(SyntaxKind.EndOfFileToken))); } internal CompilationUnitSyntax ParseCompilationUnitCore() { SyntaxToken tmp = null; SyntaxListBuilder initialBadNodes = null; var body = new NamespaceBodyBuilder(_pool); try { this.ParseNamespaceBody(ref tmp, ref body, ref initialBadNodes, SyntaxKind.CompilationUnit); var eof = this.EatToken(SyntaxKind.EndOfFileToken); var result = _syntaxFactory.CompilationUnit(body.Externs, body.Usings, body.Attributes, body.Members, eof); if (initialBadNodes != null) { // attach initial bad nodes as leading trivia on first token result = AddLeadingSkippedSyntax(result, initialBadNodes.ToListNode()); _pool.Free(initialBadNodes); } return result; } finally { body.Free(_pool); } } internal TNode ParseWithStackGuard<TNode>(Func<TNode> parseFunc, Func<TNode> createEmptyNodeFunc) where TNode : CSharpSyntaxNode { // If this value is non-zero then we are nesting calls to ParseWithStackGuard which should not be // happening. It's not a bug but it's inefficient and should be changed. Debug.Assert(_recursionDepth == 0); try { return parseFunc(); } catch (InsufficientExecutionStackException) { return CreateForGlobalFailure(lexer.TextWindow.Position, createEmptyNodeFunc()); } } private TNode CreateForGlobalFailure<TNode>(int position, TNode node) where TNode : CSharpSyntaxNode { // Turn the complete input into a single skipped token. This avoids running the lexer, and therefore // the preprocessor directive parser, which may itself run into the same problem that caused the // original failure. var builder = new SyntaxListBuilder(1); builder.Add(SyntaxFactory.BadToken(null, lexer.TextWindow.Text.ToString(), null)); var fileAsTrivia = _syntaxFactory.SkippedTokensTrivia(builder.ToList<SyntaxToken>()); node = AddLeadingSkippedSyntax(node, fileAsTrivia); ForceEndOfFile(); // force the scanner to report that it is at the end of the input. return AddError(node, position, 0, ErrorCode.ERR_InsufficientStack); } private BaseNamespaceDeclarationSyntax ParseNamespaceDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxListBuilder modifiers) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); var result = ParseNamespaceDeclarationCore(attributeLists, modifiers); _recursionDepth--; return result; } private BaseNamespaceDeclarationSyntax ParseNamespaceDeclarationCore( SyntaxList<AttributeListSyntax> attributeLists, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NamespaceKeyword); var namespaceToken = this.EatToken(SyntaxKind.NamespaceKeyword); if (IsScript) { namespaceToken = this.AddError(namespaceToken, ErrorCode.ERR_NamespaceNotAllowedInScript); } var name = this.ParseQualifiedName(); SyntaxToken openBrace = null; SyntaxToken semicolon = null; if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatToken(SyntaxKind.SemicolonToken); } else if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || IsPossibleNamespaceMemberDeclaration()) { //either we see the brace we expect here or we see something that could come after a brace //so we insert a missing one openBrace = this.EatToken(SyntaxKind.OpenBraceToken); } else { //the next character is neither the brace we expect, nor a token that could follow the expected //brace so we assume it's a mistake and replace it with a missing brace openBrace = this.EatTokenWithPrejudice(SyntaxKind.OpenBraceToken); openBrace = this.ConvertToMissingWithTrailingTrivia(openBrace, SyntaxKind.OpenBraceToken); } Debug.Assert(semicolon != null || openBrace != null); var body = new NamespaceBodyBuilder(_pool); try { if (openBrace == null) { Debug.Assert(semicolon != null); SyntaxListBuilder initialBadNodes = null; this.ParseNamespaceBody(ref semicolon, ref body, ref initialBadNodes, SyntaxKind.FileScopedNamespaceDeclaration); Debug.Assert(initialBadNodes == null); // init bad nodes should have been attached to semicolon... namespaceToken = CheckFeatureAvailability(namespaceToken, MessageID.IDS_FeatureFileScopedNamespace); return _syntaxFactory.FileScopedNamespaceDeclaration( attributeLists, modifiers.ToList(), namespaceToken, name, semicolon, body.Externs, body.Usings, body.Members); } else { SyntaxListBuilder initialBadNodes = null; this.ParseNamespaceBody(ref openBrace, ref body, ref initialBadNodes, SyntaxKind.NamespaceDeclaration); Debug.Assert(initialBadNodes == null); // init bad nodes should have been attached to open brace... return _syntaxFactory.NamespaceDeclaration( attributeLists, modifiers.ToList(), namespaceToken, name, openBrace, body.Externs, body.Usings, body.Members, this.EatToken(SyntaxKind.CloseBraceToken), this.TryEatToken(SyntaxKind.SemicolonToken)); } } finally { body.Free(_pool); } } private static bool IsPossibleStartOfTypeDeclaration(SyntaxKind kind) { switch (kind) { case SyntaxKind.EnumKeyword: case SyntaxKind.DelegateKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.StructKeyword: case SyntaxKind.AbstractKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.NewKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PublicKeyword: case SyntaxKind.SealedKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.OpenBracketToken: return true; default: return false; } } private void AddSkippedNamespaceText( ref SyntaxToken openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes, CSharpSyntaxNode skippedSyntax) { if (body.Members.Count > 0) { AddTrailingSkippedSyntax(body.Members, skippedSyntax); } else if (body.Attributes.Count > 0) { AddTrailingSkippedSyntax(body.Attributes, skippedSyntax); } else if (body.Usings.Count > 0) { AddTrailingSkippedSyntax(body.Usings, skippedSyntax); } else if (body.Externs.Count > 0) { AddTrailingSkippedSyntax(body.Externs, skippedSyntax); } else if (openBraceOrSemicolon != null) { openBraceOrSemicolon = AddTrailingSkippedSyntax(openBraceOrSemicolon, skippedSyntax); } else { if (initialBadNodes == null) { initialBadNodes = _pool.Allocate(); } initialBadNodes.AddRange(skippedSyntax); } } // Parts of a namespace declaration in the order they can be defined. private enum NamespaceParts { None = 0, ExternAliases = 1, Usings = 2, GlobalAttributes = 3, MembersAndStatements = 4, TypesAndNamespaces = 5, TopLevelStatementsAfterTypesAndNamespaces = 6, } private void ParseNamespaceBody(ref SyntaxToken openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes, SyntaxKind parentKind) { // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); bool isGlobal = openBraceOrSemicolon == null; var saveTerm = _termState; _termState |= TerminatorState.IsNamespaceMemberStartOrStop; NamespaceParts seen = NamespaceParts.None; var pendingIncompleteMembers = _pool.Allocate<MemberDeclarationSyntax>(); bool reportUnexpectedToken = true; try { while (true) { switch (this.CurrentToken.Kind) { case SyntaxKind.NamespaceKeyword: // incomplete members must be processed before we add any nodes to the body: AddIncompleteMembers(ref pendingIncompleteMembers, ref body); var attributeLists = _pool.Allocate<AttributeListSyntax>(); var modifiers = _pool.Allocate(); body.Members.Add(adjustStateAndReportStatementOutOfOrder(ref seen, this.ParseNamespaceDeclaration(attributeLists, modifiers))); _pool.Free(attributeLists); _pool.Free(modifiers); reportUnexpectedToken = true; break; case SyntaxKind.CloseBraceToken: // A very common user error is to type an additional } // somewhere in the file. This will cause us to stop parsing // the root (global) namespace too early and will make the // rest of the file unparseable and unusable by intellisense. // We detect that case here and we skip the close curly and // continue parsing as if we did not see the } if (isGlobal) { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); var token = this.EatToken(); token = this.AddError(token, IsScript ? ErrorCode.ERR_GlobalDefinitionOrStatementExpected : ErrorCode.ERR_EOFExpected); this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, token); reportUnexpectedToken = true; break; } else { // This token marks the end of a namespace body return; } case SyntaxKind.EndOfFileToken: // This token marks the end of a namespace body return; case SyntaxKind.ExternKeyword: if (isGlobal && !ScanExternAliasDirective()) { // extern member or a local function goto default; } else { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); var @extern = ParseExternAliasDirective(); if (seen > NamespaceParts.ExternAliases) { @extern = this.AddErrorToFirstToken(@extern, ErrorCode.ERR_ExternAfterElements); this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, @extern); } else { body.Externs.Add(@extern); seen = NamespaceParts.ExternAliases; } reportUnexpectedToken = true; break; } case SyntaxKind.UsingKeyword: if (isGlobal && (this.PeekToken(1).Kind == SyntaxKind.OpenParenToken || (!IsScript && IsPossibleTopLevelUsingLocalDeclarationStatement()))) { // Top-level using statement or using local declaration goto default; } else { parseUsingDirective(ref openBraceOrSemicolon, ref body, ref initialBadNodes, ref seen, ref pendingIncompleteMembers); } reportUnexpectedToken = true; break; case SyntaxKind.IdentifierToken: if (this.CurrentToken.ContextualKind != SyntaxKind.GlobalKeyword || this.PeekToken(1).Kind != SyntaxKind.UsingKeyword) { goto default; } else { parseUsingDirective(ref openBraceOrSemicolon, ref body, ref initialBadNodes, ref seen, ref pendingIncompleteMembers); } reportUnexpectedToken = true; break; case SyntaxKind.OpenBracketToken: if (this.IsPossibleGlobalAttributeDeclaration()) { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); var attribute = this.ParseAttributeDeclaration(); if (!isGlobal || seen > NamespaceParts.GlobalAttributes) { attribute = this.AddError(attribute, attribute.Target.Identifier, ErrorCode.ERR_GlobalAttributesNotFirst); this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, attribute); } else { body.Attributes.Add(attribute); seen = NamespaceParts.GlobalAttributes; } reportUnexpectedToken = true; break; } goto default; default: var memberOrStatement = isGlobal ? this.ParseMemberDeclarationOrStatement(parentKind) : this.ParseMemberDeclaration(parentKind); if (memberOrStatement == null) { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); // eat one token and try to parse declaration or statement again: var skippedToken = EatToken(); if (reportUnexpectedToken && !skippedToken.ContainsDiagnostics) { skippedToken = this.AddError(skippedToken, IsScript ? ErrorCode.ERR_GlobalDefinitionOrStatementExpected : ErrorCode.ERR_EOFExpected); // do not report the error multiple times for subsequent tokens: reportUnexpectedToken = false; } this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, skippedToken); } else if (memberOrStatement.Kind == SyntaxKind.IncompleteMember && seen < NamespaceParts.MembersAndStatements) { pendingIncompleteMembers.Add(memberOrStatement); reportUnexpectedToken = true; } else { // incomplete members must be processed before we add any nodes to the body: AddIncompleteMembers(ref pendingIncompleteMembers, ref body); body.Members.Add(adjustStateAndReportStatementOutOfOrder(ref seen, memberOrStatement)); reportUnexpectedToken = true; } break; } } } finally { _termState = saveTerm; // adds pending incomplete nodes: AddIncompleteMembers(ref pendingIncompleteMembers, ref body); _pool.Free(pendingIncompleteMembers); } MemberDeclarationSyntax adjustStateAndReportStatementOutOfOrder(ref NamespaceParts seen, MemberDeclarationSyntax memberOrStatement) { switch (memberOrStatement.Kind) { case SyntaxKind.GlobalStatement: if (seen < NamespaceParts.MembersAndStatements) { seen = NamespaceParts.MembersAndStatements; } else if (seen == NamespaceParts.TypesAndNamespaces) { seen = NamespaceParts.TopLevelStatementsAfterTypesAndNamespaces; if (!IsScript) { memberOrStatement = this.AddError(memberOrStatement, ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType); } } break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: if (seen < NamespaceParts.TypesAndNamespaces) { seen = NamespaceParts.TypesAndNamespaces; } break; default: if (seen < NamespaceParts.MembersAndStatements) { seen = NamespaceParts.MembersAndStatements; } break; } return memberOrStatement; } void parseUsingDirective(ref SyntaxToken openBrace, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes, ref NamespaceParts seen, ref SyntaxListBuilder<MemberDeclarationSyntax> pendingIncompleteMembers) { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBrace, ref body, ref initialBadNodes); var @using = this.ParseUsingDirective(); if (seen > NamespaceParts.Usings) { @using = this.AddError(@using, ErrorCode.ERR_UsingAfterElements); this.AddSkippedNamespaceText(ref openBrace, ref body, ref initialBadNodes, @using); } else { body.Usings.Add(@using); seen = NamespaceParts.Usings; } } } private GlobalStatementSyntax CheckTopLevelStatementsFeatureAvailability(GlobalStatementSyntax globalStatementSyntax) { if (IsScript || _checkedTopLevelStatementsFeatureAvailability) { return globalStatementSyntax; } _checkedTopLevelStatementsFeatureAvailability = true; return CheckFeatureAvailability(globalStatementSyntax, MessageID.IDS_TopLevelStatements); } private static void AddIncompleteMembers(ref SyntaxListBuilder<MemberDeclarationSyntax> incompleteMembers, ref NamespaceBodyBuilder body) { if (incompleteMembers.Count > 0) { body.Members.AddRange(incompleteMembers); incompleteMembers.Clear(); } } private void ReduceIncompleteMembers( ref SyntaxListBuilder<MemberDeclarationSyntax> incompleteMembers, ref SyntaxToken openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes) { for (int i = 0; i < incompleteMembers.Count; i++) { this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, incompleteMembers[i]); } incompleteMembers.Clear(); } private bool IsPossibleNamespaceMemberDeclaration() { switch (this.CurrentToken.Kind) { case SyntaxKind.ExternKeyword: case SyntaxKind.UsingKeyword: case SyntaxKind.NamespaceKeyword: return true; case SyntaxKind.IdentifierToken: return IsPartialInNamespaceMemberDeclaration(); default: return IsPossibleStartOfTypeDeclaration(this.CurrentToken.Kind); } } private bool IsPartialInNamespaceMemberDeclaration() { if (this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword) { if (this.IsPartialType()) { return true; } else if (this.PeekToken(1).Kind == SyntaxKind.NamespaceKeyword) { return true; } } return false; } public bool IsEndOfNamespace() { return this.CurrentToken.Kind == SyntaxKind.CloseBraceToken; } public bool IsGobalAttributesTerminator() { return this.IsEndOfNamespace() || this.IsPossibleNamespaceMemberDeclaration(); } private bool IsNamespaceMemberStartOrStop() { return this.IsEndOfNamespace() || this.IsPossibleNamespaceMemberDeclaration(); } /// <summary> /// Returns true if the lookahead tokens compose extern alias directive. /// </summary> private bool ScanExternAliasDirective() { // The check also includes the ending semicolon so that we can disambiguate among: // extern alias goo; // extern alias goo(); // extern alias goo { get; } return this.CurrentToken.Kind == SyntaxKind.ExternKeyword && this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).ContextualKind == SyntaxKind.AliasKeyword && this.PeekToken(2).Kind == SyntaxKind.IdentifierToken && this.PeekToken(3).Kind == SyntaxKind.SemicolonToken; } private ExternAliasDirectiveSyntax ParseExternAliasDirective() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.ExternAliasDirective) { return (ExternAliasDirectiveSyntax)this.EatNode(); } Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ExternKeyword); var externToken = this.EatToken(SyntaxKind.ExternKeyword); var aliasToken = this.EatContextualToken(SyntaxKind.AliasKeyword); externToken = CheckFeatureAvailability(externToken, MessageID.IDS_FeatureExternAlias); var name = this.ParseIdentifierToken(); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.ExternAliasDirective(externToken, aliasToken, name, semicolon); } private NameEqualsSyntax ParseNameEquals() { Debug.Assert(this.IsNamedAssignment()); return _syntaxFactory.NameEquals( _syntaxFactory.IdentifierName(this.ParseIdentifierToken()), this.EatToken(SyntaxKind.EqualsToken)); } private UsingDirectiveSyntax ParseUsingDirective() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.UsingDirective) { return (UsingDirectiveSyntax)this.EatNode(); } SyntaxToken globalToken = null; if (this.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword) { globalToken = ConvertToKeyword(this.EatToken()); } Debug.Assert(this.CurrentToken.Kind == SyntaxKind.UsingKeyword); var usingToken = this.EatToken(SyntaxKind.UsingKeyword); var staticToken = this.TryEatToken(SyntaxKind.StaticKeyword); var alias = this.IsNamedAssignment() ? ParseNameEquals() : null; NameSyntax name; SyntaxToken semicolon; if (IsPossibleNamespaceMemberDeclaration()) { //We're worried about the case where someone already has a correct program //and they've gone back to add a using directive, but have not finished the //new directive. e.g. // // using // namespace Goo { // //... // } // //If the token we see after "using" could be its own top-level construct, then //we just want to insert a missing identifier and semicolon and then return to //parsing at the top-level. // //NB: there's no way this could be true for a set of tokens that form a valid //using directive, so there's no danger in checking the error case first. name = WithAdditionalDiagnostics(CreateMissingIdentifierName(), GetExpectedTokenError(SyntaxKind.IdentifierToken, this.CurrentToken.Kind)); semicolon = SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken); } else { name = this.ParseQualifiedName(); if (name.IsMissing && this.PeekToken(1).Kind == SyntaxKind.SemicolonToken) { //if we can see a semicolon ahead, then the current token was //probably supposed to be an identifier name = AddTrailingSkippedSyntax(name, this.EatToken()); } semicolon = this.EatToken(SyntaxKind.SemicolonToken); } var usingDirective = _syntaxFactory.UsingDirective(globalToken, usingToken, staticToken, alias, name, semicolon); if (staticToken != null) { usingDirective = CheckFeatureAvailability(usingDirective, MessageID.IDS_FeatureUsingStatic); } if (globalToken != null) { usingDirective = CheckFeatureAvailability(usingDirective, MessageID.IDS_FeatureGlobalUsing); } return usingDirective; } private bool IsPossibleGlobalAttributeDeclaration() { return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken && IsGlobalAttributeTarget(this.PeekToken(1)) && this.PeekToken(2).Kind == SyntaxKind.ColonToken; } private static bool IsGlobalAttributeTarget(SyntaxToken token) { switch (token.ToAttributeLocation()) { case AttributeLocation.Assembly: case AttributeLocation.Module: return true; default: return false; } } private bool IsPossibleAttributeDeclaration() { return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken; } private SyntaxList<AttributeListSyntax> ParseAttributeDeclarations() { var attributes = _pool.Allocate<AttributeListSyntax>(); try { var saveTerm = _termState; _termState |= TerminatorState.IsAttributeDeclarationTerminator; while (this.IsPossibleAttributeDeclaration()) { var attribute = this.ParseAttributeDeclaration(); attributes.Add(attribute); } _termState = saveTerm; return attributes.ToList(); } finally { _pool.Free(attributes); } } private bool IsAttributeDeclarationTerminator() { return this.CurrentToken.Kind == SyntaxKind.CloseBracketToken || this.IsPossibleAttributeDeclaration(); // start of a new one... } private AttributeListSyntax ParseAttributeDeclaration() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.AttributeList) { return (AttributeListSyntax)this.EatNode(); } var openBracket = this.EatToken(SyntaxKind.OpenBracketToken); // Check for optional location : AttributeTargetSpecifierSyntax attrLocation = null; if (IsSomeWord(this.CurrentToken.Kind) && this.PeekToken(1).Kind == SyntaxKind.ColonToken) { var id = ConvertToKeyword(this.EatToken()); var colon = this.EatToken(SyntaxKind.ColonToken); attrLocation = _syntaxFactory.AttributeTargetSpecifier(id, colon); } var attributes = _pool.AllocateSeparated<AttributeSyntax>(); try { if (attrLocation != null && attrLocation.Identifier.ToAttributeLocation() == AttributeLocation.Module) { attrLocation = CheckFeatureAvailability(attrLocation, MessageID.IDS_FeatureModuleAttrLoc); } this.ParseAttributes(attributes); var closeBracket = this.EatToken(SyntaxKind.CloseBracketToken); var declaration = _syntaxFactory.AttributeList(openBracket, attrLocation, attributes, closeBracket); return declaration; } finally { _pool.Free(attributes); } } private void ParseAttributes(SeparatedSyntaxListBuilder<AttributeSyntax> nodes) { // always expect at least one attribute nodes.Add(this.ParseAttribute()); // remaining attributes while (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { // comma is optional, but if it is present it may be followed by another attribute nodes.AddSeparator(this.EatToken()); // check for legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBracketToken) { break; } nodes.Add(this.ParseAttribute()); } else if (this.IsPossibleAttribute()) { // report missing comma nodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); nodes.Add(this.ParseAttribute()); } else if (this.SkipBadAttributeListTokens(nodes, SyntaxKind.IdentifierToken) == PostSkipAction.Abort) { break; } } } private PostSkipAction SkipBadAttributeListTokens(SeparatedSyntaxListBuilder<AttributeSyntax> list, SyntaxKind expected) { Debug.Assert(list.Count > 0); SyntaxToken tmp = null; return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttribute(), p => p.CurrentToken.Kind == SyntaxKind.CloseBracketToken || p.IsTerminator(), expected); } private bool IsPossibleAttribute() { return this.IsTrueIdentifier(); } private AttributeSyntax ParseAttribute() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.Attribute) { return (AttributeSyntax)this.EatNode(); } var name = this.ParseQualifiedName(); var argList = this.ParseAttributeArgumentList(); return _syntaxFactory.Attribute(name, argList); } internal AttributeArgumentListSyntax ParseAttributeArgumentList() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.AttributeArgumentList) { return (AttributeArgumentListSyntax)this.EatNode(); } AttributeArgumentListSyntax argList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var openParen = this.EatToken(SyntaxKind.OpenParenToken); var argNodes = _pool.AllocateSeparated<AttributeArgumentSyntax>(); try { tryAgain: if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { if (this.IsPossibleAttributeArgument() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument argNodes.Add(this.ParseAttributeArgument()); // comma + argument or end? int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleAttributeArgument()) { argNodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); argNodes.Add(this.ParseAttributeArgument()); } else if (this.SkipBadAttributeArgumentTokens(ref openParen, argNodes, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadAttributeArgumentTokens(ref openParen, argNodes, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); argList = _syntaxFactory.AttributeArgumentList(openParen, argNodes, closeParen); } finally { _pool.Free(argNodes); } } return argList; } private PostSkipAction SkipBadAttributeArgumentTokens(ref SyntaxToken openParen, SeparatedSyntaxListBuilder<AttributeArgumentSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openParen, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttributeArgument(), p => p.CurrentToken.Kind == SyntaxKind.CloseParenToken || p.IsTerminator(), expected); } private bool IsPossibleAttributeArgument() { return this.IsPossibleExpression(); } private AttributeArgumentSyntax ParseAttributeArgument() { // Need to parse both "real" named arguments and attribute-style named arguments. // We track attribute-style named arguments only with fShouldHaveName. NameEqualsSyntax nameEquals = null; NameColonSyntax nameColon = null; if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken) { SyntaxKind nextTokenKind = this.PeekToken(1).Kind; switch (nextTokenKind) { case SyntaxKind.EqualsToken: { var name = this.ParseIdentifierToken(); var equals = this.EatToken(SyntaxKind.EqualsToken); nameEquals = _syntaxFactory.NameEquals(_syntaxFactory.IdentifierName(name), equals); } break; case SyntaxKind.ColonToken: { var name = this.ParseIdentifierName(); var colonToken = this.EatToken(SyntaxKind.ColonToken); nameColon = _syntaxFactory.NameColon(name, colonToken); nameColon = CheckFeatureAvailability(nameColon, MessageID.IDS_FeatureNamedArgument); } break; } } return _syntaxFactory.AttributeArgument( nameEquals, nameColon, this.ParseExpressionCore()); } private static DeclarationModifiers GetModifier(SyntaxToken token) => GetModifier(token.Kind, token.ContextualKind); internal static DeclarationModifiers GetModifier(SyntaxKind kind, SyntaxKind contextualKind) { switch (kind) { case SyntaxKind.PublicKeyword: return DeclarationModifiers.Public; case SyntaxKind.InternalKeyword: return DeclarationModifiers.Internal; case SyntaxKind.ProtectedKeyword: return DeclarationModifiers.Protected; case SyntaxKind.PrivateKeyword: return DeclarationModifiers.Private; case SyntaxKind.SealedKeyword: return DeclarationModifiers.Sealed; case SyntaxKind.AbstractKeyword: return DeclarationModifiers.Abstract; case SyntaxKind.StaticKeyword: return DeclarationModifiers.Static; case SyntaxKind.VirtualKeyword: return DeclarationModifiers.Virtual; case SyntaxKind.ExternKeyword: return DeclarationModifiers.Extern; case SyntaxKind.NewKeyword: return DeclarationModifiers.New; case SyntaxKind.OverrideKeyword: return DeclarationModifiers.Override; case SyntaxKind.ReadOnlyKeyword: return DeclarationModifiers.ReadOnly; case SyntaxKind.VolatileKeyword: return DeclarationModifiers.Volatile; case SyntaxKind.UnsafeKeyword: return DeclarationModifiers.Unsafe; case SyntaxKind.PartialKeyword: return DeclarationModifiers.Partial; case SyntaxKind.AsyncKeyword: return DeclarationModifiers.Async; case SyntaxKind.RefKeyword: return DeclarationModifiers.Ref; case SyntaxKind.IdentifierToken: switch (contextualKind) { case SyntaxKind.PartialKeyword: return DeclarationModifiers.Partial; case SyntaxKind.AsyncKeyword: return DeclarationModifiers.Async; } goto default; default: return DeclarationModifiers.None; } } private void ParseModifiers(SyntaxListBuilder tokens, bool forAccessors) { while (true) { var newMod = GetModifier(this.CurrentToken); if (newMod == DeclarationModifiers.None) { break; } SyntaxToken modTok; switch (newMod) { case DeclarationModifiers.Partial: var nextToken = PeekToken(1); var isPartialType = this.IsPartialType(); var isPartialMember = this.IsPartialMember(); if (isPartialType || isPartialMember) { // Standard legal cases. modTok = ConvertToKeyword(this.EatToken()); modTok = CheckFeatureAvailability(modTok, isPartialType ? MessageID.IDS_FeaturePartialTypes : MessageID.IDS_FeaturePartialMethod); } else if (nextToken.Kind == SyntaxKind.NamespaceKeyword) { // Error reported in binding modTok = ConvertToKeyword(this.EatToken()); } else if ( nextToken.Kind == SyntaxKind.EnumKeyword || nextToken.Kind == SyntaxKind.DelegateKeyword || (IsPossibleStartOfTypeDeclaration(nextToken.Kind) && GetModifier(nextToken) != DeclarationModifiers.None)) { // Misplaced partial // TODO(https://github.com/dotnet/roslyn/issues/22439): // We should consider moving this check into binding, but avoid holding on to trees modTok = AddError(ConvertToKeyword(this.EatToken()), ErrorCode.ERR_PartialMisplaced); } else { return; } break; case DeclarationModifiers.Ref: // 'ref' is only a modifier if used on a ref struct // it must be either immediately before the 'struct' // keyword, or immediately before 'partial struct' if // this is a partial ref struct declaration { var next = PeekToken(1); if (isStructOrRecordKeyword(next) || (next.ContextualKind == SyntaxKind.PartialKeyword && isStructOrRecordKeyword(PeekToken(2)))) { modTok = this.EatToken(); modTok = CheckFeatureAvailability(modTok, MessageID.IDS_FeatureRefStructs); } else if (forAccessors && this.IsPossibleAccessorModifier()) { // Accept ref as a modifier for properties and event accessors, to produce an error later during binding. modTok = this.EatToken(); } else { return; } break; } case DeclarationModifiers.Async: if (!ShouldAsyncBeTreatedAsModifier(parsingStatementNotDeclaration: false)) { return; } modTok = ConvertToKeyword(this.EatToken()); modTok = CheckFeatureAvailability(modTok, MessageID.IDS_FeatureAsync); break; default: modTok = this.EatToken(); break; } tokens.Add(modTok); } bool isStructOrRecordKeyword(SyntaxToken token) { if (token.Kind == SyntaxKind.StructKeyword) { return true; } if (token.ContextualKind == SyntaxKind.RecordKeyword) { // This is an unusual use of LangVersion. Normally we only produce errors when the langversion // does not support a feature, but in this case we are effectively making a language breaking // change to consider "record" a type declaration in all ambiguous cases. To avoid breaking // older code that is not using C# 9 we conditionally parse based on langversion return IsFeatureEnabled(MessageID.IDS_FeatureRecords); } return false; } } private bool ShouldAsyncBeTreatedAsModifier(bool parsingStatementNotDeclaration) { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword); // Adapted from CParser::IsAsyncMethod. if (IsNonContextualModifier(PeekToken(1))) { // If the next token is a (non-contextual) modifier keyword, then this token is // definitely the async keyword return true; } // Some of our helpers start at the current token, so we'll have to advance for their // sake and then backtrack when we're done. Don't leave this block without releasing // the reset point. ResetPoint resetPoint = GetResetPoint(); try { this.EatToken(); //move past contextual 'async' if (!parsingStatementNotDeclaration && (this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword)) { this.EatToken(); // "partial" doesn't affect our decision, so look past it. } // Comment directly from CParser::IsAsyncMethod. // ... 'async' [partial] <typedecl> ... // ... 'async' [partial] <event> ... // ... 'async' [partial] <implicit> <operator> ... // ... 'async' [partial] <explicit> <operator> ... // ... 'async' [partial] <typename> <operator> ... // ... 'async' [partial] <typename> <membername> ... // DEVNOTE: Although we parse async user defined conversions, operators, etc. here, // anything other than async methods are detected as erroneous later, during the define phase if (!parsingStatementNotDeclaration) { var ctk = this.CurrentToken.Kind; if (IsPossibleStartOfTypeDeclaration(ctk) || ctk == SyntaxKind.EventKeyword || ((ctk == SyntaxKind.ExplicitKeyword || ctk == SyntaxKind.ImplicitKeyword) && PeekToken(1).Kind == SyntaxKind.OperatorKeyword)) { return true; } } if (ScanType() != ScanTypeFlags.NotType) { // We've seen "async TypeName". Now we have to determine if we should we treat // 'async' as a modifier. Or is the user actually writing something like // "public async Goo" where 'async' is actually the return type. if (IsPossibleMemberName()) { // we have: "async Type X" or "async Type this", 'async' is definitely a // modifier here. return true; } var currentTokenKind = this.CurrentToken.Kind; // The file ends with "async TypeName", it's not legal code, and it's much // more likely that this is meant to be a modifier. if (currentTokenKind == SyntaxKind.EndOfFileToken) { return true; } // "async TypeName }". In this case, we just have an incomplete member, and // we should definitely default to 'async' being considered a return type here. if (currentTokenKind == SyntaxKind.CloseBraceToken) { return true; } // "async TypeName void". In this case, we just have an incomplete member before // an existing member. Treat this 'async' as a keyword. if (SyntaxFacts.IsPredefinedType(this.CurrentToken.Kind)) { return true; } // "async TypeName public". In this case, we just have an incomplete member before // an existing member. Treat this 'async' as a keyword. if (IsNonContextualModifier(this.CurrentToken)) { return true; } // "async TypeName class". In this case, we just have an incomplete member before // an existing type declaration. Treat this 'async' as a keyword. if (IsTypeDeclarationStart()) { return true; } // "async TypeName namespace". In this case, we just have an incomplete member before // an existing namespace declaration. Treat this 'async' as a keyword. if (currentTokenKind == SyntaxKind.NamespaceKeyword) { return true; } if (!parsingStatementNotDeclaration && currentTokenKind == SyntaxKind.OperatorKeyword) { return true; } } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } return false; } private static bool IsNonContextualModifier(SyntaxToken nextToken) { return GetModifier(nextToken) != DeclarationModifiers.None && !SyntaxFacts.IsContextualKeyword(nextToken.ContextualKind); } private bool IsPartialType() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword); var nextToken = this.PeekToken(1); switch (nextToken.Kind) { case SyntaxKind.StructKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.InterfaceKeyword: return true; } if (nextToken.ContextualKind == SyntaxKind.RecordKeyword) { // This is an unusual use of LangVersion. Normally we only produce errors when the langversion // does not support a feature, but in this case we are effectively making a language breaking // change to consider "record" a type declaration in all ambiguous cases. To avoid breaking // older code that is not using C# 9 we conditionally parse based on langversion return IsFeatureEnabled(MessageID.IDS_FeatureRecords); } return false; } private bool IsPartialMember() { // note(cyrusn): this could have been written like so: // // return // this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword && // this.PeekToken(1).Kind == SyntaxKind.VoidKeyword; // // However, we want to be lenient and allow the user to write // 'partial' in most modifier lists. We will then provide them with // a more specific message later in binding that they are doing // something wrong. // // Some might argue that the simple check would suffice. // However, we'd like to maintain behavior with // previously shipped versions, and so we're keeping this code. // Here we check for: // partial ReturnType MemberName Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword); var point = this.GetResetPoint(); try { this.EatToken(); // partial if (this.ScanType() == ScanTypeFlags.NotType) { return false; } return IsPossibleMemberName(); } finally { this.Reset(ref point); this.Release(ref point); } } private bool IsPossibleMemberName() { switch (this.CurrentToken.Kind) { case SyntaxKind.IdentifierToken: if (this.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword && this.PeekToken(1).Kind == SyntaxKind.UsingKeyword) { return false; } return true; case SyntaxKind.ThisKeyword: return true; default: return false; } } private MemberDeclarationSyntax ParseTypeDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); cancellationToken.ThrowIfCancellationRequested(); switch (this.CurrentToken.Kind) { case SyntaxKind.ClassKeyword: // report use of "static class" if feature is unsupported CheckForVersionSpecificModifiers(modifiers, SyntaxKind.StaticKeyword, MessageID.IDS_FeatureStaticClasses); return this.ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers); case SyntaxKind.StructKeyword: // report use of "readonly struct" if feature is unsupported CheckForVersionSpecificModifiers(modifiers, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyStructs); return this.ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers); case SyntaxKind.InterfaceKeyword: return this.ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers); case SyntaxKind.DelegateKeyword: return this.ParseDelegateDeclaration(attributes, modifiers); case SyntaxKind.EnumKeyword: return this.ParseEnumDeclaration(attributes, modifiers); case SyntaxKind.IdentifierToken: Debug.Assert(CurrentToken.ContextualKind == SyntaxKind.RecordKeyword); return ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers); default: throw ExceptionUtilities.UnexpectedValue(this.CurrentToken.Kind); } } /// <summary> /// checks for modifiers whose feature is not available /// </summary> private void CheckForVersionSpecificModifiers(SyntaxListBuilder modifiers, SyntaxKind kind, MessageID feature) { for (int i = 0, n = modifiers.Count; i < n; i++) { if (modifiers[i].RawKind == (int)kind) { modifiers[i] = CheckFeatureAvailability(modifiers[i], feature); } } } #nullable enable private TypeDeclarationSyntax ParseClassOrStructOrInterfaceDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ClassKeyword || this.CurrentToken.Kind == SyntaxKind.StructKeyword || this.CurrentToken.Kind == SyntaxKind.InterfaceKeyword || CurrentToken.ContextualKind == SyntaxKind.RecordKeyword); // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); var keyword = ConvertToKeyword(this.EatToken()); var outerSaveTerm = _termState; SyntaxToken? recordModifier = null; if (keyword.Kind == SyntaxKind.RecordKeyword) { _termState |= TerminatorState.IsEndOfRecordSignature; recordModifier = eatRecordModifierIfAvailable(); } var saveTerm = _termState; _termState |= TerminatorState.IsPossibleAggregateClauseStartOrStop; var name = this.ParseIdentifierToken(); var typeParameters = this.ParseTypeParameterList(); var paramList = keyword.Kind == SyntaxKind.RecordKeyword && CurrentToken.Kind == SyntaxKind.OpenParenToken ? ParseParenthesizedParameterList() : null; var baseList = this.ParseBaseList(); _termState = saveTerm; // Parse class body bool parseMembers = true; SyntaxListBuilder<MemberDeclarationSyntax> members = default; SyntaxListBuilder<TypeParameterConstraintClauseSyntax> constraints = default; try { if (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { constraints = _pool.Allocate<TypeParameterConstraintClauseSyntax>(); this.ParseTypeParameterConstraintClauses(constraints); } _termState = outerSaveTerm; SyntaxToken semicolon; SyntaxToken? openBrace; SyntaxToken? closeBrace; if (!(keyword.Kind == SyntaxKind.RecordKeyword) || CurrentToken.Kind != SyntaxKind.SemicolonToken) { openBrace = this.EatToken(SyntaxKind.OpenBraceToken); // ignore members if missing type name or missing open curly if (name.IsMissing || openBrace.IsMissing) { parseMembers = false; } // even if we saw a { or think we should parse members bail out early since // we know namespaces can't be nested inside types if (parseMembers) { members = _pool.Allocate<MemberDeclarationSyntax>(); while (true) { SyntaxKind kind = this.CurrentToken.Kind; if (CanStartMember(kind)) { // This token can start a member -- go parse it var saveTerm2 = _termState; _termState |= TerminatorState.IsPossibleMemberStartOrStop; var member = this.ParseMemberDeclaration(keyword.Kind); if (member != null) { // statements are accepted here, a semantic error will be reported later members.Add(member); } else { // we get here if we couldn't parse the lookahead as a statement or a declaration (we haven't consumed any tokens): this.SkipBadMemberListTokens(ref openBrace, members); } _termState = saveTerm2; } else if (kind == SyntaxKind.CloseBraceToken || kind == SyntaxKind.EndOfFileToken || this.IsTerminator()) { // This marks the end of members of this class break; } else { // Error -- try to sync up with intended reality this.SkipBadMemberListTokens(ref openBrace, members); } } } if (openBrace.IsMissing) { closeBrace = SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken); closeBrace = WithAdditionalDiagnostics(closeBrace, this.GetExpectedTokenError(SyntaxKind.CloseBraceToken, this.CurrentToken.Kind)); } else { closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); } semicolon = TryEatToken(SyntaxKind.SemicolonToken); } else { semicolon = CheckFeatureAvailability(EatToken(SyntaxKind.SemicolonToken), MessageID.IDS_FeatureRecords); openBrace = null; closeBrace = null; } return constructTypeDeclaration(_syntaxFactory, attributes, modifiers, keyword, recordModifier, name, typeParameters, paramList, baseList, constraints, openBrace, members, closeBrace, semicolon); } finally { if (!members.IsNull) { _pool.Free(members); } if (!constraints.IsNull) { _pool.Free(constraints); } } SyntaxToken? eatRecordModifierIfAvailable() { Debug.Assert(keyword.Kind == SyntaxKind.RecordKeyword); if (CurrentToken.Kind is SyntaxKind.ClassKeyword or SyntaxKind.StructKeyword) { var result = EatToken(); result = CheckFeatureAvailability(result, MessageID.IDS_FeatureRecordStructs); return result; } return null; } static TypeDeclarationSyntax constructTypeDeclaration(ContextAwareSyntax syntaxFactory, SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxToken keyword, SyntaxToken? recordModifier, SyntaxToken name, TypeParameterListSyntax typeParameters, ParameterListSyntax? paramList, BaseListSyntax baseList, SyntaxListBuilder<TypeParameterConstraintClauseSyntax> constraints, SyntaxToken? openBrace, SyntaxListBuilder<MemberDeclarationSyntax> members, SyntaxToken? closeBrace, SyntaxToken semicolon) { var modifiersList = (SyntaxList<SyntaxToken>)modifiers.ToList(); var membersList = (SyntaxList<MemberDeclarationSyntax>)members; var constraintsList = (SyntaxList<TypeParameterConstraintClauseSyntax>)constraints; switch (keyword.Kind) { case SyntaxKind.ClassKeyword: RoslynDebug.Assert(paramList is null); RoslynDebug.Assert(openBrace != null); RoslynDebug.Assert(closeBrace != null); return syntaxFactory.ClassDeclaration( attributes, modifiersList, keyword, name, typeParameters, baseList, constraintsList, openBrace, membersList, closeBrace, semicolon); case SyntaxKind.StructKeyword: RoslynDebug.Assert(paramList is null); RoslynDebug.Assert(openBrace != null); RoslynDebug.Assert(closeBrace != null); return syntaxFactory.StructDeclaration( attributes, modifiersList, keyword, name, typeParameters, baseList, constraintsList, openBrace, membersList, closeBrace, semicolon); case SyntaxKind.InterfaceKeyword: RoslynDebug.Assert(paramList is null); RoslynDebug.Assert(openBrace != null); RoslynDebug.Assert(closeBrace != null); return syntaxFactory.InterfaceDeclaration( attributes, modifiersList, keyword, name, typeParameters, baseList, constraintsList, openBrace, membersList, closeBrace, semicolon); case SyntaxKind.RecordKeyword: // record struct ... // record ... // record class ... SyntaxKind declarationKind = recordModifier?.Kind == SyntaxKind.StructKeyword ? SyntaxKind.RecordStructDeclaration : SyntaxKind.RecordDeclaration; return syntaxFactory.RecordDeclaration( declarationKind, attributes, modifiers.ToList(), keyword, classOrStructKeyword: recordModifier, name, typeParameters, paramList, baseList, constraints, openBrace, members, closeBrace, semicolon); default: throw ExceptionUtilities.UnexpectedValue(keyword.Kind); } } } #nullable disable private void SkipBadMemberListTokens(ref SyntaxToken openBrace, SyntaxListBuilder members) { if (members.Count > 0) { var tmp = members[members.Count - 1]; this.SkipBadMemberListTokens(ref tmp); members[members.Count - 1] = tmp; } else { GreenNode tmp = openBrace; this.SkipBadMemberListTokens(ref tmp); openBrace = (SyntaxToken)tmp; } } private void SkipBadMemberListTokens(ref GreenNode previousNode) { int curlyCount = 0; var tokens = _pool.Allocate(); try { bool done = false; // always consume at least one token. var token = this.EatToken(); token = this.AddError(token, ErrorCode.ERR_InvalidMemberDecl, token.Text); tokens.Add(token); while (!done) { SyntaxKind kind = this.CurrentToken.Kind; // If this token can start a member, we're done if (CanStartMember(kind) && !(kind == SyntaxKind.DelegateKeyword && (this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken || this.PeekToken(1).Kind == SyntaxKind.OpenParenToken))) { done = true; continue; } // <UNDONE> UNDONE: Seems like this makes sense, // but if this token can start a namespace element, but not a member, then // perhaps we should bail back up to parsing a namespace body somehow...</UNDONE> // Watch curlies and look for end of file/close curly switch (kind) { case SyntaxKind.OpenBraceToken: curlyCount++; break; case SyntaxKind.CloseBraceToken: if (curlyCount-- == 0) { done = true; continue; } break; case SyntaxKind.EndOfFileToken: done = true; continue; default: break; } tokens.Add(this.EatToken()); } previousNode = AddTrailingSkippedSyntax((CSharpSyntaxNode)previousNode, tokens.ToListNode()); } finally { _pool.Free(tokens); } } private bool IsPossibleMemberStartOrStop() { return this.IsPossibleMemberStart() || this.CurrentToken.Kind == SyntaxKind.CloseBraceToken; } private bool IsPossibleAggregateClauseStartOrStop() { return this.CurrentToken.Kind == SyntaxKind.ColonToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.IsCurrentTokenWhereOfConstraintClause(); } private BaseListSyntax ParseBaseList() { if (this.CurrentToken.Kind != SyntaxKind.ColonToken) { return null; } var colon = this.EatToken(); var list = _pool.AllocateSeparated<BaseTypeSyntax>(); try { // first type TypeSyntax firstType = this.ParseType(); ArgumentListSyntax argumentList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { argumentList = this.ParseParenthesizedArgumentList(); } list.Add(argumentList is object ? _syntaxFactory.PrimaryConstructorBaseType(firstType, argumentList) : (BaseTypeSyntax)_syntaxFactory.SimpleBaseType(firstType)); // any additional types while (true) { if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || ((_termState & TerminatorState.IsEndOfRecordSignature) != 0 && this.CurrentToken.Kind == SyntaxKind.SemicolonToken) || this.IsCurrentTokenWhereOfConstraintClause()) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleType()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); list.Add(_syntaxFactory.SimpleBaseType(this.ParseType())); continue; } else if (this.SkipBadBaseListTokens(ref colon, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } return _syntaxFactory.BaseList(colon, list); } finally { _pool.Free(list); } } private PostSkipAction SkipBadBaseListTokens(ref SyntaxToken colon, SeparatedSyntaxListBuilder<BaseTypeSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref colon, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttribute(), p => p.CurrentToken.Kind == SyntaxKind.OpenBraceToken || p.IsCurrentTokenWhereOfConstraintClause() || p.IsTerminator(), expected); } private bool IsCurrentTokenWhereOfConstraintClause() { return this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword && this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && this.PeekToken(2).Kind == SyntaxKind.ColonToken; } private void ParseTypeParameterConstraintClauses(SyntaxListBuilder list) { while (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { list.Add(this.ParseTypeParameterConstraintClause()); } } private TypeParameterConstraintClauseSyntax ParseTypeParameterConstraintClause() { var where = this.EatContextualToken(SyntaxKind.WhereKeyword); var name = !IsTrueIdentifier() ? this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected) : this.ParseIdentifierName(); var colon = this.EatToken(SyntaxKind.ColonToken); var bounds = _pool.AllocateSeparated<TypeParameterConstraintSyntax>(); try { // first bound if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.IsCurrentTokenWhereOfConstraintClause()) { bounds.Add(_syntaxFactory.TypeConstraint(this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_TypeExpected))); } else { bounds.Add(this.ParseTypeParameterConstraint()); // remaining bounds while (true) { if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || ((_termState & TerminatorState.IsEndOfRecordSignature) != 0 && this.CurrentToken.Kind == SyntaxKind.SemicolonToken) || this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken || this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleTypeParameterConstraint()) { bounds.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); if (this.IsCurrentTokenWhereOfConstraintClause()) { bounds.Add(_syntaxFactory.TypeConstraint(this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_TypeExpected))); break; } else { bounds.Add(this.ParseTypeParameterConstraint()); } } else if (this.SkipBadTypeParameterConstraintTokens(bounds, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } return _syntaxFactory.TypeParameterConstraintClause(where, name, colon, bounds); } finally { _pool.Free(bounds); } } private bool IsPossibleTypeParameterConstraint() { switch (this.CurrentToken.Kind) { case SyntaxKind.NewKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.StructKeyword: case SyntaxKind.DefaultKeyword: return true; case SyntaxKind.IdentifierToken: return this.IsTrueIdentifier(); default: return IsPredefinedType(this.CurrentToken.Kind); } } private TypeParameterConstraintSyntax ParseTypeParameterConstraint() { SyntaxToken questionToken = null; var syntaxKind = this.CurrentToken.Kind; switch (this.CurrentToken.Kind) { case SyntaxKind.NewKeyword: var newToken = this.EatToken(); var open = this.EatToken(SyntaxKind.OpenParenToken); var close = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.ConstructorConstraint(newToken, open, close); case SyntaxKind.StructKeyword: var structToken = this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.QuestionToken) { questionToken = this.EatToken(); questionToken = this.AddError(questionToken, ErrorCode.ERR_UnexpectedToken, questionToken.Text); } return _syntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint, structToken, questionToken); case SyntaxKind.ClassKeyword: var classToken = this.EatToken(); questionToken = this.TryEatToken(SyntaxKind.QuestionToken); return _syntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint, classToken, questionToken); case SyntaxKind.DefaultKeyword: var defaultToken = this.EatToken(); return CheckFeatureAvailability(_syntaxFactory.DefaultConstraint(defaultToken), MessageID.IDS_FeatureDefaultTypeParameterConstraint); default: var type = this.ParseType(); return _syntaxFactory.TypeConstraint(type); } } private PostSkipAction SkipBadTypeParameterConstraintTokens(SeparatedSyntaxListBuilder<TypeParameterConstraintSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleTypeParameterConstraint(), p => p.CurrentToken.Kind == SyntaxKind.OpenBraceToken || p.IsCurrentTokenWhereOfConstraintClause() || p.IsTerminator(), expected); } private bool IsPossibleMemberStart() { return CanStartMember(this.CurrentToken.Kind); } private static bool CanStartMember(SyntaxKind kind) { switch (kind) { case SyntaxKind.AbstractKeyword: case SyntaxKind.BoolKeyword: case SyntaxKind.ByteKeyword: case SyntaxKind.CharKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DecimalKeyword: case SyntaxKind.DelegateKeyword: case SyntaxKind.DoubleKeyword: case SyntaxKind.EnumKeyword: case SyntaxKind.EventKeyword: case SyntaxKind.ExternKeyword: case SyntaxKind.FixedKeyword: case SyntaxKind.FloatKeyword: case SyntaxKind.IntKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.LongKeyword: case SyntaxKind.NewKeyword: case SyntaxKind.ObjectKeyword: case SyntaxKind.OverrideKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PublicKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.SByteKeyword: case SyntaxKind.SealedKeyword: case SyntaxKind.ShortKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.StructKeyword: case SyntaxKind.UIntKeyword: case SyntaxKind.ULongKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.UShortKeyword: case SyntaxKind.VirtualKeyword: case SyntaxKind.VoidKeyword: case SyntaxKind.VolatileKeyword: case SyntaxKind.IdentifierToken: case SyntaxKind.TildeToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.ImplicitKeyword: case SyntaxKind.ExplicitKeyword: case SyntaxKind.OpenParenToken: //tuple case SyntaxKind.RefKeyword: return true; default: return false; } } private bool IsTypeDeclarationStart() { switch (this.CurrentToken.Kind) { case SyntaxKind.ClassKeyword: case SyntaxKind.DelegateKeyword when !IsFunctionPointerStart(): case SyntaxKind.EnumKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.StructKeyword: return true; case SyntaxKind.IdentifierToken: if (CurrentToken.ContextualKind == SyntaxKind.RecordKeyword) { // This is an unusual use of LangVersion. Normally we only produce errors when the langversion // does not support a feature, but in this case we are effectively making a language breaking // change to consider "record" a type declaration in all ambiguous cases. To avoid breaking // older code that is not using C# 9 we conditionally parse based on langversion return IsFeatureEnabled(MessageID.IDS_FeatureRecords); } return false; default: return false; } } private bool CanReuseMemberDeclaration(SyntaxKind kind, bool isGlobal) { switch (kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return true; case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: if (!isGlobal || IsScript) { return true; } // We can reuse original nodes if they came from the global context as well. return (this.CurrentNode.Parent is Syntax.CompilationUnitSyntax); case SyntaxKind.GlobalStatement: return isGlobal; default: return false; } } public MemberDeclarationSyntax ParseMemberDeclaration() { // Use a parent kind that causes inclusion of only member declarations that could appear in a struct // e.g. including fixed member declarations, but not statements. const SyntaxKind parentKind = SyntaxKind.StructDeclaration; return ParseWithStackGuard( () => this.ParseMemberDeclaration(parentKind), () => createEmptyNodeFunc()); // Creates a dummy declaration node to which we can attach a stack overflow message MemberDeclarationSyntax createEmptyNodeFunc() { return _syntaxFactory.IncompleteMember( new SyntaxList<AttributeListSyntax>(), new SyntaxList<SyntaxToken>(), CreateMissingIdentifierName() ); } } // Returns null if we can't parse anything (even partially). internal MemberDeclarationSyntax ParseMemberDeclarationOrStatement(SyntaxKind parentKind) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); var result = ParseMemberDeclarationOrStatementCore(parentKind); _recursionDepth--; return result; } /// <summary> /// Changes in this function around member parsing should be mirrored in <see cref="ParseMemberDeclarationCore"/>. /// Try keeping structure of both functions similar to simplify this task. The split was made to /// reduce the stack usage during recursive parsing. /// </summary> /// <returns>Returns null if we can't parse anything (even partially).</returns> private MemberDeclarationSyntax ParseMemberDeclarationOrStatementCore(SyntaxKind parentKind) { // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); Debug.Assert(parentKind == SyntaxKind.CompilationUnit); cancellationToken.ThrowIfCancellationRequested(); // don't reuse members if they were previously declared under a different type keyword kind if (this.IsIncrementalAndFactoryContextMatches) { if (CanReuseMemberDeclaration(CurrentNodeKind, isGlobal: true)) { return (MemberDeclarationSyntax)this.EatNode(); } } var saveTermState = _termState; var attributes = this.ParseAttributeDeclarations(); bool haveAttributes = (attributes.Count > 0); var afterAttributesPoint = this.GetResetPoint(); var modifiers = _pool.Allocate(); try { // // Check for the following cases to disambiguate between member declarations and expressions. // Doing this before parsing modifiers simplifies further analysis since some of these keywords can act as modifiers as well. // // unsafe { ... } // fixed (...) { ... } // delegate (...) { ... } // delegate { ... } // new { ... } // new[] { ... } // new T (...) // new T [...] // if (!haveAttributes || !IsScript) { bool wasInAsync = IsInAsync; if (!IsScript) { IsInAsync = true; // We are implicitly in an async context } try { switch (this.CurrentToken.Kind) { case SyntaxKind.UnsafeKeyword: if (this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken) { return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(ParseUnsafeStatement(attributes))); } break; case SyntaxKind.FixedKeyword: if (this.PeekToken(1).Kind == SyntaxKind.OpenParenToken) { return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(ParseFixedStatement(attributes))); } break; case SyntaxKind.DelegateKeyword: switch (this.PeekToken(1).Kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.OpenBraceToken: return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(ParseExpressionStatement(attributes))); } break; case SyntaxKind.NewKeyword: if (IsPossibleNewExpression()) { return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(ParseExpressionStatement(attributes))); } break; } } finally { IsInAsync = wasInAsync; } } // All modifiers that might start an expression are processed above. this.ParseModifiers(modifiers, forAccessors: false); bool haveModifiers = (modifiers.Count > 0); MemberDeclarationSyntax result; // Check for constructor form if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.OpenParenToken) { // Script: // Constructor definitions are not allowed. We parse them as method calls with semicolon missing error: // // Script(...) { ... } // ^ // missing ';' // // Unless modifiers or attributes are present this is more likely to be a method call than a method definition. if (haveAttributes || haveModifiers) { var token = SyntaxFactory.MissingToken(SyntaxKind.VoidKeyword); token = this.AddError(token, ErrorCode.ERR_MemberNeedsType); var voidType = _syntaxFactory.PredefinedType(token); if (!IsScript) { if (tryParseLocalDeclarationStatementFromStartPoint<LocalFunctionStatementSyntax>(attributes, ref afterAttributesPoint, out result)) { return result; } } else { var identifier = this.EatToken(); return this.ParseMethodDeclaration(attributes, modifiers, voidType, explicitInterfaceOpt: null, identifier: identifier, typeParameterList: null); } } } // Destructors are disallowed in global code, skipping check for them. // TODO: better error messages for script // Check for constant if (this.CurrentToken.Kind == SyntaxKind.ConstKeyword) { if (!IsScript && tryParseLocalDeclarationStatementFromStartPoint<LocalDeclarationStatementSyntax>(attributes, ref afterAttributesPoint, out result)) { return result; } // Prefers const field over const local variable decl return this.ParseConstantFieldDeclaration(attributes, modifiers, parentKind); } // Check for event. if (this.CurrentToken.Kind == SyntaxKind.EventKeyword) { return this.ParseEventDeclaration(attributes, modifiers, parentKind); } // check for fixed size buffers. if (this.CurrentToken.Kind == SyntaxKind.FixedKeyword) { return this.ParseFixedSizeBufferDeclaration(attributes, modifiers, parentKind); } // Check for conversion operators (implicit/explicit) result = this.TryParseConversionOperatorDeclaration(attributes, modifiers); if (result is not null) { return result; } if (this.CurrentToken.Kind == SyntaxKind.NamespaceKeyword) { return ParseNamespaceDeclaration(attributes, modifiers); } // It's valid to have a type declaration here -- check for those if (IsTypeDeclarationStart()) { return this.ParseTypeDeclaration(attributes, modifiers); } TypeSyntax type = ParseReturnType(); var afterTypeResetPoint = this.GetResetPoint(); try { // Try as a regular statement rather than a member declaration, if appropriate. if ((!haveAttributes || !IsScript) && !haveModifiers && (type.Kind == SyntaxKind.RefType || !IsOperatorStart(out _, advanceParser: false))) { this.Reset(ref afterAttributesPoint); if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken && this.CurrentToken.Kind != SyntaxKind.EndOfFileToken && this.IsPossibleStatement(acceptAccessibilityMods: true)) { var saveTerm = _termState; _termState |= TerminatorState.IsPossibleStatementStartOrStop; // partial statements can abort if a new statement starts bool wasInAsync = IsInAsync; if (!IsScript) { IsInAsync = true; // We are implicitly in an async context } // In Script we don't allow local declaration statements at the top level. We want // to fall out below and parse them instead as fields. For top-level statements, we allow // them, but want to try properties , etc. first. var statement = this.ParseStatementCore(attributes, isGlobal: true); IsInAsync = wasInAsync; _termState = saveTerm; if (isAcceptableNonDeclarationStatement(statement, IsScript)) { return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(statement)); } } this.Reset(ref afterTypeResetPoint); } // Everything that's left -- methods, fields, properties, locals, // indexers, and non-conversion operators -- starts with a type // (possibly void). // Check for misplaced modifiers. if we see any, then consider this member // terminated and restart parsing. if (IsMisplacedModifier(modifiers, attributes, type, out result)) { return result; } parse_member_name:; // If we've seen the ref keyword, we know we must have an indexer, method, property, or local. bool typeIsRef = type.IsRef; ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; // Check here for operators // Allow old-style implicit/explicit casting operator syntax, just so we can give a better error if (!typeIsRef && IsOperatorStart(out explicitInterfaceOpt)) { return this.ParseOperatorDeclaration(attributes, modifiers, type, explicitInterfaceOpt); } if ((!typeIsRef || !IsScript) && IsFieldDeclaration(isEvent: false)) { var saveTerm = _termState; if ((!haveAttributes && !haveModifiers) || !IsScript) { // if we are at top-level then statements can occur _termState |= TerminatorState.IsPossibleStatementStartOrStop; if (!IsScript) { this.Reset(ref afterAttributesPoint); if (tryParseLocalDeclarationStatement<LocalDeclarationStatementSyntax>(attributes, out result)) { return result; } this.Reset(ref afterTypeResetPoint); } } if (!typeIsRef) { return this.ParseNormalFieldDeclaration(attributes, modifiers, type, parentKind); } else { _termState = saveTerm; } } // At this point we can either have indexers, methods, or // properties (or something unknown). Try to break apart // the following name and determine what to do from there. SyntaxToken identifierOrThisOpt; TypeParameterListSyntax typeParameterListOpt; this.ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterListOpt, isEvent: false); // First, check if we got absolutely nothing. If so, then // We need to consume a bad member and try again. if (IsNoneOrIncompleteMember(parentKind, attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) { return result; } // If the modifiers did not include "async", and the type we got was "async", and there was an // error in the identifier or its type parameters, then the user is probably in the midst of typing // an async method. In that case we reconsider "async" to be a modifier, and treat the identifier // (with the type parameters) as the type (with type arguments). Then we go back to looking for // the member name again. // For example, if we get // async Task< // then we want async to be a modifier and Task<MISSING> to be a type. if (ReconsideredTypeAsAsyncModifier(ref modifiers, ref type, ref afterTypeResetPoint, ref explicitInterfaceOpt, ref identifierOrThisOpt, ref typeParameterListOpt)) { goto parse_member_name; } Debug.Assert(identifierOrThisOpt != null); // check availability of readonly members feature for indexers, properties and methods CheckForVersionSpecificModifiers(modifiers, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyMembers); if (TryParseIndexerOrPropertyDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) { return result; } // treat anything else as a method. if (!IsScript && explicitInterfaceOpt is null && tryParseLocalDeclarationStatementFromStartPoint<LocalFunctionStatementSyntax>(attributes, ref afterAttributesPoint, out result)) { return result; } return this.ParseMethodDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); } finally { this.Release(ref afterTypeResetPoint); } } finally { _pool.Free(modifiers); _termState = saveTermState; this.Release(ref afterAttributesPoint); } bool tryParseLocalDeclarationStatement<DeclarationSyntax>(SyntaxList<AttributeListSyntax> attributes, out MemberDeclarationSyntax result) where DeclarationSyntax : StatementSyntax { bool wasInAsync = IsInAsync; IsInAsync = true; // We are implicitly in an async context int lastTokenPosition = -1; IsMakingProgress(ref lastTokenPosition); var topLevelStatement = ParseLocalDeclarationStatement(attributes); IsInAsync = wasInAsync; if (topLevelStatement is DeclarationSyntax declaration && IsMakingProgress(ref lastTokenPosition, assertIfFalse: false)) { result = CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(declaration)); return true; } result = null; return false; } bool tryParseLocalDeclarationStatementFromStartPoint<DeclarationSyntax>(SyntaxList<AttributeListSyntax> attributes, ref ResetPoint startPoint, out MemberDeclarationSyntax result) where DeclarationSyntax : StatementSyntax { var resetOnFailurePoint = this.GetResetPoint(); try { this.Reset(ref startPoint); if (tryParseLocalDeclarationStatement<DeclarationSyntax>(attributes, out result)) { return true; } this.Reset(ref resetOnFailurePoint); return false; } finally { this.Release(ref resetOnFailurePoint); } } static bool isAcceptableNonDeclarationStatement(StatementSyntax statement, bool isScript) { switch (statement?.Kind) { case null: case SyntaxKind.LocalFunctionStatement: case SyntaxKind.ExpressionStatement when !isScript && // Do not parse a single identifier as an expression statement in a Simple Program, this could be a beginning of a keyword and // we want completion to offer it. ((ExpressionStatementSyntax)statement) is var exprStatement && exprStatement.Expression.Kind == SyntaxKind.IdentifierName && exprStatement.SemicolonToken.IsMissing: return false; case SyntaxKind.LocalDeclarationStatement: return !isScript && ((LocalDeclarationStatementSyntax)statement).UsingKeyword is object; default: return true; } } } private bool IsMisplacedModifier(SyntaxListBuilder modifiers, SyntaxList<AttributeListSyntax> attributes, TypeSyntax type, out MemberDeclarationSyntax result) { if (GetModifier(this.CurrentToken) != DeclarationModifiers.None && this.CurrentToken.ContextualKind != SyntaxKind.PartialKeyword && this.CurrentToken.ContextualKind != SyntaxKind.AsyncKeyword && IsComplete(type)) { var misplacedModifier = this.CurrentToken; type = this.AddError( type, type.FullWidth + misplacedModifier.GetLeadingTriviaWidth(), misplacedModifier.Width, ErrorCode.ERR_BadModifierLocation, misplacedModifier.Text); result = _syntaxFactory.IncompleteMember(attributes, modifiers.ToList(), type); return true; } result = null; return false; } private bool IsNoneOrIncompleteMember(SyntaxKind parentKind, SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifierOrThisOpt, TypeParameterListSyntax typeParameterListOpt, out MemberDeclarationSyntax result) { if (explicitInterfaceOpt == null && identifierOrThisOpt == null && typeParameterListOpt == null) { if (attributes.Count == 0 && modifiers.Count == 0 && type.IsMissing && type.Kind != SyntaxKind.RefType) { // we haven't advanced, the caller needs to consume the tokens ahead result = null; return true; } var incompleteMember = _syntaxFactory.IncompleteMember(attributes, modifiers.ToList(), type.IsMissing ? null : type); if (incompleteMember.ContainsDiagnostics) { result = incompleteMember; } else if (parentKind is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || parentKind == SyntaxKind.CompilationUnit && !IsScript) { result = this.AddErrorToLastToken(incompleteMember, ErrorCode.ERR_NamespaceUnexpected); } else { //the error position should indicate CurrentToken result = this.AddError( incompleteMember, incompleteMember.FullWidth + this.CurrentToken.GetLeadingTriviaWidth(), this.CurrentToken.Width, ErrorCode.ERR_InvalidMemberDecl, this.CurrentToken.Text); } return true; } result = null; return false; } private bool ReconsideredTypeAsAsyncModifier(ref SyntaxListBuilder modifiers, ref TypeSyntax type, ref ResetPoint afterTypeResetPoint, ref ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, ref SyntaxToken identifierOrThisOpt, ref TypeParameterListSyntax typeParameterListOpt) { if (type.Kind != SyntaxKind.RefType && identifierOrThisOpt != null && (typeParameterListOpt != null && typeParameterListOpt.ContainsDiagnostics || this.CurrentToken.Kind != SyntaxKind.OpenParenToken && this.CurrentToken.Kind != SyntaxKind.OpenBraceToken && this.CurrentToken.Kind != SyntaxKind.EqualsGreaterThanToken) && ReconsiderTypeAsAsyncModifier(ref modifiers, type, identifierOrThisOpt)) { this.Reset(ref afterTypeResetPoint); explicitInterfaceOpt = null; identifierOrThisOpt = null; typeParameterListOpt = null; this.Release(ref afterTypeResetPoint); type = ParseReturnType(); afterTypeResetPoint = this.GetResetPoint(); return true; } return false; } private bool TryParseIndexerOrPropertyDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifierOrThisOpt, TypeParameterListSyntax typeParameterListOpt, out MemberDeclarationSyntax result) { if (identifierOrThisOpt.Kind == SyntaxKind.ThisKeyword) { result = this.ParseIndexerDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); return true; } switch (this.CurrentToken.Kind) { case SyntaxKind.OpenBraceToken: case SyntaxKind.EqualsGreaterThanToken: result = this.ParsePropertyDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); return true; } result = null; return false; } // Returns null if we can't parse anything (even partially). internal MemberDeclarationSyntax ParseMemberDeclaration(SyntaxKind parentKind) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); var result = ParseMemberDeclarationCore(parentKind); _recursionDepth--; return result; } /// <summary> /// Changes in this function should be mirrored in <see cref="ParseMemberDeclarationOrStatementCore"/>. /// Try keeping structure of both functions similar to simplify this task. The split was made to /// reduce the stack usage during recursive parsing. /// </summary> /// <returns>Returns null if we can't parse anything (even partially).</returns> private MemberDeclarationSyntax ParseMemberDeclarationCore(SyntaxKind parentKind) { // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); Debug.Assert(parentKind != SyntaxKind.CompilationUnit); cancellationToken.ThrowIfCancellationRequested(); // don't reuse members if they were previously declared under a different type keyword kind if (this.IsIncrementalAndFactoryContextMatches) { if (CanReuseMemberDeclaration(CurrentNodeKind, isGlobal: false)) { return (MemberDeclarationSyntax)this.EatNode(); } } var modifiers = _pool.Allocate(); var saveTermState = _termState; try { var attributes = this.ParseAttributeDeclarations(); this.ParseModifiers(modifiers, forAccessors: false); // Check for constructor form if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.OpenParenToken) { return this.ParseConstructorDeclaration(attributes, modifiers); } // Check for destructor form if (this.CurrentToken.Kind == SyntaxKind.TildeToken) { return this.ParseDestructorDeclaration(attributes, modifiers); } // Check for constant if (this.CurrentToken.Kind == SyntaxKind.ConstKeyword) { return this.ParseConstantFieldDeclaration(attributes, modifiers, parentKind); } // Check for event. if (this.CurrentToken.Kind == SyntaxKind.EventKeyword) { return this.ParseEventDeclaration(attributes, modifiers, parentKind); } // check for fixed size buffers. if (this.CurrentToken.Kind == SyntaxKind.FixedKeyword) { return this.ParseFixedSizeBufferDeclaration(attributes, modifiers, parentKind); } // Check for conversion operators (implicit/explicit) MemberDeclarationSyntax result = this.TryParseConversionOperatorDeclaration(attributes, modifiers); if (result is not null) { return result; } // Namespaces should be handled by the caller, not checking for them // It's valid to have a type declaration here -- check for those if (IsTypeDeclarationStart()) { return this.ParseTypeDeclaration(attributes, modifiers); } // Everything that's left -- methods, fields, properties, // indexers, and non-conversion operators -- starts with a type // (possibly void). TypeSyntax type = ParseReturnType(); var afterTypeResetPoint = this.GetResetPoint(); try { // Check for misplaced modifiers. if we see any, then consider this member // terminated and restart parsing. if (IsMisplacedModifier(modifiers, attributes, type, out result)) { return result; } parse_member_name:; ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; // If we've seen the ref keyword, we know we must have an indexer, method, or property. if (type.Kind != SyntaxKind.RefType) { // Check here for operators // Allow old-style implicit/explicit casting operator syntax, just so we can give a better error if (IsOperatorStart(out explicitInterfaceOpt)) { return this.ParseOperatorDeclaration(attributes, modifiers, type, explicitInterfaceOpt); } if (IsFieldDeclaration(isEvent: false)) { return this.ParseNormalFieldDeclaration(attributes, modifiers, type, parentKind); } } // At this point we can either have indexers, methods, or // properties (or something unknown). Try to break apart // the following name and determine what to do from there. SyntaxToken identifierOrThisOpt; TypeParameterListSyntax typeParameterListOpt; this.ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterListOpt, isEvent: false); // First, check if we got absolutely nothing. If so, then // We need to consume a bad member and try again. if (IsNoneOrIncompleteMember(parentKind, attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) { return result; } // If the modifiers did not include "async", and the type we got was "async", and there was an // error in the identifier or its type parameters, then the user is probably in the midst of typing // an async method. In that case we reconsider "async" to be a modifier, and treat the identifier // (with the type parameters) as the type (with type arguments). Then we go back to looking for // the member name again. // For example, if we get // async Task< // then we want async to be a modifier and Task<MISSING> to be a type. if (ReconsideredTypeAsAsyncModifier(ref modifiers, ref type, ref afterTypeResetPoint, ref explicitInterfaceOpt, ref identifierOrThisOpt, ref typeParameterListOpt)) { goto parse_member_name; } Debug.Assert(identifierOrThisOpt != null); // check availability of readonly members feature for indexers, properties and methods CheckForVersionSpecificModifiers(modifiers, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyMembers); if (TryParseIndexerOrPropertyDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) { return result; } // treat anything else as a method. return this.ParseMethodDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); } finally { this.Release(ref afterTypeResetPoint); } } finally { _pool.Free(modifiers); _termState = saveTermState; } } // if the modifiers do not contain async or replace and the type is the identifier "async" or "replace", then // add that identifier to the modifiers and assign a new type from the identifierOrThisOpt and the // type parameter list private bool ReconsiderTypeAsAsyncModifier( ref SyntaxListBuilder modifiers, TypeSyntax type, SyntaxToken identifierOrThisOpt) { if (type.Kind != SyntaxKind.IdentifierName) return false; if (identifierOrThisOpt.Kind != SyntaxKind.IdentifierToken) return false; var identifier = ((IdentifierNameSyntax)type).Identifier; var contextualKind = identifier.ContextualKind; if (contextualKind != SyntaxKind.AsyncKeyword || modifiers.Any((int)contextualKind)) { return false; } modifiers.Add(ConvertToKeyword(identifier)); return true; } private bool IsFieldDeclaration(bool isEvent) { if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return false; } if (this.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword && this.PeekToken(1).Kind == SyntaxKind.UsingKeyword) { return false; } // Treat this as a field, unless we have anything following that // makes us: // a) explicit // b) generic // c) a property // d) a method (unless we already know we're parsing an event) var kind = this.PeekToken(1).Kind; switch (kind) { case SyntaxKind.DotToken: // Goo. explicit case SyntaxKind.ColonColonToken: // Goo:: explicit case SyntaxKind.DotDotToken: // Goo.. explicit case SyntaxKind.LessThanToken: // Goo< explicit or generic method case SyntaxKind.OpenBraceToken: // Goo { property case SyntaxKind.EqualsGreaterThanToken: // Goo => property return false; case SyntaxKind.OpenParenToken: // Goo( method return isEvent; default: return true; } } private bool IsOperatorKeyword() { return this.CurrentToken.Kind == SyntaxKind.ImplicitKeyword || this.CurrentToken.Kind == SyntaxKind.ExplicitKeyword || this.CurrentToken.Kind == SyntaxKind.OperatorKeyword; } public static bool IsComplete(CSharpSyntaxNode node) { if (node == null) { return false; } foreach (var child in node.ChildNodesAndTokens().Reverse()) { var token = child as SyntaxToken; if (token == null) { return IsComplete((CSharpSyntaxNode)child); } if (token.IsMissing) { return false; } if (token.Kind != SyntaxKind.None) { return true; } // if token was optional, consider the next one.. } return true; } private ConstructorDeclarationSyntax ParseConstructorDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { var name = this.ParseIdentifierToken(); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfMethodSignature; try { var paramList = this.ParseParenthesizedParameterList(); ConstructorInitializerSyntax initializer = this.CurrentToken.Kind == SyntaxKind.ColonToken ? this.ParseConstructorInitializer() : null; this.ParseBlockAndExpressionBodiesWithSemicolon( out BlockSyntax body, out ArrowExpressionClauseSyntax expressionBody, out SyntaxToken semicolon, requestedExpressionBodyFeature: MessageID.IDS_FeatureExpressionBodiedDeOrConstructor); return _syntaxFactory.ConstructorDeclaration(attributes, modifiers.ToList(), name, paramList, initializer, body, expressionBody, semicolon); } finally { _termState = saveTerm; } } private ConstructorInitializerSyntax ParseConstructorInitializer() { var colon = this.EatToken(SyntaxKind.ColonToken); var reportError = true; var kind = this.CurrentToken.Kind == SyntaxKind.BaseKeyword ? SyntaxKind.BaseConstructorInitializer : SyntaxKind.ThisConstructorInitializer; SyntaxToken token; if (this.CurrentToken.Kind == SyntaxKind.BaseKeyword || this.CurrentToken.Kind == SyntaxKind.ThisKeyword) { token = this.EatToken(); } else { token = this.EatToken(SyntaxKind.ThisKeyword, ErrorCode.ERR_ThisOrBaseExpected); // No need to report further errors at this point: reportError = false; } ArgumentListSyntax argumentList; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { argumentList = this.ParseParenthesizedArgumentList(); } else { var openToken = this.EatToken(SyntaxKind.OpenParenToken, reportError); var closeToken = this.EatToken(SyntaxKind.CloseParenToken, reportError); argumentList = _syntaxFactory.ArgumentList(openToken, default, closeToken); } return _syntaxFactory.ConstructorInitializer(kind, colon, token, argumentList); } private DestructorDeclarationSyntax ParseDestructorDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.TildeToken); var tilde = this.EatToken(SyntaxKind.TildeToken); var name = this.ParseIdentifierToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); this.ParseBlockAndExpressionBodiesWithSemicolon( out BlockSyntax body, out ArrowExpressionClauseSyntax expressionBody, out SyntaxToken semicolon, requestedExpressionBodyFeature: MessageID.IDS_FeatureExpressionBodiedDeOrConstructor); var parameterList = _syntaxFactory.ParameterList(openParen, default(SeparatedSyntaxList<ParameterSyntax>), closeParen); return _syntaxFactory.DestructorDeclaration(attributes, modifiers.ToList(), tilde, name, parameterList, body, expressionBody, semicolon); } /// <summary> /// Parses any block or expression bodies that are present. Also parses /// the trailing semicolon if one is present. /// </summary> private void ParseBlockAndExpressionBodiesWithSemicolon( out BlockSyntax blockBody, out ArrowExpressionClauseSyntax expressionBody, out SyntaxToken semicolon, bool parseSemicolonAfterBlock = true, MessageID requestedExpressionBodyFeature = MessageID.IDS_FeatureExpressionBodiedMethod) { // Check for 'forward' declarations with no block of any kind if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { blockBody = null; expressionBody = null; semicolon = this.EatToken(SyntaxKind.SemicolonToken); return; } blockBody = null; expressionBody = null; if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { blockBody = this.ParseMethodOrAccessorBodyBlock(attributes: default, isAccessorBody: false); } if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) { Debug.Assert(requestedExpressionBodyFeature == MessageID.IDS_FeatureExpressionBodiedMethod || requestedExpressionBodyFeature == MessageID.IDS_FeatureExpressionBodiedAccessor || requestedExpressionBodyFeature == MessageID.IDS_FeatureExpressionBodiedDeOrConstructor, "Only IDS_FeatureExpressionBodiedMethod, IDS_FeatureExpressionBodiedAccessor or IDS_FeatureExpressionBodiedDeOrConstructor can be requested"); expressionBody = this.ParseArrowExpressionClause(); expressionBody = CheckFeatureAvailability(expressionBody, requestedExpressionBodyFeature); } semicolon = null; // Expression-bodies need semicolons and native behavior // expects a semicolon if there is no body if (expressionBody != null || blockBody == null) { semicolon = this.EatToken(SyntaxKind.SemicolonToken); } // Check for bad semicolon after block body else if (parseSemicolonAfterBlock && this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); } } private bool IsEndOfTypeParameterList() { if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { // void Goo<T ( return true; } if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { // class C<T : return true; } if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { // class C<T { return true; } if (IsCurrentTokenWhereOfConstraintClause()) { // class C<T where T : return true; } return false; } private bool IsEndOfMethodSignature() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; } private bool IsEndOfRecordSignature() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; } private bool IsEndOfNameInExplicitInterface() { return this.CurrentToken.Kind == SyntaxKind.DotToken || this.CurrentToken.Kind == SyntaxKind.ColonColonToken; } private bool IsEndOfFunctionPointerParameterList(bool errored) => this.CurrentToken.Kind == (errored ? SyntaxKind.CloseParenToken : SyntaxKind.GreaterThanToken); private bool IsEndOfFunctionPointerCallingConvention() => this.CurrentToken.Kind == SyntaxKind.CloseBracketToken; private MethodDeclarationSyntax ParseMethodDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifier, TypeParameterListSyntax typeParameterList) { // Parse the name (it could be qualified) var saveTerm = _termState; _termState |= TerminatorState.IsEndOfMethodSignature; var paramList = this.ParseParenthesizedParameterList(); var constraints = default(SyntaxListBuilder<TypeParameterConstraintClauseSyntax>); try { if (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { constraints = _pool.Allocate<TypeParameterConstraintClauseSyntax>(); this.ParseTypeParameterConstraintClauses(constraints); } else if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { // Use else if, rather than if, because if we see both a constructor initializer and a constraint clause, we're too lost to recover. var colonToken = this.CurrentToken; ConstructorInitializerSyntax initializer = this.ParseConstructorInitializer(); initializer = this.AddErrorToFirstToken(initializer, ErrorCode.ERR_UnexpectedToken, colonToken.Text); paramList = AddTrailingSkippedSyntax(paramList, initializer); // CONSIDER: Parsing an invalid constructor initializer could, conceivably, get us way // off track. If this becomes a problem, an alternative approach would be to generalize // EatTokenWithPrejudice in such a way that we can just skip everything until we recognize // our context again (perhaps an open brace). } _termState = saveTerm; BlockSyntax blockBody; ArrowExpressionClauseSyntax expressionBody; SyntaxToken semicolon; // Method declarations cannot be nested or placed inside async lambdas, and so cannot occur in an // asynchronous context. Therefore the IsInAsync state of the parent scope is not saved and // restored, just assumed to be false and reset accordingly after parsing the method body. Debug.Assert(!IsInAsync); IsInAsync = modifiers.Any((int)SyntaxKind.AsyncKeyword); this.ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon); IsInAsync = false; return _syntaxFactory.MethodDeclaration( attributes, modifiers.ToList(), type, explicitInterfaceOpt, identifier, typeParameterList, paramList, constraints, blockBody, expressionBody, semicolon); } finally { if (!constraints.IsNull) { _pool.Free(constraints); } } } private TypeSyntax ParseReturnType() { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfReturnType; var type = this.ParseTypeOrVoid(); _termState = saveTerm; return type; } private bool IsEndOfReturnType() { switch (this.CurrentToken.Kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.OpenBraceToken: case SyntaxKind.SemicolonToken: return true; default: return false; } } private ConversionOperatorDeclarationSyntax TryParseConversionOperatorDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { var point = GetResetPoint(); try { SyntaxToken style; if (this.CurrentToken.Kind == SyntaxKind.ImplicitKeyword || this.CurrentToken.Kind == SyntaxKind.ExplicitKeyword) { style = this.EatToken(); } else { style = this.EatToken(SyntaxKind.ExplicitKeyword); } ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt = tryParseExplicitInterfaceSpecifier(); SyntaxToken opKeyword; TypeSyntax type; ParameterListSyntax paramList; if (style.IsMissing) { if (this.CurrentToken.Kind != SyntaxKind.OperatorKeyword || SyntaxFacts.IsAnyOverloadableOperator(this.PeekToken(1).Kind) || explicitInterfaceOpt?.DotToken.IsMissing == true) { this.Reset(ref point); return null; } } else if (explicitInterfaceOpt is not null && this.CurrentToken.Kind != SyntaxKind.OperatorKeyword && style.TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia)) { // Not likely an explicit interface implementation. Likely a beginning of the next member on the next line. this.Reset(ref point); style = this.EatToken(); explicitInterfaceOpt = null; opKeyword = this.EatToken(SyntaxKind.OperatorKeyword); type = this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected); SyntaxToken open = SyntaxFactory.MissingToken(SyntaxKind.OpenParenToken); SyntaxToken close = SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken); var parameters = _pool.AllocateSeparated<ParameterSyntax>(); paramList = _syntaxFactory.ParameterList(open, parameters, close); _pool.Free(parameters); return _syntaxFactory.ConversionOperatorDeclaration( attributes, modifiers.ToList(), style, explicitInterfaceOpt, opKeyword, type, paramList, body: null, expressionBody: null, semicolonToken: SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken)); } opKeyword = this.EatToken(SyntaxKind.OperatorKeyword); this.Release(ref point); point = GetResetPoint(); bool couldBeParameterList = this.CurrentToken.Kind == SyntaxKind.OpenParenToken; type = this.ParseType(); if (couldBeParameterList && type is TupleTypeSyntax { Elements: { Count: 2, SeparatorCount: 1 } } tupleType && tupleType.Elements.GetSeparator(0).IsMissing && tupleType.Elements[1].IsMissing && this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { // It looks like the type is missing and we parsed parameter list as the type. Recover. this.Reset(ref point); type = ParseIdentifierName(); } paramList = this.ParseParenthesizedParameterList(); BlockSyntax blockBody; ArrowExpressionClauseSyntax expressionBody; SyntaxToken semicolon; this.ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon); return _syntaxFactory.ConversionOperatorDeclaration( attributes, modifiers.ToList(), style, explicitInterfaceOpt, opKeyword, type, paramList, blockBody, expressionBody, semicolon); } finally { this.Release(ref point); } ExplicitInterfaceSpecifierSyntax tryParseExplicitInterfaceSpecifier() { if (this.CurrentToken.Kind == SyntaxKind.OperatorKeyword) { return null; } if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return null; } NameSyntax explicitInterfaceName = null; SyntaxToken separator = null; while (true) { // now, scan past the next name. if it's followed by a dot then // it's part of the explicit name we're building up. Otherwise, // it should be an operator token var point = GetResetPoint(); bool isPartOfInterfaceName; try { if (this.CurrentToken.Kind == SyntaxKind.OperatorKeyword) { isPartOfInterfaceName = false; } else { int lastTokenPosition = -1; IsMakingProgress(ref lastTokenPosition, assertIfFalse: true); ScanNamedTypePart(); isPartOfInterfaceName = IsDotOrColonColonOrDotDot() || (IsMakingProgress(ref lastTokenPosition, assertIfFalse: false) && this.CurrentToken.Kind != SyntaxKind.OpenParenToken); } } finally { this.Reset(ref point); this.Release(ref point); } if (!isPartOfInterfaceName) { // We're past any explicit interface portion if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) { separator = this.AddError(separator, ErrorCode.ERR_AliasQualAsExpression); separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } break; } else { // If we saw a . or :: then we must have something explicit. AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator, reportAnErrorOnMisplacedColonColon: true); } } if (explicitInterfaceName is null) { return null; } if (separator.Kind != SyntaxKind.DotToken) { separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, separator.GetLeadingTriviaWidth(), separator.Width)); separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } return CheckFeatureAvailability(_syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator), MessageID.IDS_FeatureStaticAbstractMembersInInterfaces); } } private OperatorDeclarationSyntax ParseOperatorDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt) { var opKeyword = this.EatToken(SyntaxKind.OperatorKeyword); SyntaxToken opToken; int opTokenErrorOffset; int opTokenErrorWidth; if (SyntaxFacts.IsAnyOverloadableOperator(this.CurrentToken.Kind)) { opToken = this.EatToken(); Debug.Assert(!opToken.IsMissing); opTokenErrorOffset = opToken.GetLeadingTriviaWidth(); opTokenErrorWidth = opToken.Width; } else { if (this.CurrentToken.Kind == SyntaxKind.ImplicitKeyword || this.CurrentToken.Kind == SyntaxKind.ExplicitKeyword) { // Grab the offset and width before we consume the invalid keyword and change our position. GetDiagnosticSpanForMissingToken(out opTokenErrorOffset, out opTokenErrorWidth); opToken = this.ConvertToMissingWithTrailingTrivia(this.EatToken(), SyntaxKind.PlusToken); Debug.Assert(opToken.IsMissing); //Which is why we used GetDiagnosticSpanForMissingToken above. Debug.Assert(type != null); // How could it be? The only caller got it from ParseReturnType. if (type.IsMissing) { SyntaxDiagnosticInfo diagInfo = MakeError(opTokenErrorOffset, opTokenErrorWidth, ErrorCode.ERR_BadOperatorSyntax, SyntaxFacts.GetText(SyntaxKind.PlusToken)); opToken = WithAdditionalDiagnostics(opToken, diagInfo); } else { // Dev10 puts this error on the type (if there is one). type = this.AddError(type, ErrorCode.ERR_BadOperatorSyntax, SyntaxFacts.GetText(SyntaxKind.PlusToken)); } } else { //Consume whatever follows the operator keyword as the operator token. If it is not //we'll add an error below (when we can guess the arity). opToken = EatToken(); Debug.Assert(!opToken.IsMissing); opTokenErrorOffset = opToken.GetLeadingTriviaWidth(); opTokenErrorWidth = opToken.Width; } } // check for >> var opKind = opToken.Kind; var tk = this.CurrentToken; if (opToken.Kind == SyntaxKind.GreaterThanToken && tk.Kind == SyntaxKind.GreaterThanToken) { // no trailing trivia and no leading trivia if (opToken.GetTrailingTriviaWidth() == 0 && tk.GetLeadingTriviaWidth() == 0) { var opToken2 = this.EatToken(); opToken = SyntaxFactory.Token(opToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanToken, opToken2.GetTrailingTrivia()); } } var paramList = this.ParseParenthesizedParameterList(); switch (paramList.Parameters.Count) { case 1: if (opToken.IsMissing || !SyntaxFacts.IsOverloadableUnaryOperator(opKind)) { SyntaxDiagnosticInfo diagInfo = MakeError(opTokenErrorOffset, opTokenErrorWidth, ErrorCode.ERR_OvlUnaryOperatorExpected); opToken = WithAdditionalDiagnostics(opToken, diagInfo); } break; case 2: if (opToken.IsMissing || !SyntaxFacts.IsOverloadableBinaryOperator(opKind)) { SyntaxDiagnosticInfo diagInfo = MakeError(opTokenErrorOffset, opTokenErrorWidth, ErrorCode.ERR_OvlBinaryOperatorExpected); opToken = WithAdditionalDiagnostics(opToken, diagInfo); } break; default: if (opToken.IsMissing) { SyntaxDiagnosticInfo diagInfo = MakeError(opTokenErrorOffset, opTokenErrorWidth, ErrorCode.ERR_OvlOperatorExpected); opToken = WithAdditionalDiagnostics(opToken, diagInfo); } else if (SyntaxFacts.IsOverloadableBinaryOperator(opKind)) { opToken = this.AddError(opToken, ErrorCode.ERR_BadBinOpArgs, SyntaxFacts.GetText(opKind)); } else if (SyntaxFacts.IsOverloadableUnaryOperator(opKind)) { opToken = this.AddError(opToken, ErrorCode.ERR_BadUnOpArgs, SyntaxFacts.GetText(opKind)); } else { opToken = this.AddError(opToken, ErrorCode.ERR_OvlOperatorExpected); } break; } BlockSyntax blockBody; ArrowExpressionClauseSyntax expressionBody; SyntaxToken semicolon; this.ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon); // if the operator is invalid, then switch it to plus (which will work either way) so that // we can finish building the tree if (!(opKind == SyntaxKind.IsKeyword || SyntaxFacts.IsOverloadableUnaryOperator(opKind) || SyntaxFacts.IsOverloadableBinaryOperator(opKind))) { opToken = ConvertToMissingWithTrailingTrivia(opToken, SyntaxKind.PlusToken); } return _syntaxFactory.OperatorDeclaration( attributes, modifiers.ToList(), type, explicitInterfaceOpt, opKeyword, opToken, paramList, blockBody, expressionBody, semicolon); } private IndexerDeclarationSyntax ParseIndexerDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken thisKeyword, TypeParameterListSyntax typeParameterList) { Debug.Assert(thisKeyword.Kind == SyntaxKind.ThisKeyword); // check to see if the user tried to create a generic indexer. if (typeParameterList != null) { thisKeyword = AddTrailingSkippedSyntax(thisKeyword, typeParameterList); thisKeyword = this.AddError(thisKeyword, ErrorCode.ERR_UnexpectedGenericName); } var parameterList = this.ParseBracketedParameterList(); AccessorListSyntax accessorList = null; ArrowExpressionClauseSyntax expressionBody = null; SyntaxToken semicolon = null; // Try to parse accessor list unless there is an expression // body and no accessor list if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) { expressionBody = this.ParseArrowExpressionClause(); expressionBody = CheckFeatureAvailability(expressionBody, MessageID.IDS_FeatureExpressionBodiedIndexer); semicolon = this.EatToken(SyntaxKind.SemicolonToken); } else { accessorList = this.ParseAccessorList(isEvent: false); if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); } } // If the user has erroneously provided both an accessor list // and an expression body, but no semicolon, we want to parse // the expression body and report the error (which is done later) if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken && semicolon == null) { expressionBody = this.ParseArrowExpressionClause(); expressionBody = CheckFeatureAvailability(expressionBody, MessageID.IDS_FeatureExpressionBodiedIndexer); semicolon = this.EatToken(SyntaxKind.SemicolonToken); } return _syntaxFactory.IndexerDeclaration( attributes, modifiers.ToList(), type, explicitInterfaceOpt, thisKeyword, parameterList, accessorList, expressionBody, semicolon); } private PropertyDeclarationSyntax ParsePropertyDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifier, TypeParameterListSyntax typeParameterList) { // check to see if the user tried to create a generic property. if (typeParameterList != null) { identifier = AddTrailingSkippedSyntax(identifier, typeParameterList); identifier = this.AddError(identifier, ErrorCode.ERR_UnexpectedGenericName); } // We know we are parsing a property because we have seen either an // open brace or an arrow token Debug.Assert(this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken); AccessorListSyntax accessorList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { accessorList = this.ParseAccessorList(isEvent: false); } ArrowExpressionClauseSyntax expressionBody = null; EqualsValueClauseSyntax initializer = null; // Check for expression body if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) { expressionBody = this.ParseArrowExpressionClause(); expressionBody = CheckFeatureAvailability(expressionBody, MessageID.IDS_FeatureExpressionBodiedProperty); } // Check if we have an initializer else if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { var equals = this.EatToken(SyntaxKind.EqualsToken); var value = this.ParseVariableInitializer(); initializer = _syntaxFactory.EqualsValueClause(equals, value: value); initializer = CheckFeatureAvailability(initializer, MessageID.IDS_FeatureAutoPropertyInitializer); } SyntaxToken semicolon = null; if (expressionBody != null || initializer != null) { semicolon = this.EatToken(SyntaxKind.SemicolonToken); } else if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); } return _syntaxFactory.PropertyDeclaration( attributes, modifiers.ToList(), type, explicitInterfaceOpt, identifier, accessorList, expressionBody, initializer, semicolon); } private AccessorListSyntax ParseAccessorList(bool isEvent) { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var accessors = default(SyntaxList<AccessorDeclarationSyntax>); if (!openBrace.IsMissing || !this.IsTerminator()) { // parse property accessors var builder = _pool.Allocate<AccessorDeclarationSyntax>(); try { while (true) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.IsPossibleAccessor()) { var acc = this.ParseAccessorDeclaration(isEvent); builder.Add(acc); } else if (this.SkipBadAccessorListTokens(ref openBrace, builder, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected) == PostSkipAction.Abort) { break; } } accessors = builder.ToList(); } finally { _pool.Free(builder); } } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); return _syntaxFactory.AccessorList(openBrace, accessors, closeBrace); } private ArrowExpressionClauseSyntax ParseArrowExpressionClause() { var arrowToken = this.EatToken(SyntaxKind.EqualsGreaterThanToken); return _syntaxFactory.ArrowExpressionClause(arrowToken, ParsePossibleRefExpression()); } private ExpressionSyntax ParsePossibleRefExpression() { var refKeyword = (SyntaxToken)null; if (this.CurrentToken.Kind == SyntaxKind.RefKeyword) { refKeyword = this.EatToken(); refKeyword = CheckFeatureAvailability(refKeyword, MessageID.IDS_FeatureRefLocalsReturns); } var expression = this.ParseExpressionCore(); if (refKeyword != null) { expression = _syntaxFactory.RefExpression(refKeyword, expression); } return expression; } private PostSkipAction SkipBadAccessorListTokens(ref SyntaxToken openBrace, SyntaxListBuilder<AccessorDeclarationSyntax> list, ErrorCode error) { return this.SkipBadListTokensWithErrorCode(ref openBrace, list, p => p.CurrentToken.Kind != SyntaxKind.CloseBraceToken && !p.IsPossibleAccessor(), p => p.IsTerminator(), error); } private bool IsPossibleAccessor() { return this.CurrentToken.Kind == SyntaxKind.IdentifierToken || IsPossibleAttributeDeclaration() || SyntaxFacts.GetAccessorDeclarationKind(this.CurrentToken.ContextualKind) != SyntaxKind.None || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken // for accessor blocks w/ missing keyword || this.CurrentToken.Kind == SyntaxKind.SemicolonToken // for empty body accessors w/ missing keyword || IsPossibleAccessorModifier(); } private bool IsPossibleAccessorModifier() { // We only want to accept a modifier as the start of an accessor if the modifiers are // actually followed by "get/set/add/remove". Otherwise, we might thing think we're // starting an accessor when we're actually starting a normal class member. For example: // // class C { // public int Prop { get { this. // private DateTime x; // // We don't want to think of the "private" in "private DateTime x" as starting an accessor // here. If we do, we'll get totally thrown off in parsing the remainder and that will // throw off the rest of the features that depend on a good syntax tree. // // Note: we allow all modifiers here. That's because we want to parse things like // "abstract get" as an accessor. This way we can provide a good error message // to the user that this is not allowed. if (GetModifier(this.CurrentToken) == DeclarationModifiers.None) { return false; } var peekIndex = 1; while (GetModifier(this.PeekToken(peekIndex)) != DeclarationModifiers.None) { peekIndex++; } var token = this.PeekToken(peekIndex); if (token.Kind == SyntaxKind.CloseBraceToken || token.Kind == SyntaxKind.EndOfFileToken) { // If we see "{ get { } public } // then we will think that "public" likely starts an accessor. return true; } switch (token.ContextualKind) { case SyntaxKind.GetKeyword: case SyntaxKind.SetKeyword: case SyntaxKind.InitKeyword: case SyntaxKind.AddKeyword: case SyntaxKind.RemoveKeyword: return true; default: return false; } } private enum PostSkipAction { Continue, Abort } private PostSkipAction SkipBadSeparatedListTokensWithExpectedKind<T, TNode>( ref T startToken, SeparatedSyntaxListBuilder<TNode> list, Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, SyntaxKind expected) where T : CSharpSyntaxNode where TNode : CSharpSyntaxNode { // We're going to cheat here and pass the underlying SyntaxListBuilder of "list" to the helper method so that // it can append skipped trivia to the last element, regardless of whether that element is a node or a token. GreenNode trailingTrivia; var action = this.SkipBadListTokensWithExpectedKindHelper(list.UnderlyingBuilder, isNotExpectedFunction, abortFunction, expected, out trailingTrivia); if (trailingTrivia != null) { startToken = AddTrailingSkippedSyntax(startToken, trailingTrivia); } return action; } private PostSkipAction SkipBadListTokensWithErrorCode<T, TNode>( ref T startToken, SyntaxListBuilder<TNode> list, Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, ErrorCode error) where T : CSharpSyntaxNode where TNode : CSharpSyntaxNode { GreenNode trailingTrivia; var action = this.SkipBadListTokensWithErrorCodeHelper(list, isNotExpectedFunction, abortFunction, error, out trailingTrivia); if (trailingTrivia != null) { startToken = AddTrailingSkippedSyntax(startToken, trailingTrivia); } return action; } /// <remarks> /// WARNING: it is possible that "list" is really the underlying builder of a SeparateSyntaxListBuilder, /// so it is important that we not add anything to the list. /// </remarks> private PostSkipAction SkipBadListTokensWithExpectedKindHelper( SyntaxListBuilder list, Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, SyntaxKind expected, out GreenNode trailingTrivia) { if (list.Count == 0) { return SkipBadTokensWithExpectedKind(isNotExpectedFunction, abortFunction, expected, out trailingTrivia); } else { GreenNode lastItemTrailingTrivia; var action = SkipBadTokensWithExpectedKind(isNotExpectedFunction, abortFunction, expected, out lastItemTrailingTrivia); if (lastItemTrailingTrivia != null) { AddTrailingSkippedSyntax(list, lastItemTrailingTrivia); } trailingTrivia = null; return action; } } private PostSkipAction SkipBadListTokensWithErrorCodeHelper<TNode>( SyntaxListBuilder<TNode> list, Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, ErrorCode error, out GreenNode trailingTrivia) where TNode : CSharpSyntaxNode { if (list.Count == 0) { return SkipBadTokensWithErrorCode(isNotExpectedFunction, abortFunction, error, out trailingTrivia); } else { GreenNode lastItemTrailingTrivia; var action = SkipBadTokensWithErrorCode(isNotExpectedFunction, abortFunction, error, out lastItemTrailingTrivia); if (lastItemTrailingTrivia != null) { AddTrailingSkippedSyntax(list, lastItemTrailingTrivia); } trailingTrivia = null; return action; } } private PostSkipAction SkipBadTokensWithExpectedKind( Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, SyntaxKind expected, out GreenNode trailingTrivia) { var nodes = _pool.Allocate(); try { bool first = true; var action = PostSkipAction.Continue; while (isNotExpectedFunction(this)) { if (abortFunction(this)) { action = PostSkipAction.Abort; break; } var token = (first && !this.CurrentToken.ContainsDiagnostics) ? this.EatTokenWithPrejudice(expected) : this.EatToken(); first = false; nodes.Add(token); } trailingTrivia = (nodes.Count > 0) ? nodes.ToListNode() : null; return action; } finally { _pool.Free(nodes); } } private PostSkipAction SkipBadTokensWithErrorCode( Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, ErrorCode errorCode, out GreenNode trailingTrivia) { var nodes = _pool.Allocate(); try { bool first = true; var action = PostSkipAction.Continue; while (isNotExpectedFunction(this)) { if (abortFunction(this)) { action = PostSkipAction.Abort; break; } var token = (first && !this.CurrentToken.ContainsDiagnostics) ? this.EatTokenWithPrejudice(errorCode) : this.EatToken(); first = false; nodes.Add(token); } trailingTrivia = (nodes.Count > 0) ? nodes.ToListNode() : null; return action; } finally { _pool.Free(nodes); } } private AccessorDeclarationSyntax ParseAccessorDeclaration(bool isEvent) { if (this.IsIncrementalAndFactoryContextMatches && SyntaxFacts.IsAccessorDeclaration(this.CurrentNodeKind)) { return (AccessorDeclarationSyntax)this.EatNode(); } var accMods = _pool.Allocate(); try { var accAttrs = this.ParseAttributeDeclarations(); this.ParseModifiers(accMods, forAccessors: true); // check availability of readonly members feature for accessors CheckForVersionSpecificModifiers(accMods, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyMembers); if (!isEvent) { if (accMods != null && accMods.Count > 0) { accMods[0] = CheckFeatureAvailability(accMods[0], MessageID.IDS_FeaturePropertyAccessorMods); } } var accessorName = this.EatToken(SyntaxKind.IdentifierToken, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected); var accessorKind = GetAccessorKind(accessorName); // Only convert the identifier to a keyword if it's a valid one. Otherwise any // other contextual keyword (like 'partial') will be converted into a keyword // and will be invalid. if (accessorKind == SyntaxKind.UnknownAccessorDeclaration) { // We'll have an UnknownAccessorDeclaration either because we didn't have // an IdentifierToken or because we have an IdentifierToken which is not // add/remove/get/set. In the former case, we'll already have reported // an error and will have a missing token. But in the latter case we need // to report that the identifier is incorrect. if (!accessorName.IsMissing) { accessorName = this.AddError(accessorName, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected); } else { Debug.Assert(accessorName.ContainsDiagnostics); } } else { accessorName = ConvertToKeyword(accessorName); } BlockSyntax blockBody = null; ArrowExpressionClauseSyntax expressionBody = null; SyntaxToken semicolon = null; bool currentTokenIsSemicolon = this.CurrentToken.Kind == SyntaxKind.SemicolonToken; bool currentTokenIsArrow = this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken; bool currentTokenIsOpenBraceToken = this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; if (currentTokenIsOpenBraceToken || currentTokenIsArrow) { this.ParseBlockAndExpressionBodiesWithSemicolon( out blockBody, out expressionBody, out semicolon, requestedExpressionBodyFeature: MessageID.IDS_FeatureExpressionBodiedAccessor); } else if (currentTokenIsSemicolon) { semicolon = EatAccessorSemicolon(); } else { // We didn't get something we recognized. If we got an accessor type we // recognized (i.e. get/set/init/add/remove) then try to parse out a block. // Only do this if it doesn't seem like we're at the end of the accessor/property. // for example, if we have "get set", don't actually try to parse out the // block. Otherwise we'll consume the 'set'. In that case, just end the // current accessor with a semicolon so we can properly consume the next // in the calling method's loop. if (accessorKind != SyntaxKind.UnknownAccessorDeclaration) { if (!IsTerminator()) { blockBody = this.ParseMethodOrAccessorBodyBlock(attributes: default, isAccessorBody: true); } else { semicolon = EatAccessorSemicolon(); } } else { // Don't bother eating anything if we didn't even have a valid accessor. // It will just lead to more errors. Note: we will have already produced // a good error by now. Debug.Assert(accessorName.ContainsDiagnostics); } } return _syntaxFactory.AccessorDeclaration( accessorKind, accAttrs, accMods.ToList(), accessorName, blockBody, expressionBody, semicolon); } finally { _pool.Free(accMods); } } private SyntaxToken EatAccessorSemicolon() => this.EatToken(SyntaxKind.SemicolonToken, IsFeatureEnabled(MessageID.IDS_FeatureExpressionBodiedAccessor) ? ErrorCode.ERR_SemiOrLBraceOrArrowExpected : ErrorCode.ERR_SemiOrLBraceExpected); private SyntaxKind GetAccessorKind(SyntaxToken accessorName) { switch (accessorName.ContextualKind) { case SyntaxKind.GetKeyword: return SyntaxKind.GetAccessorDeclaration; case SyntaxKind.SetKeyword: return SyntaxKind.SetAccessorDeclaration; case SyntaxKind.InitKeyword: return SyntaxKind.InitAccessorDeclaration; case SyntaxKind.AddKeyword: return SyntaxKind.AddAccessorDeclaration; case SyntaxKind.RemoveKeyword: return SyntaxKind.RemoveAccessorDeclaration; } return SyntaxKind.UnknownAccessorDeclaration; } internal ParameterListSyntax ParseParenthesizedParameterList() { if (this.IsIncrementalAndFactoryContextMatches && CanReuseParameterList(this.CurrentNode as CSharp.Syntax.ParameterListSyntax)) { return (ParameterListSyntax)this.EatNode(); } var parameters = _pool.AllocateSeparated<ParameterSyntax>(); try { var openKind = SyntaxKind.OpenParenToken; var closeKind = SyntaxKind.CloseParenToken; SyntaxToken open; SyntaxToken close; this.ParseParameterList(out open, parameters, out close, openKind, closeKind); return _syntaxFactory.ParameterList(open, parameters, close); } finally { _pool.Free(parameters); } } internal BracketedParameterListSyntax ParseBracketedParameterList() { if (this.IsIncrementalAndFactoryContextMatches && CanReuseBracketedParameterList(this.CurrentNode as CSharp.Syntax.BracketedParameterListSyntax)) { return (BracketedParameterListSyntax)this.EatNode(); } var parameters = _pool.AllocateSeparated<ParameterSyntax>(); try { var openKind = SyntaxKind.OpenBracketToken; var closeKind = SyntaxKind.CloseBracketToken; SyntaxToken open; SyntaxToken close; this.ParseParameterList(out open, parameters, out close, openKind, closeKind); return _syntaxFactory.BracketedParameterList(open, parameters, close); } finally { _pool.Free(parameters); } } private static bool CanReuseParameterList(CSharp.Syntax.ParameterListSyntax list) { if (list == null) { return false; } if (list.OpenParenToken.IsMissing) { return false; } if (list.CloseParenToken.IsMissing) { return false; } foreach (var parameter in list.Parameters) { if (!CanReuseParameter(parameter)) { return false; } } return true; } private static bool CanReuseBracketedParameterList(CSharp.Syntax.BracketedParameterListSyntax list) { if (list == null) { return false; } if (list.OpenBracketToken.IsMissing) { return false; } if (list.CloseBracketToken.IsMissing) { return false; } foreach (var parameter in list.Parameters) { if (!CanReuseParameter(parameter)) { return false; } } return true; } private void ParseParameterList( out SyntaxToken open, SeparatedSyntaxListBuilder<ParameterSyntax> nodes, out SyntaxToken close, SyntaxKind openKind, SyntaxKind closeKind) { open = this.EatToken(openKind); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfParameterList; if (this.CurrentToken.Kind != closeKind) { tryAgain: if (this.IsPossibleParameter() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first parameter var parameter = this.ParseParameter(); nodes.Add(parameter); // additional parameters while (true) { if (this.CurrentToken.Kind == closeKind) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleParameter()) { nodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); parameter = this.ParseParameter(); if (parameter.IsMissing && this.IsPossibleParameter()) { // ensure we always consume tokens parameter = AddTrailingSkippedSyntax(parameter, this.EatToken()); } nodes.Add(parameter); continue; } else if (this.SkipBadParameterListTokens(ref open, nodes, SyntaxKind.CommaToken, closeKind) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadParameterListTokens(ref open, nodes, SyntaxKind.IdentifierToken, closeKind) == PostSkipAction.Continue) { goto tryAgain; } } _termState = saveTerm; close = this.EatToken(closeKind); } private bool IsEndOfParameterList() { return this.CurrentToken.Kind is SyntaxKind.CloseParenToken or SyntaxKind.CloseBracketToken or SyntaxKind.SemicolonToken; } private PostSkipAction SkipBadParameterListTokens( ref SyntaxToken open, SeparatedSyntaxListBuilder<ParameterSyntax> list, SyntaxKind expected, SyntaxKind closeKind) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref open, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleParameter(), p => p.CurrentToken.Kind == closeKind || p.IsTerminator(), expected); } private bool IsPossibleParameter() { switch (this.CurrentToken.Kind) { case SyntaxKind.OpenBracketToken: // attribute case SyntaxKind.ArgListKeyword: case SyntaxKind.OpenParenToken: // tuple case SyntaxKind.DelegateKeyword when IsFunctionPointerStart(): // Function pointer type return true; case SyntaxKind.IdentifierToken: return this.IsTrueIdentifier(); default: return IsParameterModifier(this.CurrentToken.Kind) || IsPredefinedType(this.CurrentToken.Kind); } } private static bool CanReuseParameter(CSharp.Syntax.ParameterSyntax parameter) { if (parameter == null) { return false; } // cannot reuse a node that possibly ends in an expression if (parameter.Default != null) { return false; } // cannot reuse lambda parameters as normal parameters (parsed with // different rules) CSharp.CSharpSyntaxNode parent = parameter.Parent; if (parent != null) { if (parent.Kind() == SyntaxKind.SimpleLambdaExpression) { return false; } CSharp.CSharpSyntaxNode grandparent = parent.Parent; if (grandparent != null && grandparent.Kind() == SyntaxKind.ParenthesizedLambdaExpression) { Debug.Assert(parent.Kind() == SyntaxKind.ParameterList); return false; } } return true; } private ParameterSyntax ParseParameter() { if (this.IsIncrementalAndFactoryContextMatches && CanReuseParameter(this.CurrentNode as CSharp.Syntax.ParameterSyntax)) { return (ParameterSyntax)this.EatNode(); } var attributes = this.ParseAttributeDeclarations(); var modifiers = _pool.Allocate(); try { this.ParseParameterModifiers(modifiers); TypeSyntax type; SyntaxToken name; if (this.CurrentToken.Kind != SyntaxKind.ArgListKeyword) { type = this.ParseType(mode: ParseTypeMode.Parameter); name = this.ParseIdentifierToken(); // When the user type "int goo[]", give them a useful error if (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken && this.PeekToken(1).Kind == SyntaxKind.CloseBracketToken) { var open = this.EatToken(); var close = this.EatToken(); open = this.AddError(open, ErrorCode.ERR_BadArraySyntax); name = AddTrailingSkippedSyntax(name, SyntaxList.List(open, close)); } } else { // We store an __arglist parameter as a parameter with null type and whose // .Identifier has the kind ArgListKeyword. type = null; name = this.EatToken(SyntaxKind.ArgListKeyword); } EqualsValueClauseSyntax def = null; if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { var equals = this.EatToken(SyntaxKind.EqualsToken); var value = this.ParseExpressionCore(); def = _syntaxFactory.EqualsValueClause(equals, value: value); def = CheckFeatureAvailability(def, MessageID.IDS_FeatureOptionalParameter); } return _syntaxFactory.Parameter(attributes, modifiers.ToList(), type, name, def); } finally { _pool.Free(modifiers); } } private static bool IsParameterModifier(SyntaxKind kind, bool isFunctionPointerParameter = false) { switch (kind) { case SyntaxKind.ThisKeyword: case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: case SyntaxKind.ParamsKeyword: case SyntaxKind.ReadOnlyKeyword when isFunctionPointerParameter: return true; } return false; } private void ParseParameterModifiers(SyntaxListBuilder modifiers, bool isFunctionPointerParameter = false) { while (IsParameterModifier(this.CurrentToken.Kind, isFunctionPointerParameter)) { var modifier = this.EatToken(); switch (modifier.Kind) { case SyntaxKind.ThisKeyword: modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureExtensionMethod); if (this.CurrentToken.Kind == SyntaxKind.RefKeyword || this.CurrentToken.Kind == SyntaxKind.InKeyword) { modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureRefExtensionMethods); } break; case SyntaxKind.RefKeyword: { if (this.CurrentToken.Kind == SyntaxKind.ThisKeyword) { modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureRefExtensionMethods); } break; } case SyntaxKind.InKeyword: { modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureReadOnlyReferences); if (this.CurrentToken.Kind == SyntaxKind.ThisKeyword) { modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureRefExtensionMethods); } break; } } modifiers.Add(modifier); } } private FieldDeclarationSyntax ParseFixedSizeBufferDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.FixedKeyword); var fixedToken = this.EatToken(); fixedToken = CheckFeatureAvailability(fixedToken, MessageID.IDS_FeatureFixedBuffer); modifiers.Add(fixedToken); var type = this.ParseType(); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFieldDeclaration; var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseVariableDeclarators(type, VariableFlags.Fixed, variables, parentKind); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.FieldDeclaration( attributes, modifiers.ToList(), _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _termState = saveTerm; _pool.Free(variables); } } private MemberDeclarationSyntax ParseEventDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.EventKeyword); var eventToken = this.EatToken(); var type = this.ParseType(); if (IsFieldDeclaration(isEvent: true)) { return this.ParseEventFieldDeclaration(attributes, modifiers, eventToken, type, parentKind); } else { return this.ParseEventDeclarationWithAccessors(attributes, modifiers, eventToken, type); } } private EventDeclarationSyntax ParseEventDeclarationWithAccessors( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxToken eventToken, TypeSyntax type) { ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; SyntaxToken identifierOrThisOpt; TypeParameterListSyntax typeParameterList; this.ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterList, isEvent: true); // check availability of readonly members feature for custom events CheckForVersionSpecificModifiers(modifiers, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyMembers); // If we got an explicitInterfaceOpt but not an identifier, then we're in the special // case for ERR_ExplicitEventFieldImpl (see ParseMemberName for details). if (explicitInterfaceOpt != null && this.CurrentToken.Kind != SyntaxKind.OpenBraceToken && this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { Debug.Assert(typeParameterList == null, "Exit condition of ParseMemberName in this scenario"); // No need for a diagnostic, ParseMemberName has already added one. var missingIdentifier = (identifierOrThisOpt == null) ? CreateMissingIdentifierToken() : identifierOrThisOpt; var missingAccessorList = _syntaxFactory.AccessorList( SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken), default(SyntaxList<AccessorDeclarationSyntax>), SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)); return _syntaxFactory.EventDeclaration( attributes, modifiers.ToList(), eventToken, type, explicitInterfaceOpt, //already has an appropriate error attached missingIdentifier, missingAccessorList, semicolonToken: null); } SyntaxToken identifier; if (identifierOrThisOpt == null) { identifier = CreateMissingIdentifierToken(); } else if (identifierOrThisOpt.Kind != SyntaxKind.IdentifierToken) { Debug.Assert(identifierOrThisOpt.Kind == SyntaxKind.ThisKeyword); identifier = ConvertToMissingWithTrailingTrivia(identifierOrThisOpt, SyntaxKind.IdentifierToken); } else { identifier = identifierOrThisOpt; } Debug.Assert(identifier != null); Debug.Assert(identifier.Kind == SyntaxKind.IdentifierToken); if (identifier.IsMissing && !type.IsMissing) { identifier = this.AddError(identifier, ErrorCode.ERR_IdentifierExpected); } if (typeParameterList != null) // check to see if the user tried to create a generic event. { identifier = AddTrailingSkippedSyntax(identifier, typeParameterList); identifier = this.AddError(identifier, ErrorCode.ERR_UnexpectedGenericName); } AccessorListSyntax accessorList = null; SyntaxToken semicolon = null; if (explicitInterfaceOpt != null && this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatToken(SyntaxKind.SemicolonToken); } else { accessorList = this.ParseAccessorList(isEvent: true); } var decl = _syntaxFactory.EventDeclaration( attributes, modifiers.ToList(), eventToken, type, explicitInterfaceOpt, identifier, accessorList, semicolon); decl = EatUnexpectedTrailingSemicolon(decl); return decl; } private TNode EatUnexpectedTrailingSemicolon<TNode>(TNode decl) where TNode : CSharpSyntaxNode { // allow for case of one unexpected semicolon... if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { var semi = this.EatToken(); semi = this.AddError(semi, ErrorCode.ERR_UnexpectedSemicolon); decl = AddTrailingSkippedSyntax(decl, semi); } return decl; } private FieldDeclarationSyntax ParseNormalFieldDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, SyntaxKind parentKind) { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFieldDeclaration; var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseVariableDeclarators(type, flags: 0, variables: variables, parentKind: parentKind); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.FieldDeclaration( attributes, modifiers.ToList(), _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _termState = saveTerm; _pool.Free(variables); } } private EventFieldDeclarationSyntax ParseEventFieldDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxToken eventToken, TypeSyntax type, SyntaxKind parentKind) { // An attribute specified on an event declaration that omits event accessors can apply // to the event being declared, to the associated field (if the event is not abstract), // or to the associated add and remove methods. In the absence of an // attribute-target-specifier, the attribute applies to the event. The presence of the // event attribute-target-specifier indicates that the attribute applies to the event; // the presence of the field attribute-target-specifier indicates that the attribute // applies to the field; and the presence of the method attribute-target-specifier // indicates that the attribute applies to the methods. // // NOTE(cyrusn): We allow more than the above here. Specifically, even if the event is // abstract, we allow the attribute to specify that it belongs to a field. Later, in the // semantic pass, we will disallow this. var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFieldDeclaration; var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseVariableDeclarators(type, flags: 0, variables: variables, parentKind: parentKind); if (this.CurrentToken.Kind == SyntaxKind.DotToken) { eventToken = this.AddError(eventToken, ErrorCode.ERR_ExplicitEventFieldImpl); // Better error message for confusing event situation. } var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.EventFieldDeclaration( attributes, modifiers.ToList(), eventToken, _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _termState = saveTerm; _pool.Free(variables); } } private bool IsEndOfFieldDeclaration() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken; } private void ParseVariableDeclarators(TypeSyntax type, VariableFlags flags, SeparatedSyntaxListBuilder<VariableDeclaratorSyntax> variables, SyntaxKind parentKind) { // Although we try parse variable declarations in contexts where they are not allowed (non-interactive top-level or a namespace) // the reported errors should take into consideration whether or not one expects them in the current context. bool variableDeclarationsExpected = parentKind != SyntaxKind.NamespaceDeclaration && parentKind != SyntaxKind.FileScopedNamespaceDeclaration && (parentKind != SyntaxKind.CompilationUnit || IsScript); LocalFunctionStatementSyntax localFunction; ParseVariableDeclarators( type: type, flags: flags, variables: variables, variableDeclarationsExpected: variableDeclarationsExpected, allowLocalFunctions: false, attributes: default, mods: default, localFunction: out localFunction); Debug.Assert(localFunction == null); } private void ParseVariableDeclarators( TypeSyntax type, VariableFlags flags, SeparatedSyntaxListBuilder<VariableDeclaratorSyntax> variables, bool variableDeclarationsExpected, bool allowLocalFunctions, SyntaxList<AttributeListSyntax> attributes, SyntaxList<SyntaxToken> mods, out LocalFunctionStatementSyntax localFunction) { variables.Add( this.ParseVariableDeclarator( type, flags, isFirst: true, allowLocalFunctions: allowLocalFunctions, attributes: attributes, mods: mods, localFunction: out localFunction)); if (localFunction != null) { // ParseVariableDeclarator returns null, so it is not added to variables Debug.Assert(variables.Count == 0); return; } while (true) { if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { variables.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); variables.Add( this.ParseVariableDeclarator( type, flags, isFirst: false, allowLocalFunctions: false, attributes: attributes, mods: mods, localFunction: out localFunction)); } else if (!variableDeclarationsExpected || this.SkipBadVariableListTokens(variables, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } private PostSkipAction SkipBadVariableListTokens(SeparatedSyntaxListBuilder<VariableDeclaratorSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken, p => p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsTerminator(), expected); } [Flags] private enum VariableFlags { Fixed = 0x01, Const = 0x02, Local = 0x04 } private static SyntaxTokenList GetOriginalModifiers(CSharp.CSharpSyntaxNode decl) { if (decl != null) { switch (decl.Kind()) { case SyntaxKind.FieldDeclaration: return ((CSharp.Syntax.FieldDeclarationSyntax)decl).Modifiers; case SyntaxKind.MethodDeclaration: return ((CSharp.Syntax.MethodDeclarationSyntax)decl).Modifiers; case SyntaxKind.ConstructorDeclaration: return ((CSharp.Syntax.ConstructorDeclarationSyntax)decl).Modifiers; case SyntaxKind.DestructorDeclaration: return ((CSharp.Syntax.DestructorDeclarationSyntax)decl).Modifiers; case SyntaxKind.PropertyDeclaration: return ((CSharp.Syntax.PropertyDeclarationSyntax)decl).Modifiers; case SyntaxKind.EventFieldDeclaration: return ((CSharp.Syntax.EventFieldDeclarationSyntax)decl).Modifiers; case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return ((CSharp.Syntax.AccessorDeclarationSyntax)decl).Modifiers; case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((CSharp.Syntax.TypeDeclarationSyntax)decl).Modifiers; case SyntaxKind.DelegateDeclaration: return ((CSharp.Syntax.DelegateDeclarationSyntax)decl).Modifiers; } } return default(SyntaxTokenList); } private static bool WasFirstVariable(CSharp.Syntax.VariableDeclaratorSyntax variable) { var parent = GetOldParent(variable) as CSharp.Syntax.VariableDeclarationSyntax; if (parent != null) { return parent.Variables[0] == variable; } return false; } private static VariableFlags GetOriginalVariableFlags(CSharp.Syntax.VariableDeclaratorSyntax old) { var parent = GetOldParent(old); var mods = GetOriginalModifiers(parent); VariableFlags flags = default(VariableFlags); if (mods.Any(SyntaxKind.FixedKeyword)) { flags |= VariableFlags.Fixed; } if (mods.Any(SyntaxKind.ConstKeyword)) { flags |= VariableFlags.Const; } if (parent != null && (parent.Kind() == SyntaxKind.VariableDeclaration || parent.Kind() == SyntaxKind.LocalDeclarationStatement)) { flags |= VariableFlags.Local; } return flags; } private static bool CanReuseVariableDeclarator(CSharp.Syntax.VariableDeclaratorSyntax old, VariableFlags flags, bool isFirst) { if (old == null) { return false; } SyntaxKind oldKind; return (flags == GetOriginalVariableFlags(old)) && (isFirst == WasFirstVariable(old)) && old.Initializer == null // can't reuse node that possibly ends in an expression && (oldKind = GetOldParent(old).Kind()) != SyntaxKind.VariableDeclaration // or in a method body && oldKind != SyntaxKind.LocalDeclarationStatement; } private VariableDeclaratorSyntax ParseVariableDeclarator( TypeSyntax parentType, VariableFlags flags, bool isFirst, bool allowLocalFunctions, SyntaxList<AttributeListSyntax> attributes, SyntaxList<SyntaxToken> mods, out LocalFunctionStatementSyntax localFunction, bool isExpressionContext = false) { if (this.IsIncrementalAndFactoryContextMatches && CanReuseVariableDeclarator(this.CurrentNode as CSharp.Syntax.VariableDeclaratorSyntax, flags, isFirst)) { localFunction = null; return (VariableDeclaratorSyntax)this.EatNode(); } if (!isExpressionContext) { // Check for the common pattern of: // // C //<-- here // Console.WriteLine(); // // Standard greedy parsing will assume that this should be parsed as a variable // declaration: "C Console". We want to avoid that as it can confused parts of the // system further up. So, if we see certain things following the identifier, then we can // assume it's not the actual name. // // So, if we're after a newline and we see a name followed by the list below, then we // assume that we're accidentally consuming too far into the next statement. // // <dot>, <arrow>, any binary operator (except =), <question>. None of these characters // are allowed in a normal variable declaration. This also provides a more useful error // message to the user. Instead of telling them that a semicolon is expected after the // following token, then instead get a useful message about an identifier being missing. // The above list prevents: // // C //<-- here // Console.WriteLine(); // // C //<-- here // Console->WriteLine(); // // C // A + B; // // C // A ? B : D; // // C // A() var resetPoint = this.GetResetPoint(); try { var currentTokenKind = this.CurrentToken.Kind; if (currentTokenKind == SyntaxKind.IdentifierToken && !parentType.IsMissing) { var isAfterNewLine = parentType.GetLastToken().TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia); if (isAfterNewLine) { int offset, width; this.GetDiagnosticSpanForMissingToken(out offset, out width); this.EatToken(); currentTokenKind = this.CurrentToken.Kind; var isNonEqualsBinaryToken = currentTokenKind != SyntaxKind.EqualsToken && SyntaxFacts.IsBinaryExpressionOperatorToken(currentTokenKind); if (currentTokenKind == SyntaxKind.DotToken || currentTokenKind == SyntaxKind.OpenParenToken || currentTokenKind == SyntaxKind.MinusGreaterThanToken || isNonEqualsBinaryToken) { var isPossibleLocalFunctionToken = currentTokenKind == SyntaxKind.OpenParenToken || currentTokenKind == SyntaxKind.LessThanToken; // Make sure this isn't a local function if (!isPossibleLocalFunctionToken || !IsLocalFunctionAfterIdentifier()) { var missingIdentifier = CreateMissingIdentifierToken(); missingIdentifier = this.AddError(missingIdentifier, offset, width, ErrorCode.ERR_IdentifierExpected); localFunction = null; return _syntaxFactory.VariableDeclarator(missingIdentifier, null, null); } } } } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } // NOTE: Diverges from Dev10. // // When we see parse an identifier and we see the partial contextual keyword, we check // to see whether it is already attached to a partial class or partial method // declaration. However, in the specific case of variable declarators, Dev10 // specifically treats it as a variable name, even if it could be interpreted as a // keyword. var name = this.ParseIdentifierToken(); BracketedArgumentListSyntax argumentList = null; EqualsValueClauseSyntax initializer = null; TerminatorState saveTerm = _termState; bool isFixed = (flags & VariableFlags.Fixed) != 0; bool isConst = (flags & VariableFlags.Const) != 0; bool isLocal = (flags & VariableFlags.Local) != 0; // Give better error message in the case where the user did something like: // // X x = 1, Y y = 2; // using (X x = expr1, Y y = expr2) ... // // The superfluous type name is treated as variable (it is an identifier) and a missing ',' is injected after it. if (!isFirst && this.IsTrueIdentifier()) { name = this.AddError(name, ErrorCode.ERR_MultiTypeInDeclaration); } switch (this.CurrentToken.Kind) { case SyntaxKind.EqualsToken: if (isFixed) { goto default; } var equals = this.EatToken(); SyntaxToken refKeyword = null; if (isLocal && !isConst && this.CurrentToken.Kind == SyntaxKind.RefKeyword) { refKeyword = this.EatToken(); refKeyword = CheckFeatureAvailability(refKeyword, MessageID.IDS_FeatureRefLocalsReturns); } var init = this.ParseVariableInitializer(); if (refKeyword != null) { init = _syntaxFactory.RefExpression(refKeyword, init); } initializer = _syntaxFactory.EqualsValueClause(equals, init); break; case SyntaxKind.LessThanToken: if (allowLocalFunctions && isFirst) { localFunction = TryParseLocalFunctionStatementBody(attributes, mods, parentType, name); if (localFunction != null) { return null; } } goto default; case SyntaxKind.OpenParenToken: if (allowLocalFunctions && isFirst) { localFunction = TryParseLocalFunctionStatementBody(attributes, mods, parentType, name); if (localFunction != null) { return null; } } // Special case for accidental use of C-style constructors // Fake up something to hold the arguments. _termState |= TerminatorState.IsPossibleEndOfVariableDeclaration; argumentList = this.ParseBracketedArgumentList(); _termState = saveTerm; argumentList = this.AddError(argumentList, ErrorCode.ERR_BadVarDecl); break; case SyntaxKind.OpenBracketToken: bool sawNonOmittedSize; _termState |= TerminatorState.IsPossibleEndOfVariableDeclaration; var specifier = this.ParseArrayRankSpecifier(sawNonOmittedSize: out sawNonOmittedSize); _termState = saveTerm; var open = specifier.OpenBracketToken; var sizes = specifier.Sizes; var close = specifier.CloseBracketToken; if (isFixed && !sawNonOmittedSize) { close = this.AddError(close, ErrorCode.ERR_ValueExpected); } var args = _pool.AllocateSeparated<ArgumentSyntax>(); try { var withSeps = sizes.GetWithSeparators(); foreach (var item in withSeps) { var expression = item as ExpressionSyntax; if (expression != null) { bool isOmitted = expression.Kind == SyntaxKind.OmittedArraySizeExpression; if (!isFixed && !isOmitted) { expression = this.AddError(expression, ErrorCode.ERR_ArraySizeInDeclaration); } args.Add(_syntaxFactory.Argument(null, refKindKeyword: null, expression)); } else { args.AddSeparator((SyntaxToken)item); } } argumentList = _syntaxFactory.BracketedArgumentList(open, args, close); if (!isFixed) { argumentList = this.AddError(argumentList, ErrorCode.ERR_CStyleArray); // If we have "int x[] = new int[10];" then parse the initializer. if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { goto case SyntaxKind.EqualsToken; } } } finally { _pool.Free(args); } break; default: if (isConst) { name = this.AddError(name, ErrorCode.ERR_ConstValueRequired); // Error here for missing constant initializers } else if (isFixed) { if (parentType.Kind == SyntaxKind.ArrayType) { // They accidentally put the array before the identifier name = this.AddError(name, ErrorCode.ERR_FixedDimsRequired); } else { goto case SyntaxKind.OpenBracketToken; } } break; } localFunction = null; return _syntaxFactory.VariableDeclarator(name, argumentList, initializer); } // Is there a local function after an eaten identifier? private bool IsLocalFunctionAfterIdentifier() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.OpenParenToken || this.CurrentToken.Kind == SyntaxKind.LessThanToken); var resetPoint = this.GetResetPoint(); try { var typeParameterListOpt = this.ParseTypeParameterList(); var paramList = ParseParenthesizedParameterList(); if (!paramList.IsMissing && (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken || this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword)) { return true; } return false; } finally { Reset(ref resetPoint); Release(ref resetPoint); } } private bool IsPossibleEndOfVariableDeclaration() { switch (this.CurrentToken.Kind) { case SyntaxKind.CommaToken: case SyntaxKind.SemicolonToken: return true; default: return false; } } private ExpressionSyntax ParseVariableInitializer() { switch (this.CurrentToken.Kind) { case SyntaxKind.OpenBraceToken: return this.ParseArrayInitializer(); default: return this.ParseExpressionCore(); } } private bool IsPossibleVariableInitializer() { return this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.IsPossibleExpression(); } private FieldDeclarationSyntax ParseConstantFieldDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) { var constToken = this.EatToken(SyntaxKind.ConstKeyword); modifiers.Add(constToken); var type = this.ParseType(); var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseVariableDeclarators(type, VariableFlags.Const, variables, parentKind); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.FieldDeclaration( attributes, modifiers.ToList(), _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _pool.Free(variables); } } private DelegateDeclarationSyntax ParseDelegateDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.DelegateKeyword); var delegateToken = this.EatToken(SyntaxKind.DelegateKeyword); var type = this.ParseReturnType(); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfMethodSignature; var name = this.ParseIdentifierToken(); var typeParameters = this.ParseTypeParameterList(); var parameterList = this.ParseParenthesizedParameterList(); var constraints = default(SyntaxListBuilder<TypeParameterConstraintClauseSyntax>); try { if (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { constraints = _pool.Allocate<TypeParameterConstraintClauseSyntax>(); this.ParseTypeParameterConstraintClauses(constraints); } _termState = saveTerm; var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.DelegateDeclaration(attributes, modifiers.ToList(), delegateToken, type, name, typeParameters, parameterList, constraints, semicolon); } finally { if (!constraints.IsNull) { _pool.Free(constraints); } } } private EnumDeclarationSyntax ParseEnumDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.EnumKeyword); var enumToken = this.EatToken(SyntaxKind.EnumKeyword); var name = this.ParseIdentifierToken(); // check to see if the user tried to create a generic enum. var typeParameters = this.ParseTypeParameterList(); if (typeParameters != null) { name = AddTrailingSkippedSyntax(name, typeParameters); name = this.AddError(name, ErrorCode.ERR_UnexpectedGenericName); } BaseListSyntax baseList = null; if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { var colon = this.EatToken(SyntaxKind.ColonToken); var type = this.ParseType(); var tmpList = _pool.AllocateSeparated<BaseTypeSyntax>(); tmpList.Add(_syntaxFactory.SimpleBaseType(type)); baseList = _syntaxFactory.BaseList(colon, tmpList); _pool.Free(tmpList); } var members = default(SeparatedSyntaxList<EnumMemberDeclarationSyntax>); var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); if (!openBrace.IsMissing) { var builder = _pool.AllocateSeparated<EnumMemberDeclarationSyntax>(); try { this.ParseEnumMemberDeclarations(ref openBrace, builder); members = builder.ToList(); } finally { _pool.Free(builder); } } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); var semicolon = TryEatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.EnumDeclaration( attributes, modifiers.ToList(), enumToken, name, baseList, openBrace, members, closeBrace, semicolon); } private void ParseEnumMemberDeclarations( ref SyntaxToken openBrace, SeparatedSyntaxListBuilder<EnumMemberDeclarationSyntax> members) { if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsPossibleEnumMemberDeclaration() || this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { // first member members.Add(this.ParseEnumMemberDeclaration()); // additional members while (true) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.IsPossibleEnumMemberDeclaration()) { if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { // semicolon instead of comma.. consume it with error and act as if it were a comma. members.AddSeparator(this.EatTokenWithPrejudice(SyntaxKind.CommaToken)); } else { members.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); } // check for exit case after legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (!this.IsPossibleEnumMemberDeclaration()) { goto tryAgain; } members.Add(this.ParseEnumMemberDeclaration()); continue; } else if (this.SkipBadEnumMemberListTokens(ref openBrace, members, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadEnumMemberListTokens(ref openBrace, members, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } } private PostSkipAction SkipBadEnumMemberListTokens(ref SyntaxToken openBrace, SeparatedSyntaxListBuilder<EnumMemberDeclarationSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openBrace, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && p.CurrentToken.Kind != SyntaxKind.SemicolonToken && !p.IsPossibleEnumMemberDeclaration(), p => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken || p.IsTerminator(), expected); } private EnumMemberDeclarationSyntax ParseEnumMemberDeclaration() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.EnumMemberDeclaration) { return (EnumMemberDeclarationSyntax)this.EatNode(); } var memberAttrs = this.ParseAttributeDeclarations(); var memberName = this.ParseIdentifierToken(); EqualsValueClauseSyntax equalsValue = null; if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { var equals = this.EatToken(SyntaxKind.EqualsToken); ExpressionSyntax value; if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { //an identifier is a valid expression value = this.ParseIdentifierName(ErrorCode.ERR_ConstantExpected); } else { value = this.ParseExpressionCore(); } equalsValue = _syntaxFactory.EqualsValueClause(equals, value: value); } return _syntaxFactory.EnumMemberDeclaration(memberAttrs, modifiers: default, memberName, equalsValue); } private bool IsPossibleEnumMemberDeclaration() { return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken || this.IsTrueIdentifier(); } private bool IsDotOrColonColon() { return this.CurrentToken.Kind == SyntaxKind.DotToken || this.CurrentToken.Kind == SyntaxKind.ColonColonToken; } // This is public and parses open types. You probably don't want to use it. public NameSyntax ParseName() { return this.ParseQualifiedName(); } private IdentifierNameSyntax CreateMissingIdentifierName() { return _syntaxFactory.IdentifierName(CreateMissingIdentifierToken()); } private static SyntaxToken CreateMissingIdentifierToken() { return SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken); } [Flags] private enum NameOptions { None = 0, InExpression = 1 << 0, // Used to influence parser ambiguity around "<" and generics vs. expressions. Used in ParseSimpleName. InTypeList = 1 << 1, // Allows attributes to appear within the generic type argument list. Used during ParseInstantiation. PossiblePattern = 1 << 2, // Used to influence parser ambiguity around "<" and generics vs. expressions on the right of 'is' AfterIs = 1 << 3, DefinitePattern = 1 << 4, AfterOut = 1 << 5, AfterTupleComma = 1 << 6, FirstElementOfPossibleTupleLiteral = 1 << 7, } /// <summary> /// True if current identifier token is not really some contextual keyword /// </summary> /// <returns></returns> private bool IsTrueIdentifier() { if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken) { if (!IsCurrentTokenPartialKeywordOfPartialMethodOrType() && !IsCurrentTokenQueryKeywordInQuery() && !IsCurrentTokenWhereOfConstraintClause()) { return true; } } return false; } /// <summary> /// True if the given token is not really some contextual keyword. /// This method is for use in executable code, as it treats <c>partial</c> as an identifier. /// </summary> private bool IsTrueIdentifier(SyntaxToken token) { return token.Kind == SyntaxKind.IdentifierToken && !(this.IsInQuery && IsTokenQueryContextualKeyword(token)); } private IdentifierNameSyntax ParseIdentifierName(ErrorCode code = ErrorCode.ERR_IdentifierExpected) { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.IdentifierName) { if (!SyntaxFacts.IsContextualKeyword(((CSharp.Syntax.IdentifierNameSyntax)this.CurrentNode).Identifier.Kind())) { return (IdentifierNameSyntax)this.EatNode(); } } var tk = ParseIdentifierToken(code); return SyntaxFactory.IdentifierName(tk); } private SyntaxToken ParseIdentifierToken(ErrorCode code = ErrorCode.ERR_IdentifierExpected) { var ctk = this.CurrentToken.Kind; if (ctk == SyntaxKind.IdentifierToken) { // Error tolerance for IntelliSense. Consider the following case: [EditorBrowsable( partial class Goo { // } Because we're parsing an attribute argument we'll end up consuming the "partial" identifier and // we'll eventually end up in a pretty confused state. Because of that it becomes very difficult to // show the correct parameter help in this case. So, when we see "partial" we check if it's being used // as an identifier or as a contextual keyword. If it's the latter then we bail out. See // Bug: vswhidbey/542125 if (IsCurrentTokenPartialKeywordOfPartialMethodOrType() || IsCurrentTokenQueryKeywordInQuery()) { var result = CreateMissingIdentifierToken(); result = this.AddError(result, ErrorCode.ERR_InvalidExprTerm, this.CurrentToken.Text); return result; } SyntaxToken identifierToken = this.EatToken(); if (this.IsInAsync && identifierToken.ContextualKind == SyntaxKind.AwaitKeyword) { identifierToken = this.AddError(identifierToken, ErrorCode.ERR_BadAwaitAsIdentifier); } return identifierToken; } else { var name = CreateMissingIdentifierToken(); name = this.AddError(name, code); return name; } } private bool IsCurrentTokenQueryKeywordInQuery() { return this.IsInQuery && this.IsCurrentTokenQueryContextualKeyword; } private bool IsCurrentTokenPartialKeywordOfPartialMethodOrType() { if (this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword) { if (this.IsPartialType() || this.IsPartialMember()) { return true; } } return false; } private TypeParameterListSyntax ParseTypeParameterList() { if (this.CurrentToken.Kind != SyntaxKind.LessThanToken) { return null; } var saveTerm = _termState; _termState |= TerminatorState.IsEndOfTypeParameterList; try { var parameters = _pool.AllocateSeparated<TypeParameterSyntax>(); var open = this.EatToken(SyntaxKind.LessThanToken); open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics); // first parameter parameters.Add(this.ParseTypeParameter()); // remaining parameter & commas while (true) { if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken || this.IsCurrentTokenWhereOfConstraintClause()) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { parameters.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); parameters.Add(this.ParseTypeParameter()); } else if (this.SkipBadTypeParameterListTokens(parameters, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } var close = this.EatToken(SyntaxKind.GreaterThanToken); return _syntaxFactory.TypeParameterList(open, parameters, close); } finally { _termState = saveTerm; } } private PostSkipAction SkipBadTypeParameterListTokens(SeparatedSyntaxListBuilder<TypeParameterSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken, p => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken || p.IsTerminator(), expected); } private TypeParameterSyntax ParseTypeParameter() { if (this.IsCurrentTokenWhereOfConstraintClause()) { return _syntaxFactory.TypeParameter( default(SyntaxList<AttributeListSyntax>), varianceKeyword: null, this.AddError(CreateMissingIdentifierToken(), ErrorCode.ERR_IdentifierExpected)); } var attrs = default(SyntaxList<AttributeListSyntax>); if (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken && this.PeekToken(1).Kind != SyntaxKind.CloseBracketToken) { var saveTerm = _termState; _termState = TerminatorState.IsEndOfTypeArgumentList; attrs = this.ParseAttributeDeclarations(); _termState = saveTerm; } SyntaxToken varianceToken = null; if (this.CurrentToken.Kind == SyntaxKind.InKeyword || this.CurrentToken.Kind == SyntaxKind.OutKeyword) { varianceToken = CheckFeatureAvailability(this.EatToken(), MessageID.IDS_FeatureTypeVariance); } return _syntaxFactory.TypeParameter(attrs, varianceToken, this.ParseIdentifierToken()); } // Parses the parts of the names between Dots and ColonColons. private SimpleNameSyntax ParseSimpleName(NameOptions options = NameOptions.None) { var id = this.ParseIdentifierName(); if (id.Identifier.IsMissing) { return id; } // You can pass ignore generics if you don't even want the parser to consider generics at all. // The name parsing will then stop at the first "<". It doesn't make sense to pass both Generic and IgnoreGeneric. SimpleNameSyntax name = id; if (this.CurrentToken.Kind == SyntaxKind.LessThanToken) { var pt = this.GetResetPoint(); var kind = this.ScanTypeArgumentList(options); this.Reset(ref pt); this.Release(ref pt); if (kind == ScanTypeArgumentListKind.DefiniteTypeArgumentList || (kind == ScanTypeArgumentListKind.PossibleTypeArgumentList && (options & NameOptions.InTypeList) != 0)) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.LessThanToken); SyntaxToken open; var types = _pool.AllocateSeparated<TypeSyntax>(); SyntaxToken close; this.ParseTypeArgumentList(out open, types, out close); name = _syntaxFactory.GenericName(id.Identifier, _syntaxFactory.TypeArgumentList(open, types, close)); _pool.Free(types); } } return name; } private enum ScanTypeArgumentListKind { NotTypeArgumentList, PossibleTypeArgumentList, DefiniteTypeArgumentList } private ScanTypeArgumentListKind ScanTypeArgumentList(NameOptions options) { if (this.CurrentToken.Kind != SyntaxKind.LessThanToken) { return ScanTypeArgumentListKind.NotTypeArgumentList; } if ((options & NameOptions.InExpression) == 0) { return ScanTypeArgumentListKind.DefiniteTypeArgumentList; } // We're in an expression context, and we have a < token. This could be a // type argument list, or it could just be a relational expression. // // Scan just the type argument list portion (i.e. the part from < to > ) to // see what we think it could be. This will give us one of three possibilities: // // result == ScanTypeFlags.NotType. // // This is absolutely not a type-argument-list. Just return that result immediately. // // result != ScanTypeFlags.NotType && isDefinitelyTypeArgumentList. // // This is absolutely a type-argument-list. Just return that result immediately // // result != ScanTypeFlags.NotType && !isDefinitelyTypeArgumentList. // // This could be a type-argument list, or it could be an expression. Need to see // what came after the last '>' to find out which it is. // Scan for a type argument list. If we think it's a type argument list // then assume it is unless we see specific tokens following it. SyntaxToken lastTokenOfList = null; ScanTypeFlags possibleTypeArgumentFlags = ScanPossibleTypeArgumentList( ref lastTokenOfList, out bool isDefinitelyTypeArgumentList); if (possibleTypeArgumentFlags == ScanTypeFlags.NotType) { return ScanTypeArgumentListKind.NotTypeArgumentList; } if (isDefinitelyTypeArgumentList) { return ScanTypeArgumentListKind.DefiniteTypeArgumentList; } // If we did not definitively determine from immediate syntax that it was or // was not a type argument list, we must have scanned the entire thing up through // the closing greater-than token. In that case we will disambiguate based on the // token that follows it. Debug.Assert(lastTokenOfList.Kind == SyntaxKind.GreaterThanToken); switch (this.CurrentToken.Kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.CloseParenToken: case SyntaxKind.CloseBracketToken: case SyntaxKind.CloseBraceToken: case SyntaxKind.ColonToken: case SyntaxKind.SemicolonToken: case SyntaxKind.CommaToken: case SyntaxKind.DotToken: case SyntaxKind.QuestionToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.BarToken: case SyntaxKind.CaretToken: // These tokens are from 7.5.4.2 Grammar Ambiguities return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.AmpersandAmpersandToken: // e.g. `e is A<B> && e` case SyntaxKind.BarBarToken: // e.g. `e is A<B> || e` case SyntaxKind.AmpersandToken: // e.g. `e is A<B> & e` case SyntaxKind.OpenBracketToken: // e.g. `e is A<B>[]` case SyntaxKind.LessThanToken: // e.g. `e is A<B> < C` case SyntaxKind.LessThanEqualsToken: // e.g. `e is A<B> <= C` case SyntaxKind.GreaterThanEqualsToken: // e.g. `e is A<B> >= C` case SyntaxKind.IsKeyword: // e.g. `e is A<B> is bool` case SyntaxKind.AsKeyword: // e.g. `e is A<B> as bool` // These tokens were added to 7.5.4.2 Grammar Ambiguities in C# 7.0 return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.OpenBraceToken: // e.g. `e is A<B> {}` // This token was added to 7.5.4.2 Grammar Ambiguities in C# 8.0 return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.GreaterThanToken when ((options & NameOptions.AfterIs) != 0) && this.PeekToken(1).Kind != SyntaxKind.GreaterThanToken: // This token is added to 7.5.4.2 Grammar Ambiguities in C#7 for the special case in which // the possible generic is following an `is` keyword, e.g. `e is A<B> > C`. // We test one further token ahead because a right-shift operator `>>` looks like a pair of greater-than // tokens at this stage, but we don't intend to be handling the right-shift operator. // The upshot is that we retain compatibility with the two previous behaviors: // `(x is A<B>>C)` is parsed as `(x is A<B>) > C` // `A<B>>C` elsewhere is parsed as `A < (B >> C)` return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.IdentifierToken: // C#7: In certain contexts, we treat *identifier* as a disambiguating token. Those // contexts are where the sequence of tokens being disambiguated is immediately preceded by one // of the keywords is, case, or out, or arises while parsing the first element of a tuple literal // (in which case the tokens are preceded by `(` and the identifier is followed by a `,`) or a // subsequent element of a tuple literal (in which case the tokens are preceded by `,` and the // identifier is followed by a `,` or `)`). // In C#8 (or whenever recursive patterns are introduced) we also treat an identifier as a // disambiguating token if we're parsing the type of a pattern. // Note that we treat query contextual keywords (which appear here as identifiers) as disambiguating tokens as well. if ((options & (NameOptions.AfterIs | NameOptions.DefinitePattern | NameOptions.AfterOut)) != 0 || (options & NameOptions.AfterTupleComma) != 0 && (this.PeekToken(1).Kind == SyntaxKind.CommaToken || this.PeekToken(1).Kind == SyntaxKind.CloseParenToken) || (options & NameOptions.FirstElementOfPossibleTupleLiteral) != 0 && this.PeekToken(1).Kind == SyntaxKind.CommaToken ) { // we allow 'G<T,U> x' as a pattern-matching operation and a declaration expression in a tuple. return ScanTypeArgumentListKind.DefiniteTypeArgumentList; } return ScanTypeArgumentListKind.PossibleTypeArgumentList; case SyntaxKind.EndOfFileToken: // e.g. `e is A<B>` // This is useful for parsing expressions in isolation return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.EqualsGreaterThanToken: // e.g. `e switch { A<B> => 1 }` // This token was added to 7.5.4.2 Grammar Ambiguities in C# 9.0 return ScanTypeArgumentListKind.DefiniteTypeArgumentList; default: return ScanTypeArgumentListKind.PossibleTypeArgumentList; } } private ScanTypeFlags ScanPossibleTypeArgumentList( ref SyntaxToken lastTokenOfList, out bool isDefinitelyTypeArgumentList) { isDefinitelyTypeArgumentList = false; if (this.CurrentToken.Kind == SyntaxKind.LessThanToken) { ScanTypeFlags result = ScanTypeFlags.GenericTypeOrExpression; do { lastTokenOfList = this.EatToken(); // Type arguments cannot contain attributes, so if this is an open square, we early out and assume it is not a type argument if (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken) { lastTokenOfList = null; return ScanTypeFlags.NotType; } if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken) { lastTokenOfList = EatToken(); return result; } switch (this.ScanType(out lastTokenOfList)) { case ScanTypeFlags.NotType: lastTokenOfList = null; return ScanTypeFlags.NotType; case ScanTypeFlags.MustBeType: // We're currently scanning a possible type-argument list. But we're // not sure if this is actually a type argument list, or is maybe some // complex relational expression with <'s and >'s. One thing we can // tell though is that if we have a predefined type (like 'int' or 'string') // before a comma or > then this is definitely a type argument list. i.e. // if you have: // // var v = ImmutableDictionary<int, // // then there's no legal interpretation of this as an expression (since a // standalone predefined type is not a valid simple term. Contrast that // with : // // var v = ImmutableDictionary<Int32, // // Here this might actually be a relational expression and the comma is meant // to separate out the variable declarator 'v' from the next variable. // // Note: we check if we got 'MustBeType' which triggers for predefined types, // (int, string, etc.), or array types (Goo[], A<T>[][] etc.), or pointer types // of things that must be types (int*, void**, etc.). isDefinitelyTypeArgumentList = DetermineIfDefinitelyTypeArgumentList(isDefinitelyTypeArgumentList); result = ScanTypeFlags.GenericTypeOrMethod; break; // case ScanTypeFlags.TupleType: // It would be nice if we saw a tuple to state that we definitely had a // type argument list. However, there are cases where this would not be // true. For example: // // public class C // { // public static void Main() // { // XX X = default; // int a = 1, b = 2; // bool z = X < (a, b), w = false; // } // } // // struct XX // { // public static bool operator <(XX x, (int a, int b) arg) => true; // public static bool operator >(XX x, (int a, int b) arg) => false; // } case ScanTypeFlags.NullableType: // See above. If we have X<Y?, or X<Y?>, then this is definitely a type argument list. isDefinitelyTypeArgumentList = DetermineIfDefinitelyTypeArgumentList(isDefinitelyTypeArgumentList); if (isDefinitelyTypeArgumentList) { result = ScanTypeFlags.GenericTypeOrMethod; } // Note: we intentionally fall out without setting 'result'. // Seeing a nullable type (not followed by a , or > ) is not enough // information for us to determine what this is yet. i.e. the user may have: // // X < Y ? Z : W // // We'd see a nullable type here, but this is definitely not a type arg list. break; case ScanTypeFlags.GenericTypeOrExpression: // See above. If we have X<Y<Z>, then this would definitely be a type argument list. // However, if we have X<Y<Z>> then this might not be type argument list. This could just // be some sort of expression where we're comparing, and then shifting values. if (!isDefinitelyTypeArgumentList) { isDefinitelyTypeArgumentList = this.CurrentToken.Kind == SyntaxKind.CommaToken; result = ScanTypeFlags.GenericTypeOrMethod; } break; case ScanTypeFlags.GenericTypeOrMethod: result = ScanTypeFlags.GenericTypeOrMethod; break; } } while (this.CurrentToken.Kind == SyntaxKind.CommaToken); if (this.CurrentToken.Kind != SyntaxKind.GreaterThanToken) { lastTokenOfList = null; return ScanTypeFlags.NotType; } lastTokenOfList = this.EatToken(); return result; } return ScanTypeFlags.NonGenericTypeOrExpression; } private bool DetermineIfDefinitelyTypeArgumentList(bool isDefinitelyTypeArgumentList) { if (!isDefinitelyTypeArgumentList) { isDefinitelyTypeArgumentList = this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.GreaterThanToken; } return isDefinitelyTypeArgumentList; } // ParseInstantiation: Parses the generic argument/parameter parts of the name. private void ParseTypeArgumentList(out SyntaxToken open, SeparatedSyntaxListBuilder<TypeSyntax> types, out SyntaxToken close) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.LessThanToken); open = this.EatToken(SyntaxKind.LessThanToken); open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics); if (this.IsOpenName()) { // NOTE: trivia will be attached to comma, not omitted type argument var omittedTypeArgumentInstance = _syntaxFactory.OmittedTypeArgument(SyntaxFactory.Token(SyntaxKind.OmittedTypeArgumentToken)); types.Add(omittedTypeArgumentInstance); while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { types.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); types.Add(omittedTypeArgumentInstance); } close = this.EatToken(SyntaxKind.GreaterThanToken); return; } // first type types.Add(this.ParseTypeArgument()); // remaining types & commas while (true) { if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleType()) { types.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); types.Add(this.ParseTypeArgument()); } else if (this.SkipBadTypeArgumentListTokens(types, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } close = this.EatToken(SyntaxKind.GreaterThanToken); } private PostSkipAction SkipBadTypeArgumentListTokens(SeparatedSyntaxListBuilder<TypeSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleType(), p => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken || p.IsTerminator(), expected); } // Parses the individual generic parameter/arguments in a name. private TypeSyntax ParseTypeArgument() { var attrs = default(SyntaxList<AttributeListSyntax>); if (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken && this.PeekToken(1).Kind != SyntaxKind.CloseBracketToken) { // Here, if we see a "[" that looks like it has something in it, we parse // it as an attribute and then later put an error on the whole type if // it turns out that attributes are not allowed. // TODO: should there be another flag that controls this behavior? we have // "allowAttrs" but should there also be a "recognizeAttrs" that we can // set to false in an expression context? var saveTerm = _termState; _termState = TerminatorState.IsEndOfTypeArgumentList; attrs = this.ParseAttributeDeclarations(); _termState = saveTerm; } SyntaxToken varianceToken = null; if (this.CurrentToken.Kind == SyntaxKind.InKeyword || this.CurrentToken.Kind == SyntaxKind.OutKeyword) { // Recognize the variance syntax, but give an error as it's // only appropriate in a type parameter list. varianceToken = this.EatToken(); varianceToken = CheckFeatureAvailability(varianceToken, MessageID.IDS_FeatureTypeVariance); varianceToken = this.AddError(varianceToken, ErrorCode.ERR_IllegalVarianceSyntax); } var result = this.ParseType(); // Consider the case where someone supplies an invalid type argument // Such as Action<0> or Action<static>. In this case we generate a missing // identifier in ParseType, but if we continue as is we'll immediately start to // interpret 0 as the start of a new expression when we can tell it's most likely // meant to be part of the type list. // // To solve this we check if the current token is not comma or greater than and // the next token is a comma or greater than. If so we assume that the found // token is part of this expression and we attempt to recover. This does open // the door for cases where we have an incomplete line to be interpretted as // a single expression. For example: // // Action< // Incomplete line // a>b; // // However, this only happens when the following expression is of the form a>... // or a,... which means this case should happen less frequently than what we're // trying to solve here so we err on the side of better error messages // for the majority of cases. SyntaxKind nextTokenKind = SyntaxKind.None; if (result.IsMissing && (this.CurrentToken.Kind != SyntaxKind.CommaToken && this.CurrentToken.Kind != SyntaxKind.GreaterThanToken) && ((nextTokenKind = this.PeekToken(1).Kind) == SyntaxKind.CommaToken || nextTokenKind == SyntaxKind.GreaterThanToken)) { // Eat the current token and add it as skipped so we recover result = AddTrailingSkippedSyntax(result, this.EatToken()); } if (varianceToken != null) { result = AddLeadingSkippedSyntax(result, varianceToken); } if (attrs.Count > 0) { result = AddLeadingSkippedSyntax(result, attrs.Node); result = this.AddError(result, ErrorCode.ERR_TypeExpected); } return result; } private bool IsEndOfTypeArgumentList() => this.CurrentToken.Kind == SyntaxKind.GreaterThanToken; private bool IsOpenName() { bool isOpen = true; int n = 0; while (this.PeekToken(n).Kind == SyntaxKind.CommaToken) { n++; } if (this.PeekToken(n).Kind != SyntaxKind.GreaterThanToken) { isOpen = false; } return isOpen; } private void ParseMemberName( out ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, out SyntaxToken identifierOrThisOpt, out TypeParameterListSyntax typeParameterListOpt, bool isEvent) { identifierOrThisOpt = null; explicitInterfaceOpt = null; typeParameterListOpt = null; if (!IsPossibleMemberName()) { // No clue what this is. Just bail. Our caller will have to // move forward and try again. return; } NameSyntax explicitInterfaceName = null; SyntaxToken separator = null; ResetPoint beforeIdentifierPoint = default(ResetPoint); bool beforeIdentifierPointSet = false; try { while (true) { // Check if we got 'this'. If so, then we have an indexer. // Note: we parse out type parameters here as well so that // we can give a useful error about illegal generic indexers. if (this.CurrentToken.Kind == SyntaxKind.ThisKeyword) { beforeIdentifierPoint = GetResetPoint(); beforeIdentifierPointSet = true; identifierOrThisOpt = this.EatToken(); typeParameterListOpt = this.ParseTypeParameterList(); break; } // now, scan past the next name. if it's followed by a dot then // it's part of the explicit name we're building up. Otherwise, // it's the name of the member. var point = GetResetPoint(); bool isMemberName; try { ScanNamedTypePart(); isMemberName = !IsDotOrColonColonOrDotDot(); } finally { this.Reset(ref point); this.Release(ref point); } if (isMemberName) { // We're past any explicit interface portion and We've // gotten to the member name. beforeIdentifierPoint = GetResetPoint(); beforeIdentifierPointSet = true; if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) { separator = this.AddError(separator, ErrorCode.ERR_AliasQualAsExpression); separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } identifierOrThisOpt = this.ParseIdentifierToken(); typeParameterListOpt = this.ParseTypeParameterList(); break; } else { // If we saw a . or :: then we must have something explicit. AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator); } } if (explicitInterfaceName != null) { if (separator.Kind != SyntaxKind.DotToken) { separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, separator.GetLeadingTriviaWidth(), separator.Width)); separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } if (isEvent && this.CurrentToken.Kind != SyntaxKind.OpenBraceToken && this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { // CS0071: If you're explicitly implementing an event field, you have to use the accessor form // // Good: // event EventDelegate Parent.E // { // add { ... } // remove { ... } // } // // Bad: // event EventDelegate Parent. // E( //(or anything that is not the semicolon // // To recover: rollback to before the name of the field was parsed (just the part after the last // dot), insert a missing identifier for the field name, insert missing accessors, and then treat // the event name that's actually there as the beginning of a new member. e.g. // // event EventDelegate Parent./*Missing nodes here*/ // // E( // // Rationale: The identifier could be the name of a type at the beginning of an existing member // declaration (above which someone has started to type an explicit event implementation). // // In case the dot doesn't follow with an end line or E ends with a semicolon, the error recovery // is skipped. In that case the rationale above does not fit very well. explicitInterfaceOpt = _syntaxFactory.ExplicitInterfaceSpecifier( explicitInterfaceName, AddError(separator, ErrorCode.ERR_ExplicitEventFieldImpl)); if (separator.TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia)) { Debug.Assert(beforeIdentifierPointSet); Reset(ref beforeIdentifierPoint); //clear fields that were populated after the reset point identifierOrThisOpt = null; typeParameterListOpt = null; } } else { explicitInterfaceOpt = _syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator); } } } finally { if (beforeIdentifierPointSet) { Release(ref beforeIdentifierPoint); } } } private void AccumulateExplicitInterfaceName(ref NameSyntax explicitInterfaceName, ref SyntaxToken separator, bool reportAnErrorOnMisplacedColonColon = false) { // first parse the upcoming name portion. var saveTerm = _termState; _termState |= TerminatorState.IsEndOfNameInExplicitInterface; if (explicitInterfaceName == null) { // If this is the first time, then just get the next simple // name and store it as the explicit interface name. explicitInterfaceName = this.ParseSimpleName(NameOptions.InTypeList); // Now, get the next separator. if (this.CurrentToken.Kind == SyntaxKind.DotDotToken) { // Error recovery as in ParseQualifiedNameRight. If we have `X..Y` break that into `X.<missing-id>.Y` separator = this.EatToken(); explicitInterfaceName = RecoverFromDotDot(explicitInterfaceName, ref separator); } else { separator = this.CurrentToken.Kind == SyntaxKind.ColonColonToken ? this.EatToken() // fine after the first identifier : this.EatToken(SyntaxKind.DotToken); } } else { // Parse out the next part and combine it with the // current explicit name to form the new explicit name. var tmp = this.ParseQualifiedNameRight(NameOptions.InTypeList, explicitInterfaceName, separator); Debug.Assert(!ReferenceEquals(tmp, explicitInterfaceName), "We should have consumed something and updated explicitInterfaceName"); explicitInterfaceName = tmp; // Now, get the next separator. if (this.CurrentToken.Kind == SyntaxKind.ColonColonToken) { separator = this.EatToken(); if (reportAnErrorOnMisplacedColonColon) { // The https://github.com/dotnet/roslyn/issues/53021 is tracking fixing this in general separator = this.AddError(separator, ErrorCode.ERR_UnexpectedAliasedName); } separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } else if (this.CurrentToken.Kind == SyntaxKind.DotDotToken) { // Error recovery as in ParseQualifiedNameRight. If we have `X..Y` break that into `X.<missing-id>.Y` separator = this.EatToken(); explicitInterfaceName = RecoverFromDotDot(explicitInterfaceName, ref separator); } else { separator = this.EatToken(SyntaxKind.DotToken); } } _termState = saveTerm; } /// <summary> /// This is an adjusted version of <see cref="ParseMemberName"/>. /// When it returns true, it stops at operator keyword (<see cref="IsOperatorKeyword"/>). /// When it returns false, it does not advance in the token stream. /// </summary> private bool IsOperatorStart(out ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, bool advanceParser = true) { explicitInterfaceOpt = null; if (IsOperatorKeyword()) { return true; } if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return false; } NameSyntax explicitInterfaceName = null; SyntaxToken separator = null; ResetPoint beforeIdentifierPoint = GetResetPoint(); try { while (true) { // now, scan past the next name. if it's followed by a dot then // it's part of the explicit name we're building up. Otherwise, // it should be an operator token var point = GetResetPoint(); bool isPartOfInterfaceName; try { if (IsOperatorKeyword()) { isPartOfInterfaceName = false; } else { ScanNamedTypePart(); // If we have part of the interface name, but no dot before the operator token, then // for the purpose of error recovery, treat this as an operator start with a // missing dot token. isPartOfInterfaceName = IsDotOrColonColonOrDotDot() || IsOperatorKeyword(); } } finally { this.Reset(ref point); this.Release(ref point); } if (!isPartOfInterfaceName) { // We're past any explicit interface portion if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) { separator = this.AddError(separator, ErrorCode.ERR_AliasQualAsExpression); separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } break; } else { // If we saw a . or :: then we must have something explicit. AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator, reportAnErrorOnMisplacedColonColon: true); } } if (!IsOperatorKeyword() || explicitInterfaceName is null) { Reset(ref beforeIdentifierPoint); return false; } if (!advanceParser) { Reset(ref beforeIdentifierPoint); return true; } if (separator.Kind != SyntaxKind.DotToken) { separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, separator.GetLeadingTriviaWidth(), separator.Width)); separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } explicitInterfaceOpt = CheckFeatureAvailability(_syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator), MessageID.IDS_FeatureStaticAbstractMembersInInterfaces); return true; } finally { Release(ref beforeIdentifierPoint); } } private NameSyntax ParseAliasQualifiedName(NameOptions allowedParts = NameOptions.None) { NameSyntax name = this.ParseSimpleName(allowedParts); if (this.CurrentToken.Kind == SyntaxKind.ColonColonToken) { var token = this.EatToken(); name = ParseQualifiedNameRight(allowedParts, name, token); } return name; } private NameSyntax ParseQualifiedName(NameOptions options = NameOptions.None) { NameSyntax name = this.ParseAliasQualifiedName(options); // Handle .. tokens for error recovery purposes. while (IsDotOrColonColonOrDotDot()) { if (this.PeekToken(1).Kind == SyntaxKind.ThisKeyword) { break; } var separator = this.EatToken(); name = ParseQualifiedNameRight(options, name, separator); } return name; } private bool IsDotOrColonColonOrDotDot() { return this.IsDotOrColonColon() || this.CurrentToken.Kind == SyntaxKind.DotDotToken; } private NameSyntax ParseQualifiedNameRight( NameOptions options, NameSyntax left, SyntaxToken separator) { Debug.Assert( separator.Kind == SyntaxKind.DotToken || separator.Kind == SyntaxKind.DotDotToken || separator.Kind == SyntaxKind.ColonColonToken); var right = this.ParseSimpleName(options); switch (separator.Kind) { case SyntaxKind.DotToken: return _syntaxFactory.QualifiedName(left, separator, right); case SyntaxKind.DotDotToken: // Error recovery. If we have `X..Y` break that into `X.<missing-id>.Y` return _syntaxFactory.QualifiedName(RecoverFromDotDot(left, ref separator), separator, right); case SyntaxKind.ColonColonToken: if (left.Kind != SyntaxKind.IdentifierName) { separator = this.AddError(separator, ErrorCode.ERR_UnexpectedAliasedName, separator.ToString()); } // If the left hand side is not an identifier name then the user has done // something like Goo.Bar::Blah. We've already made an error node for the // ::, so just pretend that they typed Goo.Bar.Blah and continue on. var identifierLeft = left as IdentifierNameSyntax; if (identifierLeft == null) { separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); return _syntaxFactory.QualifiedName(left, separator, right); } else { if (identifierLeft.Identifier.ContextualKind == SyntaxKind.GlobalKeyword) { identifierLeft = _syntaxFactory.IdentifierName(ConvertToKeyword(identifierLeft.Identifier)); } identifierLeft = CheckFeatureAvailability(identifierLeft, MessageID.IDS_FeatureGlobalNamespace); // If the name on the right had errors or warnings then we need to preserve // them in the tree. return WithAdditionalDiagnostics(_syntaxFactory.AliasQualifiedName(identifierLeft, separator, right), left.GetDiagnostics()); } default: throw ExceptionUtilities.Unreachable; } } private NameSyntax RecoverFromDotDot(NameSyntax left, ref SyntaxToken separator) { Debug.Assert(separator.Kind == SyntaxKind.DotDotToken); var leftDot = SyntaxFactory.Token(separator.LeadingTrivia.Node, SyntaxKind.DotToken, null); var missingName = this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected); separator = SyntaxFactory.Token(null, SyntaxKind.DotToken, separator.TrailingTrivia.Node); return _syntaxFactory.QualifiedName(left, leftDot, missingName); } private SyntaxToken ConvertToMissingWithTrailingTrivia(SyntaxToken token, SyntaxKind expectedKind) { var newToken = SyntaxFactory.MissingToken(expectedKind); newToken = AddTrailingSkippedSyntax(newToken, token); return newToken; } private enum ScanTypeFlags { /// <summary> /// Definitely not a type name. /// </summary> NotType, /// <summary> /// Definitely a type name: either a predefined type (int, string, etc.) or an array /// type (ending with a [] brackets), or a pointer type (ending with *s), or a function /// pointer type (ending with > in valid cases, or a *, ), or calling convention /// identifier, in invalid cases). /// </summary> MustBeType, /// <summary> /// Might be a generic (qualified) type name or a method name. /// </summary> GenericTypeOrMethod, /// <summary> /// Might be a generic (qualified) type name or an expression or a method name. /// </summary> GenericTypeOrExpression, /// <summary> /// Might be a non-generic (qualified) type name or an expression. /// </summary> NonGenericTypeOrExpression, /// <summary> /// A type name with alias prefix (Alias::Name). Note that Alias::Name.X would not fall under this. This /// only is returned for exactly Alias::Name. /// </summary> AliasQualifiedName, /// <summary> /// Nullable type (ending with ?). /// </summary> NullableType, /// <summary> /// Might be a pointer type or a multiplication. /// </summary> PointerOrMultiplication, /// <summary> /// Might be a tuple type. /// </summary> TupleType, } private bool IsPossibleType() { var tk = this.CurrentToken.Kind; return IsPredefinedType(tk) || this.IsTrueIdentifier(); } private ScanTypeFlags ScanType(bool forPattern = false) { return ScanType(out _, forPattern); } private ScanTypeFlags ScanType(out SyntaxToken lastTokenOfType, bool forPattern = false) { return ScanType(forPattern ? ParseTypeMode.DefinitePattern : ParseTypeMode.Normal, out lastTokenOfType); } private void ScanNamedTypePart() { SyntaxToken lastTokenOfType; ScanNamedTypePart(out lastTokenOfType); } private ScanTypeFlags ScanNamedTypePart(out SyntaxToken lastTokenOfType) { if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken || !this.IsTrueIdentifier()) { lastTokenOfType = null; return ScanTypeFlags.NotType; } lastTokenOfType = this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.LessThanToken) { return this.ScanPossibleTypeArgumentList(ref lastTokenOfType, out _); } else { return ScanTypeFlags.NonGenericTypeOrExpression; } } private ScanTypeFlags ScanType(ParseTypeMode mode, out SyntaxToken lastTokenOfType) { Debug.Assert(mode != ParseTypeMode.NewExpression); ScanTypeFlags result; bool isFunctionPointer = false; if (this.CurrentToken.Kind == SyntaxKind.RefKeyword) { // in a ref local or ref return, we treat "ref" and "ref readonly" as part of the type this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword) { this.EatToken(); } } // Handle :: as well for error case of an alias used without a preceding identifier. if (this.CurrentToken.Kind is SyntaxKind.IdentifierToken or SyntaxKind.ColonColonToken) { bool isAlias; if (this.CurrentToken.Kind is SyntaxKind.ColonColonToken) { result = ScanTypeFlags.NonGenericTypeOrExpression; // Definitely seems like an alias if we're starting with a :: isAlias = true; // We set this to null to appease the flow checker. It will always be the case that this will be // set to an appropriate value inside the `for` loop below. We'll consume the :: there and then // call ScanNamedTypePart which will always set this to a valid value. lastTokenOfType = null; } else { Debug.Assert(this.CurrentToken.Kind is SyntaxKind.IdentifierToken); // We're an alias if we start with an: id:: isAlias = this.PeekToken(1).Kind == SyntaxKind.ColonColonToken; result = this.ScanNamedTypePart(out lastTokenOfType); if (result == ScanTypeFlags.NotType) { return ScanTypeFlags.NotType; } Debug.Assert(result is ScanTypeFlags.GenericTypeOrExpression or ScanTypeFlags.GenericTypeOrMethod or ScanTypeFlags.NonGenericTypeOrExpression); } // Scan a name for (bool firstLoop = true; IsDotOrColonColon(); firstLoop = false) { // If we consume any more dots or colons, don't consider us an alias anymore. For dots, we now have // x::y.z (which is now back to a normal expr/type, not an alias), and for colons that means we have // x::y::z or x.y::z both of which are effectively gibberish. if (!firstLoop) { isAlias = false; } this.EatToken(); result = this.ScanNamedTypePart(out lastTokenOfType); if (result == ScanTypeFlags.NotType) { return ScanTypeFlags.NotType; } Debug.Assert(result is ScanTypeFlags.GenericTypeOrExpression or ScanTypeFlags.GenericTypeOrMethod or ScanTypeFlags.NonGenericTypeOrExpression); } if (isAlias) { result = ScanTypeFlags.AliasQualifiedName; } } else if (IsPredefinedType(this.CurrentToken.Kind)) { // Simple type... lastTokenOfType = this.EatToken(); result = ScanTypeFlags.MustBeType; } else if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { lastTokenOfType = this.EatToken(); result = this.ScanTupleType(out lastTokenOfType); if (result == ScanTypeFlags.NotType || mode == ParseTypeMode.DefinitePattern && this.CurrentToken.Kind != SyntaxKind.OpenBracketToken) { // A tuple type can appear in a pattern only if it is the element type of an array type. return ScanTypeFlags.NotType; } } else if (IsFunctionPointerStart()) { isFunctionPointer = true; result = ScanFunctionPointerType(out lastTokenOfType); } else { // Can't be a type! lastTokenOfType = null; return ScanTypeFlags.NotType; } int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { switch (this.CurrentToken.Kind) { case SyntaxKind.QuestionToken when lastTokenOfType.Kind != SyntaxKind.QuestionToken && // don't allow `Type??` lastTokenOfType.Kind != SyntaxKind.AsteriskToken && // don't allow `Type*?` !isFunctionPointer: // don't allow `delegate*<...>?` lastTokenOfType = this.EatToken(); result = ScanTypeFlags.NullableType; break; case SyntaxKind.AsteriskToken when lastTokenOfType.Kind != SyntaxKind.CloseBracketToken: // don't allow `Type[]*` // Check for pointer type(s) switch (mode) { case ParseTypeMode.FirstElementOfPossibleTupleLiteral: case ParseTypeMode.AfterTupleComma: // We are parsing the type for a declaration expression in a tuple, which does // not permit pointer types except as an element type of an array type. // In that context a `*` is parsed as a multiplication. if (PointerTypeModsFollowedByRankAndDimensionSpecifier()) { goto default; } goto done; case ParseTypeMode.DefinitePattern: // pointer type syntax is not supported in patterns. goto done; default: lastTokenOfType = this.EatToken(); isFunctionPointer = false; if (result == ScanTypeFlags.GenericTypeOrExpression || result == ScanTypeFlags.NonGenericTypeOrExpression) { result = ScanTypeFlags.PointerOrMultiplication; } else if (result == ScanTypeFlags.GenericTypeOrMethod) { result = ScanTypeFlags.MustBeType; } break; } break; case SyntaxKind.OpenBracketToken: // Check for array types. this.EatToken(); while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { this.EatToken(); } if (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { lastTokenOfType = null; return ScanTypeFlags.NotType; } lastTokenOfType = this.EatToken(); isFunctionPointer = false; result = ScanTypeFlags.MustBeType; break; default: goto done; } } done: return result; } /// <summary> /// Returns TupleType when a possible tuple type is found. /// Note that this is not MustBeType, so that the caller can consider deconstruction syntaxes. /// The caller is expected to have consumed the opening paren. /// </summary> private ScanTypeFlags ScanTupleType(out SyntaxToken lastTokenOfType) { var tupleElementType = ScanType(out lastTokenOfType); if (tupleElementType != ScanTypeFlags.NotType) { if (IsTrueIdentifier()) { lastTokenOfType = this.EatToken(); } if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { do { lastTokenOfType = this.EatToken(); tupleElementType = ScanType(out lastTokenOfType); if (tupleElementType == ScanTypeFlags.NotType) { lastTokenOfType = this.EatToken(); return ScanTypeFlags.NotType; } if (IsTrueIdentifier()) { lastTokenOfType = this.EatToken(); } } while (this.CurrentToken.Kind == SyntaxKind.CommaToken); if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken) { lastTokenOfType = this.EatToken(); return ScanTypeFlags.TupleType; } } } // Can't be a type! lastTokenOfType = null; return ScanTypeFlags.NotType; } #nullable enable private ScanTypeFlags ScanFunctionPointerType(out SyntaxToken lastTokenOfType) { Debug.Assert(IsFunctionPointerStart()); _ = EatToken(SyntaxKind.DelegateKeyword); lastTokenOfType = EatToken(SyntaxKind.AsteriskToken); TerminatorState saveTerm; if (CurrentToken.Kind == SyntaxKind.IdentifierToken) { var peek1 = PeekToken(1); switch (CurrentToken) { case { ContextualKind: SyntaxKind.ManagedKeyword }: case { ContextualKind: SyntaxKind.UnmanagedKeyword }: case var _ when IsPossibleFunctionPointerParameterListStart(peek1): case var _ when peek1.Kind == SyntaxKind.OpenBracketToken: lastTokenOfType = EatToken(); break; default: // Whatever is next, it's probably not part of the type. We know that delegate* must be // a function pointer start, however, so say the asterisk is the last element and bail return ScanTypeFlags.MustBeType; } if (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { lastTokenOfType = EatToken(SyntaxKind.OpenBracketToken); saveTerm = _termState; _termState |= TerminatorState.IsEndOfFunctionPointerCallingConvention; try { while (true) { lastTokenOfType = TryEatToken(SyntaxKind.IdentifierToken) ?? lastTokenOfType; if (skipBadFunctionPointerTokens() == PostSkipAction.Abort) { break; } Debug.Assert(CurrentToken.Kind == SyntaxKind.CommaToken); lastTokenOfType = EatToken(); } lastTokenOfType = TryEatToken(SyntaxKind.CloseBracketToken) ?? lastTokenOfType; } finally { _termState = saveTerm; } } } if (!IsPossibleFunctionPointerParameterListStart(CurrentToken)) { // Even though this function pointer type is incomplete, we know that it // must be the start of a type, as there is no other possible interpretation // of delegate*. By always treating it as a type, we ensure that any disambiguation // done in later parsing treats this as a type, which will produce better // errors at later stages. return ScanTypeFlags.MustBeType; } var validStartingToken = EatToken().Kind == SyntaxKind.LessThanToken; saveTerm = _termState; _termState |= validStartingToken ? TerminatorState.IsEndOfFunctionPointerParameterList : TerminatorState.IsEndOfFunctionPointerParameterListErrored; var ignoredModifiers = _pool.Allocate<SyntaxToken>(); try { do { ParseParameterModifiers(ignoredModifiers, isFunctionPointerParameter: true); ignoredModifiers.Clear(); _ = ScanType(out _); if (skipBadFunctionPointerTokens() == PostSkipAction.Abort) { break; } _ = EatToken(SyntaxKind.CommaToken); } while (true); } finally { _termState = saveTerm; _pool.Free(ignoredModifiers); } if (!validStartingToken && CurrentToken.Kind == SyntaxKind.CloseParenToken) { lastTokenOfType = EatTokenAsKind(SyntaxKind.GreaterThanToken); } else { lastTokenOfType = EatToken(SyntaxKind.GreaterThanToken); } return ScanTypeFlags.MustBeType; PostSkipAction skipBadFunctionPointerTokens() { return SkipBadTokensWithExpectedKind(isNotExpectedFunction: p => p.CurrentToken.Kind != SyntaxKind.CommaToken, abortFunction: p => p.IsTerminator(), expected: SyntaxKind.CommaToken, trailingTrivia: out _); } } #nullable disable private static bool IsPredefinedType(SyntaxKind keyword) { return SyntaxFacts.IsPredefinedType(keyword); } public TypeSyntax ParseTypeName() { return ParseType(); } private TypeSyntax ParseTypeOrVoid() { if (this.CurrentToken.Kind == SyntaxKind.VoidKeyword && this.PeekToken(1).Kind != SyntaxKind.AsteriskToken) { // Must be 'void' type, so create such a type node and return it. return _syntaxFactory.PredefinedType(this.EatToken()); } return this.ParseType(); } private enum ParseTypeMode { Normal, Parameter, AfterIs, DefinitePattern, AfterOut, AfterRef, AfterTupleComma, AsExpression, NewExpression, FirstElementOfPossibleTupleLiteral, } private TypeSyntax ParseType(ParseTypeMode mode = ParseTypeMode.Normal) { if (this.CurrentToken.Kind == SyntaxKind.RefKeyword) { var refKeyword = this.EatToken(); refKeyword = this.CheckFeatureAvailability(refKeyword, MessageID.IDS_FeatureRefLocalsReturns); SyntaxToken readonlyKeyword = null; if (this.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword) { readonlyKeyword = this.EatToken(); readonlyKeyword = this.CheckFeatureAvailability(readonlyKeyword, MessageID.IDS_FeatureReadOnlyReferences); } var type = ParseTypeCore(ParseTypeMode.AfterRef); return _syntaxFactory.RefType(refKeyword, readonlyKeyword, type); } return ParseTypeCore(mode); } private TypeSyntax ParseTypeCore(ParseTypeMode mode) { NameOptions nameOptions; switch (mode) { case ParseTypeMode.AfterIs: nameOptions = NameOptions.InExpression | NameOptions.AfterIs | NameOptions.PossiblePattern; break; case ParseTypeMode.DefinitePattern: nameOptions = NameOptions.InExpression | NameOptions.DefinitePattern | NameOptions.PossiblePattern; break; case ParseTypeMode.AfterOut: nameOptions = NameOptions.InExpression | NameOptions.AfterOut; break; case ParseTypeMode.AfterTupleComma: nameOptions = NameOptions.InExpression | NameOptions.AfterTupleComma; break; case ParseTypeMode.FirstElementOfPossibleTupleLiteral: nameOptions = NameOptions.InExpression | NameOptions.FirstElementOfPossibleTupleLiteral; break; case ParseTypeMode.NewExpression: case ParseTypeMode.AsExpression: case ParseTypeMode.Normal: case ParseTypeMode.Parameter: case ParseTypeMode.AfterRef: nameOptions = NameOptions.None; break; default: throw ExceptionUtilities.UnexpectedValue(mode); } var type = this.ParseUnderlyingType(mode, options: nameOptions); Debug.Assert(type != null); int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { switch (this.CurrentToken.Kind) { case SyntaxKind.QuestionToken when canBeNullableType(): { var question = EatNullableQualifierIfApplicable(mode); if (question != null) { type = _syntaxFactory.NullableType(type, question); continue; } goto done; // token not consumed } bool canBeNullableType() { // These are the fast tests for (in)applicability. // More expensive tests are in `EatNullableQualifierIfApplicable` if (type.Kind == SyntaxKind.NullableType || type.Kind == SyntaxKind.PointerType || type.Kind == SyntaxKind.FunctionPointerType) return false; if (this.PeekToken(1).Kind == SyntaxKind.OpenBracketToken) return true; if (mode == ParseTypeMode.DefinitePattern) return true; // Permit nullable type parsing and report while binding for a better error message if (mode == ParseTypeMode.NewExpression && type.Kind == SyntaxKind.TupleType && this.PeekToken(1).Kind != SyntaxKind.OpenParenToken && this.PeekToken(1).Kind != SyntaxKind.OpenBraceToken) return false; // Permit `new (int, int)?(t)` (creation) and `new (int, int) ? x : y` (conditional) return true; } case SyntaxKind.AsteriskToken when type.Kind != SyntaxKind.ArrayType: switch (mode) { case ParseTypeMode.AfterIs: case ParseTypeMode.DefinitePattern: case ParseTypeMode.AfterTupleComma: case ParseTypeMode.FirstElementOfPossibleTupleLiteral: // these contexts do not permit a pointer type except as an element type of an array. if (PointerTypeModsFollowedByRankAndDimensionSpecifier()) { type = this.ParsePointerTypeMods(type); continue; } break; case ParseTypeMode.Normal: case ParseTypeMode.Parameter: case ParseTypeMode.AfterOut: case ParseTypeMode.AfterRef: case ParseTypeMode.AsExpression: case ParseTypeMode.NewExpression: type = this.ParsePointerTypeMods(type); continue; } goto done; // token not consumed case SyntaxKind.OpenBracketToken: // Now check for arrays. { var ranks = _pool.Allocate<ArrayRankSpecifierSyntax>(); try { while (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken) { var rank = this.ParseArrayRankSpecifier(out _); ranks.Add(rank); } type = _syntaxFactory.ArrayType(type, ranks); } finally { _pool.Free(ranks); } continue; } default: goto done; // token not consumed } } done:; Debug.Assert(type != null); return type; } private SyntaxToken EatNullableQualifierIfApplicable(ParseTypeMode mode) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.QuestionToken); var resetPoint = this.GetResetPoint(); try { var questionToken = this.EatToken(); if (!canFollowNullableType()) { // Restore current token index this.Reset(ref resetPoint); return null; } return CheckFeatureAvailability(questionToken, MessageID.IDS_FeatureNullable); bool canFollowNullableType() { switch (mode) { case ParseTypeMode.AfterIs: case ParseTypeMode.DefinitePattern: case ParseTypeMode.AsExpression: // These contexts might be a type that is at the end of an expression. // In these contexts we only permit the nullable qualifier if it is followed // by a token that could not start an expression, because for backward // compatibility we want to consider a `?` token as part of the `?:` // operator if possible. return !CanStartExpression(); case ParseTypeMode.NewExpression: // A nullable qualifier is permitted as part of the type in a `new` expression. // e.g. `new int?()` is allowed. It creates a null value of type `Nullable<int>`. // Similarly `new int? {}` is allowed. return this.CurrentToken.Kind == SyntaxKind.OpenParenToken || // ctor parameters this.CurrentToken.Kind == SyntaxKind.OpenBracketToken || // array type this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; // object initializer default: return true; } } } finally { this.Release(ref resetPoint); } } private bool PointerTypeModsFollowedByRankAndDimensionSpecifier() { // Are pointer specifiers (if any) followed by an array specifier? for (int i = 0; ; i++) { switch (this.PeekToken(i).Kind) { case SyntaxKind.AsteriskToken: continue; case SyntaxKind.OpenBracketToken: return true; default: return false; } } } private ArrayRankSpecifierSyntax ParseArrayRankSpecifier(out bool sawNonOmittedSize) { sawNonOmittedSize = false; bool sawOmittedSize = false; var open = this.EatToken(SyntaxKind.OpenBracketToken); var list = _pool.AllocateSeparated<ExpressionSyntax>(); try { var omittedArraySizeExpressionInstance = _syntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition) && this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { // NOTE: trivia will be attached to comma, not omitted array size sawOmittedSize = true; list.Add(omittedArraySizeExpressionInstance); list.AddSeparator(this.EatToken()); } else if (this.IsPossibleExpression()) { var size = this.ParseExpressionCore(); sawNonOmittedSize = true; list.Add(size); if (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); } } else if (this.SkipBadArrayRankSpecifierTokens(ref open, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } // Don't end on a comma. // If the omitted size would be the only element, then skip it unless sizes were expected. if (((list.Count & 1) == 0)) { sawOmittedSize = true; list.Add(omittedArraySizeExpressionInstance); } // Never mix omitted and non-omitted array sizes. If there were non-omitted array sizes, // then convert all of the omitted array sizes to missing identifiers. if (sawOmittedSize && sawNonOmittedSize) { for (int i = 0; i < list.Count; i++) { if (list[i].RawKind == (int)SyntaxKind.OmittedArraySizeExpression) { int width = list[i].Width; int offset = list[i].GetLeadingTriviaWidth(); list[i] = this.AddError(this.CreateMissingIdentifierName(), offset, width, ErrorCode.ERR_ValueExpected); } } } // Eat the close brace and we're done. var close = this.EatToken(SyntaxKind.CloseBracketToken); return _syntaxFactory.ArrayRankSpecifier(open, list, close); } finally { _pool.Free(list); } } private TupleTypeSyntax ParseTupleType() { var open = this.EatToken(SyntaxKind.OpenParenToken); var list = _pool.AllocateSeparated<TupleElementSyntax>(); try { if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { var element = ParseTupleElement(); list.Add(element); while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { var comma = this.EatToken(SyntaxKind.CommaToken); list.AddSeparator(comma); element = ParseTupleElement(); list.Add(element); } } if (list.Count < 2) { if (list.Count < 1) { list.Add(_syntaxFactory.TupleElement(this.CreateMissingIdentifierName(), identifier: null)); } list.AddSeparator(SyntaxFactory.MissingToken(SyntaxKind.CommaToken)); var missing = this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_TupleTooFewElements); list.Add(_syntaxFactory.TupleElement(missing, identifier: null)); } var close = this.EatToken(SyntaxKind.CloseParenToken); var result = _syntaxFactory.TupleType(open, list, close); result = CheckFeatureAvailability(result, MessageID.IDS_FeatureTuples); return result; } finally { _pool.Free(list); } } private TupleElementSyntax ParseTupleElement() { var type = ParseType(); SyntaxToken name = null; if (IsTrueIdentifier()) { name = this.ParseIdentifierToken(); } return _syntaxFactory.TupleElement(type, name); } private PostSkipAction SkipBadArrayRankSpecifierTokens(ref SyntaxToken openBracket, SeparatedSyntaxListBuilder<ExpressionSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openBracket, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), p => p.CurrentToken.Kind == SyntaxKind.CloseBracketToken || p.IsTerminator(), expected); } private TypeSyntax ParseUnderlyingType(ParseTypeMode mode, NameOptions options = NameOptions.None) { if (IsPredefinedType(this.CurrentToken.Kind)) { // This is a predefined type var token = this.EatToken(); if (token.Kind == SyntaxKind.VoidKeyword && this.CurrentToken.Kind != SyntaxKind.AsteriskToken) { token = this.AddError(token, mode == ParseTypeMode.Parameter ? ErrorCode.ERR_NoVoidParameter : ErrorCode.ERR_NoVoidHere); } return _syntaxFactory.PredefinedType(token); } // The :: case is for error recovery. if (IsTrueIdentifier() || this.CurrentToken.Kind == SyntaxKind.ColonColonToken) { return this.ParseQualifiedName(options); } if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { return this.ParseTupleType(); } else if (IsFunctionPointerStart()) { return ParseFunctionPointerTypeSyntax(); } return this.AddError( this.CreateMissingIdentifierName(), mode == ParseTypeMode.NewExpression ? ErrorCode.ERR_BadNewExpr : ErrorCode.ERR_TypeExpected); } #nullable enable private FunctionPointerTypeSyntax ParseFunctionPointerTypeSyntax() { Debug.Assert(IsFunctionPointerStart()); var @delegate = EatToken(SyntaxKind.DelegateKeyword); var asterisk = EatToken(SyntaxKind.AsteriskToken); FunctionPointerCallingConventionSyntax? callingConvention = parseCallingConvention(); if (!IsPossibleFunctionPointerParameterListStart(CurrentToken)) { var lessThanTokenError = WithAdditionalDiagnostics(SyntaxFactory.MissingToken(SyntaxKind.LessThanToken), GetExpectedTokenError(SyntaxKind.LessThanToken, SyntaxKind.None)); var missingTypes = _pool.AllocateSeparated<FunctionPointerParameterSyntax>(); var missingTypeName = CreateMissingIdentifierName(); var missingType = SyntaxFactory.FunctionPointerParameter(attributeLists: default, modifiers: default, missingTypeName); missingTypes.Add(missingType); // Handle the simple case of delegate*>. We don't try to deal with any variation of delegate*invalid>, as // we don't know for sure that the expression isn't a relational with something else. var greaterThanTokenError = TryEatToken(SyntaxKind.GreaterThanToken) ?? SyntaxFactory.MissingToken(SyntaxKind.GreaterThanToken); var paramList = SyntaxFactory.FunctionPointerParameterList(lessThanTokenError, missingTypes, greaterThanTokenError); var funcPtr = SyntaxFactory.FunctionPointerType(@delegate, asterisk, callingConvention, paramList); _pool.Free(missingTypes); return funcPtr; } var lessThanToken = EatTokenAsKind(SyntaxKind.LessThanToken); var saveTerm = _termState; _termState |= (lessThanToken.IsMissing ? TerminatorState.IsEndOfFunctionPointerParameterListErrored : TerminatorState.IsEndOfFunctionPointerParameterList); var types = _pool.AllocateSeparated<FunctionPointerParameterSyntax>(); try { while (true) { var modifiers = _pool.Allocate<SyntaxToken>(); try { ParseParameterModifiers(modifiers, isFunctionPointerParameter: true); var parameterType = ParseTypeOrVoid(); types.Add(SyntaxFactory.FunctionPointerParameter(attributeLists: default, modifiers, parameterType)); if (skipBadFunctionPointerTokens(types) == PostSkipAction.Abort) { break; } Debug.Assert(CurrentToken.Kind == SyntaxKind.CommaToken); types.AddSeparator(EatToken(SyntaxKind.CommaToken)); } finally { _pool.Free(modifiers); } } SyntaxToken greaterThanToken; if (lessThanToken.IsMissing && CurrentToken.Kind == SyntaxKind.CloseParenToken) { greaterThanToken = EatTokenAsKind(SyntaxKind.GreaterThanToken); } else { greaterThanToken = EatToken(SyntaxKind.GreaterThanToken); } var funcPointer = SyntaxFactory.FunctionPointerType(@delegate, asterisk, callingConvention, SyntaxFactory.FunctionPointerParameterList(lessThanToken, types, greaterThanToken)); funcPointer = CheckFeatureAvailability(funcPointer, MessageID.IDS_FeatureFunctionPointers); return funcPointer; } finally { _termState = saveTerm; _pool.Free(types); } PostSkipAction skipBadFunctionPointerTokens<T>(SeparatedSyntaxListBuilder<T> list) where T : CSharpSyntaxNode { CSharpSyntaxNode? tmp = null; Debug.Assert(list.Count > 0); return SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, isNotExpectedFunction: p => p.CurrentToken.Kind != SyntaxKind.CommaToken, abortFunction: p => p.IsTerminator(), expected: SyntaxKind.CommaToken); } FunctionPointerCallingConventionSyntax? parseCallingConvention() { if (CurrentToken.Kind == SyntaxKind.IdentifierToken) { SyntaxToken managedSpecifier; SyntaxToken peek1 = PeekToken(1); switch (CurrentToken) { case { ContextualKind: SyntaxKind.ManagedKeyword }: case { ContextualKind: SyntaxKind.UnmanagedKeyword }: managedSpecifier = EatContextualToken(CurrentToken.ContextualKind); break; case var _ when IsPossibleFunctionPointerParameterListStart(peek1): // If there's a possible parameter list next, treat this as a bad identifier that should have been managed or unmanaged managedSpecifier = EatTokenAsKind(SyntaxKind.ManagedKeyword); break; case var _ when peek1.Kind == SyntaxKind.OpenBracketToken: // If there's an open brace next, treat this as a bad identifier that should have been unmanaged managedSpecifier = EatTokenAsKind(SyntaxKind.UnmanagedKeyword); break; default: // Whatever is next, it's probably not a calling convention or a function pointer type. // Bail out return null; } FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventions = null; if (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { var openBracket = EatToken(SyntaxKind.OpenBracketToken); var callingConventionModifiers = _pool.AllocateSeparated<FunctionPointerUnmanagedCallingConventionSyntax>(); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFunctionPointerCallingConvention; try { while (true) { callingConventionModifiers.Add(SyntaxFactory.FunctionPointerUnmanagedCallingConvention(EatToken(SyntaxKind.IdentifierToken))); if (skipBadFunctionPointerTokens(callingConventionModifiers) == PostSkipAction.Abort) { break; } Debug.Assert(CurrentToken.Kind == SyntaxKind.CommaToken); callingConventionModifiers.AddSeparator(EatToken(SyntaxKind.CommaToken)); } var closeBracket = EatToken(SyntaxKind.CloseBracketToken); unmanagedCallingConventions = SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(openBracket, callingConventionModifiers, closeBracket); } finally { _termState = saveTerm; _pool.Free(callingConventionModifiers); } } if (managedSpecifier.Kind == SyntaxKind.ManagedKeyword && unmanagedCallingConventions != null) { // 'managed' calling convention cannot be combined with unmanaged calling convention specifiers. unmanagedCallingConventions = AddError(unmanagedCallingConventions, ErrorCode.ERR_CannotSpecifyManagedWithUnmanagedSpecifiers); } return SyntaxFactory.FunctionPointerCallingConvention(managedSpecifier, unmanagedCallingConventions); } return null; } } private bool IsFunctionPointerStart() => CurrentToken.Kind == SyntaxKind.DelegateKeyword && PeekToken(1).Kind == SyntaxKind.AsteriskToken; private static bool IsPossibleFunctionPointerParameterListStart(SyntaxToken token) // We consider both ( and < to be possible starts, in order to make error recovery more graceful // in the scenario where a user accidentally surrounds their function pointer type list with parens. => token.Kind == SyntaxKind.LessThanToken || token.Kind == SyntaxKind.OpenParenToken; #nullable disable private TypeSyntax ParsePointerTypeMods(TypeSyntax type) { // Check for pointer types while (this.CurrentToken.Kind == SyntaxKind.AsteriskToken) { type = _syntaxFactory.PointerType(type, this.EatToken()); } return type; } public StatementSyntax ParseStatement() { return ParseWithStackGuard( () => ParsePossiblyAttributedStatement() ?? ParseExpressionStatement(attributes: default), () => SyntaxFactory.EmptyStatement(attributeLists: default, SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken))); } private StatementSyntax ParsePossiblyAttributedStatement() => ParseStatementCore(ParseAttributeDeclarations(), isGlobal: false); /// <param name="isGlobal">If we're being called while parsing a C# top-level statements (Script or Simple Program). /// At the top level in Script, we allow most statements *except* for local-decls/local-funcs. /// Those will instead be parsed out as script-fields/methods.</param> private StatementSyntax ParseStatementCore(SyntaxList<AttributeListSyntax> attributes, bool isGlobal) { if (canReuseStatement(attributes, isGlobal)) { return (StatementSyntax)this.EatNode(); } ResetPoint resetPointBeforeStatement = this.GetResetPoint(); try { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); StatementSyntax result; // Main switch to handle processing almost any statement. switch (this.CurrentToken.Kind) { case SyntaxKind.FixedKeyword: return this.ParseFixedStatement(attributes); case SyntaxKind.BreakKeyword: return this.ParseBreakStatement(attributes); case SyntaxKind.ContinueKeyword: return this.ParseContinueStatement(attributes); case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: return this.ParseTryStatement(attributes); case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: return this.ParseCheckedStatement(attributes); case SyntaxKind.DoKeyword: return this.ParseDoStatement(attributes); case SyntaxKind.ForKeyword: return this.ParseForOrForEachStatement(attributes); case SyntaxKind.ForEachKeyword: return this.ParseForEachStatement(attributes, awaitTokenOpt: null); case SyntaxKind.GotoKeyword: return this.ParseGotoStatement(attributes); case SyntaxKind.IfKeyword: return this.ParseIfStatement(attributes); case SyntaxKind.ElseKeyword: // Including 'else' keyword to handle 'else without if' error cases return this.ParseMisplacedElse(attributes); case SyntaxKind.LockKeyword: return this.ParseLockStatement(attributes); case SyntaxKind.ReturnKeyword: return this.ParseReturnStatement(attributes); case SyntaxKind.SwitchKeyword: return this.ParseSwitchStatement(attributes); case SyntaxKind.ThrowKeyword: return this.ParseThrowStatement(attributes); case SyntaxKind.UnsafeKeyword: result = TryParseStatementStartingWithUnsafe(attributes); if (result != null) return result; break; case SyntaxKind.UsingKeyword: return ParseStatementStartingWithUsing(attributes); case SyntaxKind.WhileKeyword: return this.ParseWhileStatement(attributes); case SyntaxKind.OpenBraceToken: return this.ParseBlock(attributes); case SyntaxKind.SemicolonToken: return _syntaxFactory.EmptyStatement(attributes, this.EatToken()); case SyntaxKind.IdentifierToken: result = TryParseStatementStartingWithIdentifier(attributes, isGlobal); if (result != null) return result; break; } return ParseStatementCoreRest(attributes, isGlobal, ref resetPointBeforeStatement); } finally { _recursionDepth--; this.Release(ref resetPointBeforeStatement); } bool canReuseStatement(SyntaxList<AttributeListSyntax> attributes, bool isGlobal) { return this.IsIncrementalAndFactoryContextMatches && this.CurrentNode is Syntax.StatementSyntax && !isGlobal && // Top-level statements are reused by ParseMemberDeclarationOrStatementCore when possible. attributes.Count == 0; } } private StatementSyntax ParseStatementCoreRest(SyntaxList<AttributeListSyntax> attributes, bool isGlobal, ref ResetPoint resetPointBeforeStatement) { isGlobal = isGlobal && IsScript; if (!this.IsPossibleLocalDeclarationStatement(isGlobal)) { return this.ParseExpressionStatement(attributes); } if (isGlobal) { // if we're at the global script level, then we don't support local-decls or // local-funcs. The caller instead will look for those and parse them as // fields/methods in the global script scope. return null; } bool beginsWithAwait = this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword; var result = ParseLocalDeclarationStatement(attributes); // didn't get any sort of statement. This was something else entirely // (like just a `}`). No need to retry anything here. Just reset back // to where we started from and bail entirely from parsing a statement. if (result == null) { this.Reset(ref resetPointBeforeStatement); return null; } if (result.ContainsDiagnostics && beginsWithAwait && !IsInAsync) { // Local decl had issues. We were also starting with 'await' in a non-async // context. Retry parsing this as if we were in an 'async' context as it's much // more likely that this was a misplace await-expr' than a local decl. // // The user will still get a later binding error about an await-expr in a non-async // context. this.Reset(ref resetPointBeforeStatement); IsInAsync = true; result = ParseExpressionStatement(attributes); IsInAsync = false; } // Didn't want to retry as an `await expr`. Just return what we actually // produced. return result; } private StatementSyntax TryParseStatementStartingWithIdentifier(SyntaxList<AttributeListSyntax> attributes, bool isGlobal) { if (this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword && this.PeekToken(1).Kind == SyntaxKind.ForEachKeyword) { return this.ParseForEachStatement(attributes, ParseAwaitKeyword(MessageID.IDS_FeatureAsyncStreams)); } else if (IsPossibleAwaitUsing()) { if (PeekToken(2).Kind == SyntaxKind.OpenParenToken) { // `await using Type ...` is handled below in ParseLocalDeclarationStatement return this.ParseUsingStatement(attributes, ParseAwaitKeyword(MessageID.IDS_FeatureAsyncUsing)); } } else if (this.IsPossibleLabeledStatement()) { return this.ParseLabeledStatement(attributes); } else if (this.IsPossibleYieldStatement()) { return this.ParseYieldStatement(attributes); } else if (this.IsPossibleAwaitExpressionStatement()) { return this.ParseExpressionStatement(attributes); } else if (this.IsQueryExpression(mayBeVariableDeclaration: true, mayBeMemberDeclaration: isGlobal && IsScript)) { return this.ParseExpressionStatement(attributes, this.ParseQueryExpression(0)); } return null; } private StatementSyntax ParseStatementStartingWithUsing(SyntaxList<AttributeListSyntax> attributes) => PeekToken(1).Kind == SyntaxKind.OpenParenToken ? ParseUsingStatement(attributes) : ParseLocalDeclarationStatement(attributes); // Checking for brace to disambiguate between unsafe statement and unsafe local function private StatementSyntax TryParseStatementStartingWithUnsafe(SyntaxList<AttributeListSyntax> attributes) => IsPossibleUnsafeStatement() ? ParseUnsafeStatement(attributes) : null; private SyntaxToken ParseAwaitKeyword(MessageID feature) { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword); SyntaxToken awaitToken = this.EatContextualToken(SyntaxKind.AwaitKeyword); return feature != MessageID.None ? CheckFeatureAvailability(awaitToken, feature) : awaitToken; } private bool IsPossibleAwaitUsing() => CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword && PeekToken(1).Kind == SyntaxKind.UsingKeyword; private bool IsPossibleLabeledStatement() { return this.PeekToken(1).Kind == SyntaxKind.ColonToken && this.IsTrueIdentifier(); } private bool IsPossibleUnsafeStatement() { return this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken; } private bool IsPossibleYieldStatement() { return this.CurrentToken.ContextualKind == SyntaxKind.YieldKeyword && (this.PeekToken(1).Kind == SyntaxKind.ReturnKeyword || this.PeekToken(1).Kind == SyntaxKind.BreakKeyword); } private bool IsPossibleLocalDeclarationStatement(bool isGlobalScriptLevel) { // This method decides whether to parse a statement as a // declaration or as an expression statement. In the old // compiler it would simply call IsLocalDeclaration. var tk = this.CurrentToken.Kind; if (tk == SyntaxKind.RefKeyword || IsDeclarationModifier(tk) || // treat `static int x = 2;` as a local variable declaration (SyntaxFacts.IsPredefinedType(tk) && this.PeekToken(1).Kind != SyntaxKind.DotToken && // e.g. `int.Parse()` is an expression this.PeekToken(1).Kind != SyntaxKind.OpenParenToken)) // e.g. `int (x, y)` is an error decl expression { return true; } // note: `using (` and `await using (` are already handled in ParseStatementCore. if (tk == SyntaxKind.UsingKeyword) { Debug.Assert(PeekToken(1).Kind != SyntaxKind.OpenParenToken); return true; } if (IsPossibleAwaitUsing()) { Debug.Assert(PeekToken(2).Kind != SyntaxKind.OpenParenToken); return true; } tk = this.CurrentToken.ContextualKind; var isPossibleAttributeOrModifier = (IsAdditionalLocalFunctionModifier(tk) || tk == SyntaxKind.OpenBracketToken) && (tk != SyntaxKind.AsyncKeyword || ShouldAsyncBeTreatedAsModifier(parsingStatementNotDeclaration: true)); if (isPossibleAttributeOrModifier) { return true; } return IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(isGlobalScriptLevel); } private bool IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(bool isGlobalScriptLevel) { bool? typedIdentifier = IsPossibleTypedIdentifierStart(this.CurrentToken, this.PeekToken(1), allowThisKeyword: false); if (typedIdentifier != null) { return typedIdentifier.Value; } // It's common to have code like the following: // // Task. // await Task.Delay() // // In this case we don't want to parse this as a local declaration like: // // Task.await Task // // This does not represent user intent, and it causes all sorts of problems to higher // layers. This is because both the parse tree is strange, and the symbol tables have // entries that throw things off (like a bogus 'Task' local). // // Note that we explicitly do this check when we see that the code spreads over multiple // lines. We don't want this if the user has actually written "X.Y z" var tk = this.CurrentToken.ContextualKind; if (tk == SyntaxKind.IdentifierToken) { var token1 = PeekToken(1); if (token1.Kind == SyntaxKind.DotToken && token1.TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia)) { if (PeekToken(2).Kind == SyntaxKind.IdentifierToken && PeekToken(3).Kind == SyntaxKind.IdentifierToken) { // We have something like: // // X. // Y z // // This is only a local declaration if we have: // // X.Y z; // X.Y z = ... // X.Y z, ... // X.Y z( ... (local function) // X.Y z<W... (local function) // var token4Kind = PeekToken(4).Kind; if (token4Kind != SyntaxKind.SemicolonToken && token4Kind != SyntaxKind.EqualsToken && token4Kind != SyntaxKind.CommaToken && token4Kind != SyntaxKind.OpenParenToken && token4Kind != SyntaxKind.LessThanToken) { return false; } } } } var resetPoint = this.GetResetPoint(); try { ScanTypeFlags st = this.ScanType(); // We could always return true for st == AliasQualName in addition to MustBeType on the first line, however, we want it to return false in the case where // CurrentToken.Kind != SyntaxKind.Identifier so that error cases, like: A::N(), are not parsed as variable declarations and instead are parsed as A.N() where we can give // a better error message saying "did you meant to use a '.'?" if (st == ScanTypeFlags.MustBeType && this.CurrentToken.Kind != SyntaxKind.DotToken && this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { return true; } if (st == ScanTypeFlags.NotType || this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return false; } // T? and T* might start an expression, we need to parse further to disambiguate: if (isGlobalScriptLevel) { if (st == ScanTypeFlags.PointerOrMultiplication) { return false; } else if (st == ScanTypeFlags.NullableType) { return IsPossibleDeclarationStatementFollowingNullableType(); } } return true; } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } private bool IsPossibleTopLevelUsingLocalDeclarationStatement() { if (this.CurrentToken.Kind != SyntaxKind.UsingKeyword) { return false; } var tk = PeekToken(1).Kind; if (tk == SyntaxKind.RefKeyword) { return true; } if (IsDeclarationModifier(tk)) // treat `const int x = 2;` as a local variable declaration { if (tk != SyntaxKind.StaticKeyword) // For `static` we still need to make sure we have a typed identifier after it, because `using static type;` is a valid using directive. { return true; } } else if (SyntaxFacts.IsPredefinedType(tk)) { return true; } var resetPoint = this.GetResetPoint(); try { // Skip 'using' keyword EatToken(); if (tk == SyntaxKind.StaticKeyword) { // Skip 'static' keyword EatToken(); } return IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(isGlobalScriptLevel: false); } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } // Looks ahead for a declaration of a field, property or method declaration following a nullable type T?. private bool IsPossibleDeclarationStatementFollowingNullableType() { if (IsFieldDeclaration(isEvent: false)) { return IsPossibleFieldDeclarationFollowingNullableType(); } ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; SyntaxToken identifierOrThisOpt; TypeParameterListSyntax typeParameterListOpt; this.ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterListOpt, isEvent: false); if (explicitInterfaceOpt == null && identifierOrThisOpt == null && typeParameterListOpt == null) { return false; } // looks like a property: if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { return true; } // don't accept indexers: if (identifierOrThisOpt.Kind == SyntaxKind.ThisKeyword) { return false; } return IsPossibleMethodDeclarationFollowingNullableType(); } // At least one variable declaration terminated by a semicolon or a comma. // idf; // idf, // idf = <expr>; // idf = <expr>, private bool IsPossibleFieldDeclarationFollowingNullableType() { if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return false; } this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFieldDeclaration; this.EatToken(); this.ParseVariableInitializer(); _termState = saveTerm; } return this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken; } private bool IsPossibleMethodDeclarationFollowingNullableType() { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfMethodSignature; var paramList = this.ParseParenthesizedParameterList(); _termState = saveTerm; var separatedParameters = paramList.Parameters.GetWithSeparators(); // parsed full signature: if (!paramList.CloseParenToken.IsMissing) { // (...) { // (...) where if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { return true; } // disambiguates conditional expressions // (...) : if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { return false; } } // no parameters, just an open paren followed by a token that doesn't belong to a parameter definition: if (separatedParameters.Count == 0) { return false; } var parameter = (ParameterSyntax)separatedParameters[0]; // has an attribute: // ([Attr] if (parameter.AttributeLists.Count > 0) { return true; } // has params modifier: // (params for (int i = 0; i < parameter.Modifiers.Count; i++) { if (parameter.Modifiers[i].Kind == SyntaxKind.ParamsKeyword) { return true; } } if (parameter.Type == null) { // has arglist: // (__arglist if (parameter.Identifier.Kind == SyntaxKind.ArgListKeyword) { return true; } } else if (parameter.Type.Kind == SyntaxKind.NullableType) { // nullable type with modifiers // (ref T? // (out T? if (parameter.Modifiers.Count > 0) { return true; } // nullable type, identifier, and separator or closing parent // (T ? idf, // (T ? idf) if (!parameter.Identifier.IsMissing && (separatedParameters.Count >= 2 && !separatedParameters[1].IsMissing || separatedParameters.Count == 1 && !paramList.CloseParenToken.IsMissing)) { return true; } } else if (parameter.Type.Kind == SyntaxKind.IdentifierName && ((IdentifierNameSyntax)parameter.Type).Identifier.ContextualKind == SyntaxKind.FromKeyword) { // assume that "from" is meant to be a query start ("from" bound to a type is rare): // (from return false; } else { // has a name and a non-nullable type: // (T idf // (ref T idf // (out T idf if (!parameter.Identifier.IsMissing) { return true; } } return false; } private bool IsPossibleNewExpression() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NewKeyword); // skip new SyntaxToken nextToken = PeekToken(1); // new { } // new [ ] switch (nextToken.Kind) { case SyntaxKind.OpenBraceToken: case SyntaxKind.OpenBracketToken: return true; } // // Declaration with new modifier vs. new expression // Parse it as an expression if the type is not followed by an identifier or this keyword. // // Member declarations: // new T Idf ... // new T this ... // new partial Idf ("partial" as a type name) // new partial this ("partial" as a type name) // new partial T Idf // new partial T this // new <modifier> // new <class|interface|struct|enum> // new partial <class|interface|struct|enum> // // New expressions: // new T [] // new T { } // new <non-type> // if (SyntaxFacts.GetBaseTypeDeclarationKind(nextToken.Kind) != SyntaxKind.None) { return false; } DeclarationModifiers modifier = GetModifier(nextToken); if (modifier == DeclarationModifiers.Partial) { if (SyntaxFacts.IsPredefinedType(PeekToken(2).Kind)) { return false; } // class, struct, enum, interface keywords, but also other modifiers that are not allowed after // partial keyword but start class declaration, so we can assume the user just swapped them. if (IsPossibleStartOfTypeDeclaration(PeekToken(2).Kind)) { return false; } } else if (modifier != DeclarationModifiers.None) { return false; } bool? typedIdentifier = IsPossibleTypedIdentifierStart(nextToken, PeekToken(2), allowThisKeyword: true); if (typedIdentifier != null) { // new Idf Idf // new Idf . // new partial T // new partial . return !typedIdentifier.Value; } var resetPoint = this.GetResetPoint(); try { // skips new keyword EatToken(); ScanTypeFlags st = this.ScanType(); return !IsPossibleMemberName() || st == ScanTypeFlags.NotType; } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } /// <returns> /// true if the current token can be the first token of a typed identifier (a type name followed by an identifier), /// false if it definitely can't be, /// null if we need to scan further to find out. /// </returns> private bool? IsPossibleTypedIdentifierStart(SyntaxToken current, SyntaxToken next, bool allowThisKeyword) { if (IsTrueIdentifier(current)) { switch (next.Kind) { // tokens that can be in type names... case SyntaxKind.DotToken: case SyntaxKind.AsteriskToken: case SyntaxKind.QuestionToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.LessThanToken: case SyntaxKind.ColonColonToken: return null; case SyntaxKind.OpenParenToken: if (current.IsIdentifierVar()) { // potentially either a tuple type in a local declaration (true), or // a tuple lvalue in a deconstruction assignment (false). return null; } else { return false; } case SyntaxKind.IdentifierToken: return IsTrueIdentifier(next); case SyntaxKind.ThisKeyword: return allowThisKeyword; default: return false; } } return null; } private BlockSyntax ParsePossiblyAttributedBlock() => ParseBlock(this.ParseAttributeDeclarations()); /// <summary> /// Used to parse the block-body for a method or accessor. For blocks that appear *inside* /// method bodies, call <see cref="ParseBlock"/>. /// </summary> /// <param name="isAccessorBody">If is true, then we produce a special diagnostic if the /// open brace is missing.</param> private BlockSyntax ParseMethodOrAccessorBodyBlock(SyntaxList<AttributeListSyntax> attributes, bool isAccessorBody) { // Check again for incremental re-use. This way if a method signature is edited we can // still quickly re-sync on the body. if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.Block && attributes.Count == 0) return (BlockSyntax)this.EatNode(); // There's a special error code for a missing token after an accessor keyword CSharpSyntaxNode openBrace = isAccessorBody && this.CurrentToken.Kind != SyntaxKind.OpenBraceToken ? this.AddError( SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken), IsFeatureEnabled(MessageID.IDS_FeatureExpressionBodiedAccessor) ? ErrorCode.ERR_SemiOrLBraceOrArrowExpected : ErrorCode.ERR_SemiOrLBraceExpected) : this.EatToken(SyntaxKind.OpenBraceToken); var statements = _pool.Allocate<StatementSyntax>(); this.ParseStatements(ref openBrace, statements, stopOnSwitchSections: false); var block = _syntaxFactory.Block( attributes, (SyntaxToken)openBrace, // Force creation a many-children list, even if only 1, 2, or 3 elements in the statement list. IsLargeEnoughNonEmptyStatementList(statements) ? new SyntaxList<StatementSyntax>(SyntaxList.List(((SyntaxListBuilder)statements).ToArray())) : statements, this.EatToken(SyntaxKind.CloseBraceToken)); _pool.Free(statements); return block; } /// <summary> /// Used to parse normal blocks that appear inside method bodies. For the top level block /// of a method/accessor use <see cref="ParseMethodOrAccessorBodyBlock"/>. /// </summary> private BlockSyntax ParseBlock(SyntaxList<AttributeListSyntax> attributes) { // Check again for incremental re-use, since ParseBlock is called from a bunch of places // other than ParseStatementCore() if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.Block) return (BlockSyntax)this.EatNode(); CSharpSyntaxNode openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var statements = _pool.Allocate<StatementSyntax>(); this.ParseStatements(ref openBrace, statements, stopOnSwitchSections: false); var block = _syntaxFactory.Block( attributes, (SyntaxToken)openBrace, statements, this.EatToken(SyntaxKind.CloseBraceToken)); _pool.Free(statements); return block; } // Is this statement list non-empty, and large enough to make using weak children beneficial? private static bool IsLargeEnoughNonEmptyStatementList(SyntaxListBuilder<StatementSyntax> statements) { if (statements.Count == 0) { return false; } else if (statements.Count == 1) { // If we have a single statement, it might be small, like "return null", or large, // like a loop or if or switch with many statements inside. Use the width as a proxy for // how big it is. If it's small, its better to forgo a many children list anyway, since the // weak reference would consume as much memory as is saved. return statements[0].Width > 60; } else { // For 2 or more statements, go ahead and create a many-children lists. return true; } } private void ParseStatements(ref CSharpSyntaxNode previousNode, SyntaxListBuilder<StatementSyntax> statements, bool stopOnSwitchSections) { var saveTerm = _termState; _termState |= TerminatorState.IsPossibleStatementStartOrStop; // partial statements can abort if a new statement starts if (stopOnSwitchSections) { _termState |= TerminatorState.IsSwitchSectionStart; } int lastTokenPosition = -1; while (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken && this.CurrentToken.Kind != SyntaxKind.EndOfFileToken && !(stopOnSwitchSections && this.IsPossibleSwitchSection()) && IsMakingProgress(ref lastTokenPosition)) { if (this.IsPossibleStatement(acceptAccessibilityMods: true)) { var statement = this.ParsePossiblyAttributedStatement(); if (statement != null) { statements.Add(statement); continue; } } GreenNode trailingTrivia; var action = this.SkipBadStatementListTokens(statements, SyntaxKind.CloseBraceToken, out trailingTrivia); if (trailingTrivia != null) { previousNode = AddTrailingSkippedSyntax(previousNode, trailingTrivia); } if (action == PostSkipAction.Abort) { break; } } _termState = saveTerm; } private bool IsPossibleStatementStartOrStop() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.IsPossibleStatement(acceptAccessibilityMods: true); } private PostSkipAction SkipBadStatementListTokens(SyntaxListBuilder<StatementSyntax> statements, SyntaxKind expected, out GreenNode trailingTrivia) { return this.SkipBadListTokensWithExpectedKindHelper( statements, // We know we have a bad statement, so it can't be a local // function, meaning we shouldn't consider accessibility // modifiers to be the start of a statement p => !p.IsPossibleStatement(acceptAccessibilityMods: false), p => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken || p.IsTerminator(), expected, out trailingTrivia ); } private bool IsPossibleStatement(bool acceptAccessibilityMods) { var tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.FixedKeyword: case SyntaxKind.BreakKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.LockKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.ThrowKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.UsingKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.OpenBraceToken: case SyntaxKind.SemicolonToken: case SyntaxKind.StaticKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: case SyntaxKind.RefKeyword: case SyntaxKind.ExternKeyword: case SyntaxKind.OpenBracketToken: return true; case SyntaxKind.IdentifierToken: return IsTrueIdentifier(); case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: return !_isInTry; // Accessibility modifiers are not legal in a statement, // but a common mistake for local functions. Parse to give a // better error message. case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: return acceptAccessibilityMods; default: return IsPredefinedType(tk) || IsPossibleExpression(); } } private FixedStatementSyntax ParseFixedStatement(SyntaxList<AttributeListSyntax> attributes) { var @fixed = this.EatToken(SyntaxKind.FixedKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFixedStatement; var decl = ParseVariableDeclaration(); _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); StatementSyntax statement = this.ParseEmbeddedStatement(); return _syntaxFactory.FixedStatement(attributes, @fixed, openParen, decl, closeParen, statement); } private bool IsEndOfFixedStatement() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken; } private StatementSyntax ParseEmbeddedStatement() { // ParseEmbeddedStatement is called through many recursive statement parsing cases. We // keep the body exceptionally simple, and we optimize for the common case, to ensure it // is inlined into the callers. Otherwise the overhead of this single method can have a // deep impact on the number of recursive calls we can make (more than a hundred during // empirical testing). return parseEmbeddedStatementRest(this.ParsePossiblyAttributedStatement()); StatementSyntax parseEmbeddedStatementRest(StatementSyntax statement) { if (statement == null) { // The consumers of embedded statements are expecting to receive a non-null statement // yet there are several error conditions that can lead ParseStatementCore to return // null. When that occurs create an error empty Statement and return it to the caller. return SyntaxFactory.EmptyStatement(attributeLists: default, EatToken(SyntaxKind.SemicolonToken)); } // In scripts, stand-alone expression statements may not be followed by semicolons. // ParseExpressionStatement hides the error. // However, embedded expression statements are required to be followed by semicolon. if (statement.Kind == SyntaxKind.ExpressionStatement && IsScript) { var expressionStatementSyntax = (ExpressionStatementSyntax)statement; var semicolonToken = expressionStatementSyntax.SemicolonToken; // Do not add a new error if the same error was already added. if (semicolonToken.IsMissing && !semicolonToken.GetDiagnostics().Contains(diagnosticInfo => (ErrorCode)diagnosticInfo.Code == ErrorCode.ERR_SemicolonExpected)) { semicolonToken = this.AddError(semicolonToken, ErrorCode.ERR_SemicolonExpected); return expressionStatementSyntax.Update(expressionStatementSyntax.AttributeLists, expressionStatementSyntax.Expression, semicolonToken); } } return statement; } } private BreakStatementSyntax ParseBreakStatement(SyntaxList<AttributeListSyntax> attributes) { var breakKeyword = this.EatToken(SyntaxKind.BreakKeyword); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.BreakStatement(attributes, breakKeyword, semicolon); } private ContinueStatementSyntax ParseContinueStatement(SyntaxList<AttributeListSyntax> attributes) { var continueKeyword = this.EatToken(SyntaxKind.ContinueKeyword); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.ContinueStatement(attributes, continueKeyword, semicolon); } private TryStatementSyntax ParseTryStatement(SyntaxList<AttributeListSyntax> attributes) { var isInTry = _isInTry; _isInTry = true; var @try = this.EatToken(SyntaxKind.TryKeyword); BlockSyntax block; if (@try.IsMissing) { block = _syntaxFactory.Block( attributeLists: default, this.EatToken(SyntaxKind.OpenBraceToken), default(SyntaxList<StatementSyntax>), this.EatToken(SyntaxKind.CloseBraceToken)); } else { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfTryBlock; block = this.ParsePossiblyAttributedBlock(); _termState = saveTerm; } var catches = default(SyntaxListBuilder<CatchClauseSyntax>); FinallyClauseSyntax @finally = null; try { bool hasEnd = false; if (this.CurrentToken.Kind == SyntaxKind.CatchKeyword) { hasEnd = true; catches = _pool.Allocate<CatchClauseSyntax>(); while (this.CurrentToken.Kind == SyntaxKind.CatchKeyword) { catches.Add(this.ParseCatchClause()); } } if (this.CurrentToken.Kind == SyntaxKind.FinallyKeyword) { hasEnd = true; var fin = this.EatToken(); var finBlock = this.ParsePossiblyAttributedBlock(); @finally = _syntaxFactory.FinallyClause(fin, finBlock); } if (!hasEnd) { block = this.AddErrorToLastToken(block, ErrorCode.ERR_ExpectedEndTry); // synthesize missing tokens for "finally { }": @finally = _syntaxFactory.FinallyClause( SyntaxToken.CreateMissing(SyntaxKind.FinallyKeyword, null, null), _syntaxFactory.Block( attributeLists: default, SyntaxToken.CreateMissing(SyntaxKind.OpenBraceToken, null, null), default(SyntaxList<StatementSyntax>), SyntaxToken.CreateMissing(SyntaxKind.CloseBraceToken, null, null))); } _isInTry = isInTry; return _syntaxFactory.TryStatement(attributes, @try, block, catches, @finally); } finally { if (!catches.IsNull) { _pool.Free(catches); } } } private bool IsEndOfTryBlock() { return this.CurrentToken.Kind == SyntaxKind.CloseBraceToken || this.CurrentToken.Kind == SyntaxKind.CatchKeyword || this.CurrentToken.Kind == SyntaxKind.FinallyKeyword; } private CatchClauseSyntax ParseCatchClause() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.CatchKeyword); var @catch = this.EatToken(); CatchDeclarationSyntax decl = null; var saveTerm = _termState; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var openParen = this.EatToken(); _termState |= TerminatorState.IsEndOfCatchClause; var type = this.ParseType(); SyntaxToken name = null; if (this.IsTrueIdentifier()) { name = this.ParseIdentifierToken(); } _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); decl = _syntaxFactory.CatchDeclaration(openParen, type, name, closeParen); } CatchFilterClauseSyntax filter = null; var keywordKind = this.CurrentToken.ContextualKind; if (keywordKind == SyntaxKind.WhenKeyword || keywordKind == SyntaxKind.IfKeyword) { var whenKeyword = this.EatContextualToken(SyntaxKind.WhenKeyword); if (keywordKind == SyntaxKind.IfKeyword) { // The initial design of C# exception filters called for the use of the // "if" keyword in this position. We've since changed to "when", but // the error recovery experience for early adopters (and for old source // stored in the symbol server) will be better if we consume "if" as // though it were "when". whenKeyword = AddTrailingSkippedSyntax(whenKeyword, EatToken()); } whenKeyword = CheckFeatureAvailability(whenKeyword, MessageID.IDS_FeatureExceptionFilter); _termState |= TerminatorState.IsEndOfFilterClause; var openParen = this.EatToken(SyntaxKind.OpenParenToken); var filterExpression = this.ParseExpressionCore(); _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); filter = _syntaxFactory.CatchFilterClause(whenKeyword, openParen, filterExpression, closeParen); } _termState |= TerminatorState.IsEndOfCatchBlock; var block = this.ParsePossiblyAttributedBlock(); _termState = saveTerm; return _syntaxFactory.CatchClause(@catch, decl, filter, block); } private bool IsEndOfCatchClause() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.Kind == SyntaxKind.CloseBraceToken || this.CurrentToken.Kind == SyntaxKind.CatchKeyword || this.CurrentToken.Kind == SyntaxKind.FinallyKeyword; } private bool IsEndOfFilterClause() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.Kind == SyntaxKind.CloseBraceToken || this.CurrentToken.Kind == SyntaxKind.CatchKeyword || this.CurrentToken.Kind == SyntaxKind.FinallyKeyword; } private bool IsEndOfCatchBlock() { return this.CurrentToken.Kind == SyntaxKind.CloseBraceToken || this.CurrentToken.Kind == SyntaxKind.CatchKeyword || this.CurrentToken.Kind == SyntaxKind.FinallyKeyword; } private StatementSyntax ParseCheckedStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.CheckedKeyword || this.CurrentToken.Kind == SyntaxKind.UncheckedKeyword); if (this.PeekToken(1).Kind == SyntaxKind.OpenParenToken) { return this.ParseExpressionStatement(attributes); } var spec = this.EatToken(); var block = this.ParsePossiblyAttributedBlock(); return _syntaxFactory.CheckedStatement(SyntaxFacts.GetCheckStatement(spec.Kind), attributes, spec, block); } private DoStatementSyntax ParseDoStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.DoKeyword); var @do = this.EatToken(SyntaxKind.DoKeyword); var statement = this.ParseEmbeddedStatement(); var @while = this.EatToken(SyntaxKind.WhileKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfDoWhileExpression; var expression = this.ParseExpressionCore(); _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.DoStatement(attributes, @do, statement, @while, openParen, expression, closeParen, semicolon); } private bool IsEndOfDoWhileExpression() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken; } private StatementSyntax ParseForOrForEachStatement(SyntaxList<AttributeListSyntax> attributes) { // Check if the user wrote the following accidentally: // // for (SomeType t in // // instead of // // foreach (SomeType t in // // In that case, parse it as a foreach, but given the appropriate message that a // 'foreach' keyword was expected. var resetPoint = this.GetResetPoint(); try { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ForKeyword); this.EatToken(); if (this.EatToken().Kind == SyntaxKind.OpenParenToken && this.ScanType() != ScanTypeFlags.NotType && this.EatToken().Kind == SyntaxKind.IdentifierToken && this.EatToken().Kind == SyntaxKind.InKeyword) { // Looks like a foreach statement. Parse it that way instead this.Reset(ref resetPoint); return this.ParseForEachStatement(attributes, awaitTokenOpt: null); } else { // Normal for statement. this.Reset(ref resetPoint); return this.ParseForStatement(attributes); } } finally { this.Release(ref resetPoint); } } private ForStatementSyntax ParseForStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ForKeyword); var forToken = this.EatToken(SyntaxKind.ForKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfForStatementArgument; var resetPoint = this.GetResetPoint(); var initializers = _pool.AllocateSeparated<ExpressionSyntax>(); var incrementors = _pool.AllocateSeparated<ExpressionSyntax>(); try { // Here can be either a declaration or an expression statement list. Scan // for a declaration first. VariableDeclarationSyntax decl = null; bool isDeclaration = false; if (this.CurrentToken.Kind == SyntaxKind.RefKeyword) { isDeclaration = true; } else { isDeclaration = !this.IsQueryExpression(mayBeVariableDeclaration: true, mayBeMemberDeclaration: false) && this.ScanType() != ScanTypeFlags.NotType && this.IsTrueIdentifier(); this.Reset(ref resetPoint); } if (isDeclaration) { decl = ParseVariableDeclaration(); if (decl.Type.Kind == SyntaxKind.RefType) { decl = decl.Update( CheckFeatureAvailability(decl.Type, MessageID.IDS_FeatureRefFor), decl.Variables); } } else if (this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { // Not a type followed by an identifier, so it must be an expression list. this.ParseForStatementExpressionList(ref openParen, initializers); } var semi = this.EatToken(SyntaxKind.SemicolonToken); ExpressionSyntax condition = null; if (this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { condition = this.ParseExpressionCore(); } var semi2 = this.EatToken(SyntaxKind.SemicolonToken); if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { this.ParseForStatementExpressionList(ref semi2, incrementors); } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = ParseEmbeddedStatement(); return _syntaxFactory.ForStatement(attributes, forToken, openParen, decl, initializers, semi, condition, semi2, incrementors, closeParen, statement); } finally { _termState = saveTerm; this.Release(ref resetPoint); _pool.Free(incrementors); _pool.Free(initializers); } } private bool IsEndOfForStatementArgument() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; } private void ParseForStatementExpressionList(ref SyntaxToken startToken, SeparatedSyntaxListBuilder<ExpressionSyntax> list) { if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken && this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { tryAgain: if (this.IsPossibleExpression() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument list.Add(this.ParseExpressionCore()); // additional arguments int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleExpression()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); list.Add(this.ParseExpressionCore()); continue; } else if (this.SkipBadForStatementExpressionListTokens(ref startToken, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadForStatementExpressionListTokens(ref startToken, list, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } } private PostSkipAction SkipBadForStatementExpressionListTokens(ref SyntaxToken startToken, SeparatedSyntaxListBuilder<ExpressionSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), p => p.CurrentToken.Kind == SyntaxKind.CloseParenToken || p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsTerminator(), expected); } private CommonForEachStatementSyntax ParseForEachStatement( SyntaxList<AttributeListSyntax> attributes, SyntaxToken awaitTokenOpt) { // Can be a 'for' keyword if the user typed: 'for (SomeType t in' Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ForEachKeyword || this.CurrentToken.Kind == SyntaxKind.ForKeyword); // Syntax for foreach is either: // foreach [await] ( <type> <identifier> in <expr> ) <embedded-statement> // or // foreach [await] ( <deconstruction-declaration> in <expr> ) <embedded-statement> SyntaxToken @foreach; // If we're at a 'for', then consume it and attach // it as skipped text to the missing 'foreach' token. if (this.CurrentToken.Kind == SyntaxKind.ForKeyword) { var skippedForToken = this.EatToken(); skippedForToken = this.AddError(skippedForToken, ErrorCode.ERR_SyntaxError, SyntaxFacts.GetText(SyntaxKind.ForEachKeyword), SyntaxFacts.GetText(SyntaxKind.ForKeyword)); @foreach = ConvertToMissingWithTrailingTrivia(skippedForToken, SyntaxKind.ForEachKeyword); } else { @foreach = this.EatToken(SyntaxKind.ForEachKeyword); } var openParen = this.EatToken(SyntaxKind.OpenParenToken); var variable = ParseExpressionOrDeclaration(ParseTypeMode.Normal, feature: MessageID.IDS_FeatureTuples, permitTupleDesignation: true); var @in = this.EatToken(SyntaxKind.InKeyword, ErrorCode.ERR_InExpected); if (!IsValidForeachVariable(variable)) { @in = this.AddError(@in, ErrorCode.ERR_BadForeachDecl); } var expression = this.ParseExpressionCore(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = this.ParseEmbeddedStatement(); if (variable is DeclarationExpressionSyntax decl) { if (decl.Type.Kind == SyntaxKind.RefType) { decl = decl.Update( CheckFeatureAvailability(decl.Type, MessageID.IDS_FeatureRefForEach), decl.Designation); } if (decl.designation.Kind != SyntaxKind.ParenthesizedVariableDesignation) { // if we see a foreach declaration that isn't a deconstruction, we use the old form of foreach syntax node. SyntaxToken identifier; switch (decl.designation.Kind) { case SyntaxKind.SingleVariableDesignation: identifier = ((SingleVariableDesignationSyntax)decl.designation).identifier; break; case SyntaxKind.DiscardDesignation: // revert the identifier from its contextual underscore back to an identifier. var discard = ((DiscardDesignationSyntax)decl.designation).underscoreToken; Debug.Assert(discard.Kind == SyntaxKind.UnderscoreToken); identifier = SyntaxToken.WithValue(SyntaxKind.IdentifierToken, discard.LeadingTrivia.Node, discard.Text, discard.ValueText, discard.TrailingTrivia.Node); break; default: throw ExceptionUtilities.UnexpectedValue(decl.designation.Kind); } return _syntaxFactory.ForEachStatement(attributes, awaitTokenOpt, @foreach, openParen, decl.Type, identifier, @in, expression, closeParen, statement); } } return _syntaxFactory.ForEachVariableStatement(attributes, awaitTokenOpt, @foreach, openParen, variable, @in, expression, closeParen, statement); } // // Parse an expression where a declaration expression would be permitted. This is suitable for use after // the `out` keyword in an argument list, or in the elements of a tuple literal (because they may // be on the left-hand-side of a positional subpattern). The first element of a tuple is handled slightly // differently, as we check for the comma before concluding that the identifier should cause a // disambiguation. For example, for the input `(A < B , C > D)`, we treat this as a tuple with // two elements, because if we considered the `A<B,C>` to be a type, it wouldn't be a tuple at // all. Since we don't have such a thing as a one-element tuple (even for positional subpattern), the // absence of the comma after the `D` means we don't treat the `D` as contributing to the // disambiguation of the expression/type. More formally, ... // // If a sequence of tokens can be parsed(in context) as a* simple-name* (§7.6.3), *member-access* (§7.6.5), // or* pointer-member-access* (§18.5.2) ending with a* type-argument-list* (§4.4.1), the token immediately // following the closing `>` token is examined, to see if it is // - One of `( ) ] } : ; , . ? == != | ^ && || & [`; or // - One of the relational operators `< > <= >= is as`; or // - A contextual query keyword appearing inside a query expression; or // - In certain contexts, we treat *identifier* as a disambiguating token.Those contexts are where the // sequence of tokens being disambiguated is immediately preceded by one of the keywords `is`, `case` // or `out`, or arises while parsing the first element of a tuple literal(in which case the tokens are // preceded by `(` or `:` and the identifier is followed by a `,`) or a subsequent element of a tuple literal. // // If the following token is among this list, or an identifier in such a context, then the *type-argument-list* is // retained as part of the *simple-name*, *member-access* or *pointer-member-access* and any other possible parse // of the sequence of tokens is discarded.Otherwise, the *type-argument-list* is not considered to be part of the // *simple-name*, *member-access* or *pointer-member-access*, even if there is no other possible parse of the // sequence of tokens.Note that these rules are not applied when parsing a *type-argument-list* in a *namespace-or-type-name* (§3.8). // // See also ScanTypeArgumentList where these disambiguation rules are encoded. // private ExpressionSyntax ParseExpressionOrDeclaration(ParseTypeMode mode, MessageID feature, bool permitTupleDesignation) { return IsPossibleDeclarationExpression(mode, permitTupleDesignation) ? this.ParseDeclarationExpression(mode, feature) : this.ParseSubExpression(Precedence.Expression); } private bool IsPossibleDeclarationExpression(ParseTypeMode mode, bool permitTupleDesignation) { if (this.IsInAsync && this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword) { // can't be a declaration expression. return false; } var resetPoint = this.GetResetPoint(); try { bool typeIsVar = IsVarType(); SyntaxToken lastTokenOfType; if (ScanType(mode, out lastTokenOfType) == ScanTypeFlags.NotType) { return false; } // check for a designation if (!ScanDesignation(permitTupleDesignation && (typeIsVar || IsPredefinedType(lastTokenOfType.Kind)))) { return false; } switch (mode) { case ParseTypeMode.FirstElementOfPossibleTupleLiteral: return this.CurrentToken.Kind == SyntaxKind.CommaToken; case ParseTypeMode.AfterTupleComma: return this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.CloseParenToken; default: // The other case where we disambiguate between a declaration and expression is before the `in` of a foreach loop. // There we err on the side of accepting a declaration. return true; } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } /// <summary> /// Is the following set of tokens, interpreted as a type, the type <c>var</c>? /// </summary> private bool IsVarType() { if (!this.CurrentToken.IsIdentifierVar()) { return false; } switch (this.PeekToken(1).Kind) { case SyntaxKind.DotToken: case SyntaxKind.ColonColonToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.AsteriskToken: case SyntaxKind.QuestionToken: case SyntaxKind.LessThanToken: return false; default: return true; } } private static bool IsValidForeachVariable(ExpressionSyntax variable) { switch (variable.Kind) { case SyntaxKind.DeclarationExpression: // e.g. `foreach (var (x, y) in e)` return true; case SyntaxKind.TupleExpression: // e.g. `foreach ((var x, var y) in e)` return true; case SyntaxKind.IdentifierName: // e.g. `foreach (_ in e)` return ((IdentifierNameSyntax)variable).Identifier.ContextualKind == SyntaxKind.UnderscoreToken; default: return false; } } private GotoStatementSyntax ParseGotoStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.GotoKeyword); var @goto = this.EatToken(SyntaxKind.GotoKeyword); SyntaxToken caseOrDefault = null; ExpressionSyntax arg = null; SyntaxKind kind; if (this.CurrentToken.Kind == SyntaxKind.CaseKeyword || this.CurrentToken.Kind == SyntaxKind.DefaultKeyword) { caseOrDefault = this.EatToken(); if (caseOrDefault.Kind == SyntaxKind.CaseKeyword) { kind = SyntaxKind.GotoCaseStatement; arg = this.ParseExpressionCore(); } else { kind = SyntaxKind.GotoDefaultStatement; } } else { kind = SyntaxKind.GotoStatement; arg = this.ParseIdentifierName(); } var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.GotoStatement(kind, attributes, @goto, caseOrDefault, arg, semicolon); } private IfStatementSyntax ParseIfStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.IfKeyword); return _syntaxFactory.IfStatement( attributes, this.EatToken(SyntaxKind.IfKeyword), this.EatToken(SyntaxKind.OpenParenToken), this.ParseExpressionCore(), this.EatToken(SyntaxKind.CloseParenToken), this.ParseEmbeddedStatement(), this.ParseElseClauseOpt()); } private IfStatementSyntax ParseMisplacedElse(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ElseKeyword); return _syntaxFactory.IfStatement( attributes, this.EatToken(SyntaxKind.IfKeyword, ErrorCode.ERR_ElseCannotStartStatement), this.EatToken(SyntaxKind.OpenParenToken), this.ParseExpressionCore(), this.EatToken(SyntaxKind.CloseParenToken), this.ParseExpressionStatement(attributes: default), this.ParseElseClauseOpt()); } private ElseClauseSyntax ParseElseClauseOpt() { if (this.CurrentToken.Kind != SyntaxKind.ElseKeyword) { return null; } var elseToken = this.EatToken(SyntaxKind.ElseKeyword); var elseStatement = this.ParseEmbeddedStatement(); return _syntaxFactory.ElseClause(elseToken, elseStatement); } private LockStatementSyntax ParseLockStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.LockKeyword); var @lock = this.EatToken(SyntaxKind.LockKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expression = this.ParseExpressionCore(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = this.ParseEmbeddedStatement(); return _syntaxFactory.LockStatement(attributes, @lock, openParen, expression, closeParen, statement); } private ReturnStatementSyntax ParseReturnStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ReturnKeyword); var @return = this.EatToken(SyntaxKind.ReturnKeyword); ExpressionSyntax arg = null; if (this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { arg = this.ParsePossibleRefExpression(); } var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.ReturnStatement(attributes, @return, arg, semicolon); } private YieldStatementSyntax ParseYieldStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.YieldKeyword); var yieldToken = ConvertToKeyword(this.EatToken()); SyntaxToken returnOrBreak; ExpressionSyntax arg = null; SyntaxKind kind; yieldToken = CheckFeatureAvailability(yieldToken, MessageID.IDS_FeatureIterators); if (this.CurrentToken.Kind == SyntaxKind.BreakKeyword) { kind = SyntaxKind.YieldBreakStatement; returnOrBreak = this.EatToken(); } else { kind = SyntaxKind.YieldReturnStatement; returnOrBreak = this.EatToken(SyntaxKind.ReturnKeyword); if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { returnOrBreak = this.AddError(returnOrBreak, ErrorCode.ERR_EmptyYield); } else { arg = this.ParseExpressionCore(); } } var semi = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.YieldStatement(kind, attributes, yieldToken, returnOrBreak, arg, semi); } private SwitchStatementSyntax ParseSwitchStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.SwitchKeyword); var @switch = this.EatToken(SyntaxKind.SwitchKeyword); var expression = this.ParseExpressionCore(); SyntaxToken openParen; SyntaxToken closeParen; if (expression.Kind == SyntaxKind.ParenthesizedExpression) { var parenExpression = (ParenthesizedExpressionSyntax)expression; openParen = parenExpression.OpenParenToken; expression = parenExpression.Expression; closeParen = parenExpression.CloseParenToken; Debug.Assert(parenExpression.GetDiagnostics().Length == 0); } else if (expression.Kind == SyntaxKind.TupleExpression) { // As a special case, when a tuple literal is the governing expression of // a switch statement we permit the switch statement's own parentheses to be omitted. // LDM 2018-04-04. openParen = closeParen = null; } else { // Some other expression has appeared without parens. Give a syntax error. openParen = SyntaxFactory.MissingToken(SyntaxKind.OpenParenToken); expression = this.AddError(expression, ErrorCode.ERR_SwitchGoverningExpressionRequiresParens); closeParen = SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken); } var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var sections = _pool.Allocate<SwitchSectionSyntax>(); try { while (this.IsPossibleSwitchSection()) { var swcase = this.ParseSwitchSection(); sections.Add(swcase); } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); return _syntaxFactory.SwitchStatement(attributes, @switch, openParen, expression, closeParen, openBrace, sections, closeBrace); } finally { _pool.Free(sections); } } private bool IsPossibleSwitchSection() { return (this.CurrentToken.Kind == SyntaxKind.CaseKeyword) || (this.CurrentToken.Kind == SyntaxKind.DefaultKeyword && this.PeekToken(1).Kind != SyntaxKind.OpenParenToken); } private SwitchSectionSyntax ParseSwitchSection() { Debug.Assert(this.IsPossibleSwitchSection()); // First, parse case label(s) var labels = _pool.Allocate<SwitchLabelSyntax>(); var statements = _pool.Allocate<StatementSyntax>(); try { do { SyntaxToken specifier; SwitchLabelSyntax label; SyntaxToken colon; if (this.CurrentToken.Kind == SyntaxKind.CaseKeyword) { ExpressionSyntax expression; specifier = this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { expression = ParseIdentifierName(ErrorCode.ERR_ConstantExpected); colon = this.EatToken(SyntaxKind.ColonToken); label = _syntaxFactory.CaseSwitchLabel(specifier, expression, colon); } else { var node = ParseExpressionOrPatternForSwitchStatement(); // if there is a 'when' token, we treat a case expression as a constant pattern. if (this.CurrentToken.ContextualKind == SyntaxKind.WhenKeyword && node is ExpressionSyntax ex) node = _syntaxFactory.ConstantPattern(ex); if (node.Kind == SyntaxKind.DiscardPattern) node = this.AddError(node, ErrorCode.ERR_DiscardPatternInSwitchStatement); if (node is PatternSyntax pat) { var whenClause = ParseWhenClause(Precedence.Expression); colon = this.EatToken(SyntaxKind.ColonToken); label = _syntaxFactory.CasePatternSwitchLabel(specifier, pat, whenClause, colon); label = CheckFeatureAvailability(label, MessageID.IDS_FeaturePatternMatching); } else { colon = this.EatToken(SyntaxKind.ColonToken); label = _syntaxFactory.CaseSwitchLabel(specifier, (ExpressionSyntax)node, colon); } } } else { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.DefaultKeyword); specifier = this.EatToken(SyntaxKind.DefaultKeyword); colon = this.EatToken(SyntaxKind.ColonToken); label = _syntaxFactory.DefaultSwitchLabel(specifier, colon); } labels.Add(label); } while (IsPossibleSwitchSection()); // Next, parse statement list stopping for new sections CSharpSyntaxNode tmp = labels[labels.Count - 1]; this.ParseStatements(ref tmp, statements, true); labels[labels.Count - 1] = (SwitchLabelSyntax)tmp; return _syntaxFactory.SwitchSection(labels, statements); } finally { _pool.Free(statements); _pool.Free(labels); } } private ThrowStatementSyntax ParseThrowStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ThrowKeyword); var @throw = this.EatToken(SyntaxKind.ThrowKeyword); ExpressionSyntax arg = null; if (this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { arg = this.ParseExpressionCore(); } var semi = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.ThrowStatement(attributes, @throw, arg, semi); } private UnsafeStatementSyntax ParseUnsafeStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.UnsafeKeyword); var @unsafe = this.EatToken(SyntaxKind.UnsafeKeyword); var block = this.ParsePossiblyAttributedBlock(); return _syntaxFactory.UnsafeStatement(attributes, @unsafe, block); } private UsingStatementSyntax ParseUsingStatement(SyntaxList<AttributeListSyntax> attributes, SyntaxToken awaitTokenOpt = null) { var @using = this.EatToken(SyntaxKind.UsingKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); VariableDeclarationSyntax declaration = null; ExpressionSyntax expression = null; var resetPoint = this.GetResetPoint(); ParseUsingExpression(ref declaration, ref expression, ref resetPoint); this.Release(ref resetPoint); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = this.ParseEmbeddedStatement(); return _syntaxFactory.UsingStatement(attributes, awaitTokenOpt, @using, openParen, declaration, expression, closeParen, statement); } private void ParseUsingExpression(ref VariableDeclarationSyntax declaration, ref ExpressionSyntax expression, ref ResetPoint resetPoint) { if (this.IsAwaitExpression()) { expression = this.ParseExpressionCore(); return; } // Now, this can be either an expression or a decl list ScanTypeFlags st; if (this.IsQueryExpression(mayBeVariableDeclaration: true, mayBeMemberDeclaration: false)) { st = ScanTypeFlags.NotType; } else { st = this.ScanType(); } if (st == ScanTypeFlags.NullableType) { // We need to handle: // * using (f ? x = a : x = b) // * using (f ? x = a) // * using (f ? x, y) if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { this.Reset(ref resetPoint); expression = this.ParseExpressionCore(); } else { switch (this.PeekToken(1).Kind) { default: this.Reset(ref resetPoint); expression = this.ParseExpressionCore(); break; case SyntaxKind.CommaToken: case SyntaxKind.CloseParenToken: this.Reset(ref resetPoint); declaration = ParseVariableDeclaration(); break; case SyntaxKind.EqualsToken: // Parse it as a decl. If the next token is a : and only one variable was parsed, // convert the whole thing to ?: expression. this.Reset(ref resetPoint); declaration = ParseVariableDeclaration(); // We may have non-nullable types in error scenarios. if (this.CurrentToken.Kind == SyntaxKind.ColonToken && declaration.Type.Kind == SyntaxKind.NullableType && SyntaxFacts.IsName(((NullableTypeSyntax)declaration.Type).ElementType.Kind) && declaration.Variables.Count == 1) { // We have "name? id = expr :" so need to convert to a ?: expression. this.Reset(ref resetPoint); declaration = null; expression = this.ParseExpressionCore(); } break; } } } else if (IsUsingStatementVariableDeclaration(st)) { this.Reset(ref resetPoint); declaration = ParseVariableDeclaration(); } else { // Must be an expression statement this.Reset(ref resetPoint); expression = this.ParseExpressionCore(); } } private bool IsUsingStatementVariableDeclaration(ScanTypeFlags st) { Debug.Assert(st != ScanTypeFlags.NullableType); bool condition1 = st == ScanTypeFlags.MustBeType && this.CurrentToken.Kind != SyntaxKind.DotToken; bool condition2 = st != ScanTypeFlags.NotType && this.CurrentToken.Kind == SyntaxKind.IdentifierToken; bool condition3 = st == ScanTypeFlags.NonGenericTypeOrExpression || this.PeekToken(1).Kind == SyntaxKind.EqualsToken; return condition1 || (condition2 && condition3); } private WhileStatementSyntax ParseWhileStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.WhileKeyword); var @while = this.EatToken(SyntaxKind.WhileKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var condition = this.ParseExpressionCore(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = this.ParseEmbeddedStatement(); return _syntaxFactory.WhileStatement(attributes, @while, openParen, condition, closeParen, statement); } private LabeledStatementSyntax ParseLabeledStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.IdentifierToken); // We have an identifier followed by a colon. But if the identifier is a contextual keyword in a query context, // ParseIdentifier will result in a missing name and Eat(Colon) will fail. We won't make forward progress. Debug.Assert(this.IsTrueIdentifier()); var label = this.ParseIdentifierToken(); var colon = this.EatToken(SyntaxKind.ColonToken); Debug.Assert(!colon.IsMissing); var statement = this.ParsePossiblyAttributedStatement() ?? SyntaxFactory.EmptyStatement(attributeLists: default, EatToken(SyntaxKind.SemicolonToken)); return _syntaxFactory.LabeledStatement(attributes, label, colon, statement); } /// <summary> /// Parses any kind of local declaration statement: local variable or local function. /// </summary> private StatementSyntax ParseLocalDeclarationStatement(SyntaxList<AttributeListSyntax> attributes) { SyntaxToken awaitKeyword, usingKeyword; bool canParseAsLocalFunction = false; if (IsPossibleAwaitUsing()) { awaitKeyword = ParseAwaitKeyword(MessageID.None); usingKeyword = EatToken(); } else if (this.CurrentToken.Kind == SyntaxKind.UsingKeyword) { awaitKeyword = null; usingKeyword = EatToken(); } else { awaitKeyword = null; usingKeyword = null; canParseAsLocalFunction = true; } if (usingKeyword != null) { usingKeyword = CheckFeatureAvailability(usingKeyword, MessageID.IDS_FeatureUsingDeclarations); } var mods = _pool.Allocate(); this.ParseDeclarationModifiers(mods); var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseLocalDeclaration(variables, allowLocalFunctions: canParseAsLocalFunction, attributes: attributes, mods: mods.ToList(), type: out var type, localFunction: out var localFunction); if (localFunction != null) { Debug.Assert(variables.Count == 0); return localFunction; } if (canParseAsLocalFunction) { // If we find an accessibility modifier but no local function it's likely // the user forgot a closing brace. Let's back out of statement parsing. // We check just for a leading accessibility modifier in the syntax because // SkipBadStatementListTokens will not skip attribute lists. if (attributes.Count == 0 && mods.Count > 0 && IsAccessibilityModifier(((SyntaxToken)mods[0]).ContextualKind)) { return null; } } for (int i = 0; i < mods.Count; i++) { var mod = (SyntaxToken)mods[i]; if (IsAdditionalLocalFunctionModifier(mod.ContextualKind)) { mods[i] = this.AddError(mod, ErrorCode.ERR_BadMemberFlag, mod.Text); } } var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.LocalDeclarationStatement( attributes, awaitKeyword, usingKeyword, mods.ToList(), _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _pool.Free(variables); _pool.Free(mods); } } private VariableDesignationSyntax ParseDesignation(bool forPattern) { // the two forms of designation are // (1) identifier // (2) ( designation ... ) // for pattern-matching, we permit the designation list to be empty VariableDesignationSyntax result; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var openParen = this.EatToken(SyntaxKind.OpenParenToken); var listOfDesignations = _pool.AllocateSeparated<VariableDesignationSyntax>(); bool done = false; if (forPattern) { done = (this.CurrentToken.Kind == SyntaxKind.CloseParenToken); } else { listOfDesignations.Add(ParseDesignation(forPattern)); listOfDesignations.AddSeparator(EatToken(SyntaxKind.CommaToken)); } if (!done) { while (true) { listOfDesignations.Add(ParseDesignation(forPattern)); if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { listOfDesignations.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); } else { break; } } } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); result = _syntaxFactory.ParenthesizedVariableDesignation(openParen, listOfDesignations, closeParen); _pool.Free(listOfDesignations); } else { result = ParseSimpleDesignation(); } return result; } /// <summary> /// Parse a single variable designation (e.g. <c>x</c>) or a wildcard designation (e.g. <c>_</c>) /// </summary> /// <returns></returns> private VariableDesignationSyntax ParseSimpleDesignation() { if (CurrentToken.ContextualKind == SyntaxKind.UnderscoreToken) { var underscore = this.EatContextualToken(SyntaxKind.UnderscoreToken); return _syntaxFactory.DiscardDesignation(underscore); } else { var identifier = this.EatToken(SyntaxKind.IdentifierToken); return _syntaxFactory.SingleVariableDesignation(identifier); } } private WhenClauseSyntax ParseWhenClause(Precedence precedence) { if (this.CurrentToken.ContextualKind != SyntaxKind.WhenKeyword) { return null; } var when = this.EatContextualToken(SyntaxKind.WhenKeyword); var condition = ParseSubExpression(precedence); return _syntaxFactory.WhenClause(when, condition); } /// <summary> /// Parse a local variable declaration. /// </summary> /// <returns></returns> private VariableDeclarationSyntax ParseVariableDeclaration() { var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); TypeSyntax type; LocalFunctionStatementSyntax localFunction; ParseLocalDeclaration(variables, false, attributes: default, mods: default, out type, out localFunction); Debug.Assert(localFunction == null); var result = _syntaxFactory.VariableDeclaration(type, variables); _pool.Free(variables); return result; } private void ParseLocalDeclaration( SeparatedSyntaxListBuilder<VariableDeclaratorSyntax> variables, bool allowLocalFunctions, SyntaxList<AttributeListSyntax> attributes, SyntaxList<SyntaxToken> mods, out TypeSyntax type, out LocalFunctionStatementSyntax localFunction) { type = allowLocalFunctions ? ParseReturnType() : this.ParseType(); VariableFlags flags = VariableFlags.Local; if (mods.Any((int)SyntaxKind.ConstKeyword)) { flags |= VariableFlags.Const; } var saveTerm = _termState; _termState |= TerminatorState.IsEndOfDeclarationClause; this.ParseVariableDeclarators( type, flags, variables, variableDeclarationsExpected: true, allowLocalFunctions: allowLocalFunctions, attributes: attributes, mods: mods, localFunction: out localFunction); _termState = saveTerm; if (allowLocalFunctions && localFunction == null && (type as PredefinedTypeSyntax)?.Keyword.Kind == SyntaxKind.VoidKeyword) { type = this.AddError(type, ErrorCode.ERR_NoVoidHere); } } private bool IsEndOfDeclarationClause() { switch (this.CurrentToken.Kind) { case SyntaxKind.SemicolonToken: case SyntaxKind.CloseParenToken: case SyntaxKind.ColonToken: return true; default: return false; } } private void ParseDeclarationModifiers(SyntaxListBuilder list) { SyntaxKind k; while (IsDeclarationModifier(k = this.CurrentToken.ContextualKind) || IsAdditionalLocalFunctionModifier(k)) { SyntaxToken mod; if (k == SyntaxKind.AsyncKeyword) { // check for things like "async async()" where async is the type and/or the function name { var resetPoint = this.GetResetPoint(); var invalid = !IsPossibleStartOfTypeDeclaration(this.EatToken().Kind) && !IsDeclarationModifier(this.CurrentToken.Kind) && !IsAdditionalLocalFunctionModifier(this.CurrentToken.Kind) && (ScanType() == ScanTypeFlags.NotType || this.CurrentToken.Kind != SyntaxKind.IdentifierToken); this.Reset(ref resetPoint); this.Release(ref resetPoint); if (invalid) { break; } } mod = this.EatContextualToken(k); if (k == SyntaxKind.AsyncKeyword) { mod = CheckFeatureAvailability(mod, MessageID.IDS_FeatureAsync); } } else { mod = this.EatToken(); } if (k == SyntaxKind.ReadOnlyKeyword || k == SyntaxKind.VolatileKeyword) { mod = this.AddError(mod, ErrorCode.ERR_BadMemberFlag, mod.Text); } else if (list.Any(mod.RawKind)) { // check for duplicates, can only be const mod = this.AddError(mod, ErrorCode.ERR_TypeExpected, mod.Text); } list.Add(mod); } } private static bool IsDeclarationModifier(SyntaxKind kind) { switch (kind) { case SyntaxKind.ConstKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: return true; default: return false; } } private static bool IsAdditionalLocalFunctionModifier(SyntaxKind kind) { switch (kind) { case SyntaxKind.StaticKeyword: case SyntaxKind.AsyncKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.ExternKeyword: // Not a valid modifier, but we should parse to give a good // error message case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: return true; default: return false; } } private static bool IsAccessibilityModifier(SyntaxKind kind) { switch (kind) { // Accessibility modifiers aren't legal in a local function, // but a common mistake. Parse to give a better error message. case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: return true; default: return false; } } private LocalFunctionStatementSyntax TryParseLocalFunctionStatementBody( SyntaxList<AttributeListSyntax> attributes, SyntaxList<SyntaxToken> modifiers, TypeSyntax type, SyntaxToken identifier) { // This may potentially be an ambiguous parse until very far into the token stream, so we may have to backtrack. // For example, "await x()" is ambiguous at the current point of parsing (right now we're right after the x). // The point at which it becomes unambiguous is after the argument list. A "=>" or "{" means its a local function // (with return type @await), a ";" or other expression-y token means its an await of a function call. // Note that we could just check if we're in an async context, but that breaks some analyzers, because // "await f();" would be parsed as a local function statement when really we want a parse error so we can say // "did you mean to make this method be an async method?" (it's invalid either way, so the spec doesn't care) var resetPoint = this.GetResetPoint(); // Indicates this must be parsed as a local function, even if there's no body bool forceLocalFunc = true; if (type.Kind == SyntaxKind.IdentifierName) { var id = ((IdentifierNameSyntax)type).Identifier; forceLocalFunc = id.ContextualKind != SyntaxKind.AwaitKeyword; } bool parentScopeIsInAsync = IsInAsync; IsInAsync = false; SyntaxListBuilder badBuilder = null; for (int i = 0; i < modifiers.Count; i++) { var modifier = modifiers[i]; switch (modifier.ContextualKind) { case SyntaxKind.AsyncKeyword: IsInAsync = true; forceLocalFunc = true; continue; case SyntaxKind.UnsafeKeyword: forceLocalFunc = true; continue; case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: continue; // already reported earlier, no need to report again case SyntaxKind.StaticKeyword: modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureStaticLocalFunctions); if ((object)modifier == modifiers[i]) { continue; } break; case SyntaxKind.ExternKeyword: modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureExternLocalFunctions); if ((object)modifier == modifiers[i]) { continue; } break; default: modifier = this.AddError(modifier, ErrorCode.ERR_BadMemberFlag, modifier.Text); break; } if (badBuilder == null) { badBuilder = _pool.Allocate(); badBuilder.AddRange(modifiers); } badBuilder[i] = modifier; } if (badBuilder != null) { modifiers = badBuilder.ToList(); _pool.Free(badBuilder); } TypeParameterListSyntax typeParameterListOpt = this.ParseTypeParameterList(); // "await f<T>()" still makes sense, so don't force accept a local function if there's a type parameter list. ParameterListSyntax paramList = this.ParseParenthesizedParameterList(); // "await x()" is ambiguous (see note at start of this method), but we assume "await x(await y)" is meant to be a function if it's in a non-async context. if (!forceLocalFunc) { var paramListSyntax = paramList.Parameters; for (int i = 0; i < paramListSyntax.Count; i++) { // "await x(y)" still parses as a parameter list, so check to see if it's a valid parameter (like "x(t y)") forceLocalFunc |= !paramListSyntax[i].ContainsDiagnostics; if (forceLocalFunc) break; } } var constraints = default(SyntaxListBuilder<TypeParameterConstraintClauseSyntax>); if (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { constraints = _pool.Allocate<TypeParameterConstraintClauseSyntax>(); this.ParseTypeParameterConstraintClauses(constraints); forceLocalFunc = true; } BlockSyntax blockBody; ArrowExpressionClauseSyntax expressionBody; SyntaxToken semicolon; this.ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon, parseSemicolonAfterBlock: false); IsInAsync = parentScopeIsInAsync; if (!forceLocalFunc && blockBody == null && expressionBody == null) { this.Reset(ref resetPoint); this.Release(ref resetPoint); return null; } this.Release(ref resetPoint); identifier = CheckFeatureAvailability(identifier, MessageID.IDS_FeatureLocalFunctions); return _syntaxFactory.LocalFunctionStatement( attributes, modifiers, type, identifier, typeParameterListOpt, paramList, constraints, blockBody, expressionBody, semicolon); } private ExpressionStatementSyntax ParseExpressionStatement(SyntaxList<AttributeListSyntax> attributes) { return ParseExpressionStatement(attributes, this.ParseExpressionCore()); } private ExpressionStatementSyntax ParseExpressionStatement(SyntaxList<AttributeListSyntax> attributes, ExpressionSyntax expression) { SyntaxToken semicolon; if (IsScript && this.CurrentToken.Kind == SyntaxKind.EndOfFileToken) { semicolon = SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken); } else { // Do not report an error if the expression is not a statement expression. // The error is reported in semantic analysis. semicolon = this.EatToken(SyntaxKind.SemicolonToken); } return _syntaxFactory.ExpressionStatement(attributes, expression, semicolon); } public ExpressionSyntax ParseExpression() { return ParseWithStackGuard( this.ParseExpressionCore, this.CreateMissingIdentifierName); } private ExpressionSyntax ParseExpressionCore() { return this.ParseSubExpression(Precedence.Expression); } /// <summary> /// Is the current token one that could start an expression? /// </summary> private bool CanStartExpression() { return IsPossibleExpression(allowBinaryExpressions: false, allowAssignmentExpressions: false, allowAttributes: false); } /// <summary> /// Is the current token one that could be in an expression? /// </summary> private bool IsPossibleExpression() { return IsPossibleExpression(allowBinaryExpressions: true, allowAssignmentExpressions: true, allowAttributes: true); } private bool IsPossibleExpression(bool allowBinaryExpressions, bool allowAssignmentExpressions, bool allowAttributes) { SyntaxKind tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.TypeOfKeyword: case SyntaxKind.DefaultKeyword: case SyntaxKind.SizeOfKeyword: case SyntaxKind.MakeRefKeyword: case SyntaxKind.RefTypeKeyword: case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: case SyntaxKind.RefValueKeyword: case SyntaxKind.ArgListKeyword: case SyntaxKind.BaseKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.ThisKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.NullKeyword: case SyntaxKind.OpenParenToken: case SyntaxKind.NumericLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.NewKeyword: case SyntaxKind.DelegateKeyword: case SyntaxKind.ColonColonToken: // bad aliased name case SyntaxKind.ThrowKeyword: case SyntaxKind.StackAllocKeyword: case SyntaxKind.DotDotToken: case SyntaxKind.RefKeyword: return true; case SyntaxKind.StaticKeyword: return IsPossibleAnonymousMethodExpression() || IsPossibleLambdaExpression(Precedence.Expression); case SyntaxKind.OpenBracketToken: return allowAttributes && IsPossibleLambdaExpression(Precedence.Expression); case SyntaxKind.IdentifierToken: // Specifically allow the from contextual keyword, because it can always be the start of an // expression (whether it is used as an identifier or a keyword). return this.IsTrueIdentifier() || (this.CurrentToken.ContextualKind == SyntaxKind.FromKeyword); default: return IsPredefinedType(tk) || SyntaxFacts.IsAnyUnaryExpression(tk) || (allowBinaryExpressions && SyntaxFacts.IsBinaryExpression(tk)) || (allowAssignmentExpressions && SyntaxFacts.IsAssignmentExpressionOperatorToken(tk)); } } private static bool IsInvalidSubExpression(SyntaxKind kind) { switch (kind) { case SyntaxKind.BreakKeyword: case SyntaxKind.CaseKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.FinallyKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.LockKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.UsingKeyword: case SyntaxKind.WhileKeyword: return true; default: return false; } } internal static bool IsRightAssociative(SyntaxKind op) { switch (op) { case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: case SyntaxKind.CoalesceExpression: return true; default: return false; } } private enum Precedence : uint { Expression = 0, // Loosest possible precedence, used to accept all expressions Assignment = Expression, Lambda = Assignment, // "The => operator has the same precedence as assignment (=) and is right-associative." Conditional, Coalescing, ConditionalOr, ConditionalAnd, LogicalOr, LogicalXor, LogicalAnd, Equality, Relational, Shift, Additive, Multiplicative, Switch, Range, Unary, Cast, PointerIndirection, AddressOf, Primary, } private static Precedence GetPrecedence(SyntaxKind op) { switch (op) { case SyntaxKind.QueryExpression: return Precedence.Expression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return Precedence.Lambda; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: return Precedence.Assignment; case SyntaxKind.CoalesceExpression: case SyntaxKind.ThrowExpression: return Precedence.Coalescing; case SyntaxKind.LogicalOrExpression: return Precedence.ConditionalOr; case SyntaxKind.LogicalAndExpression: return Precedence.ConditionalAnd; case SyntaxKind.BitwiseOrExpression: return Precedence.LogicalOr; case SyntaxKind.ExclusiveOrExpression: return Precedence.LogicalXor; case SyntaxKind.BitwiseAndExpression: return Precedence.LogicalAnd; case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: return Precedence.Equality; case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.IsPatternExpression: return Precedence.Relational; case SyntaxKind.SwitchExpression: case SyntaxKind.WithExpression: return Precedence.Switch; case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: return Precedence.Shift; case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: return Precedence.Additive; case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: return Precedence.Multiplicative; case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.BitwiseNotExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.SizeOfExpression: case SyntaxKind.CheckedExpression: case SyntaxKind.UncheckedExpression: case SyntaxKind.MakeRefExpression: case SyntaxKind.RefValueExpression: case SyntaxKind.RefTypeExpression: case SyntaxKind.AwaitExpression: case SyntaxKind.IndexExpression: return Precedence.Unary; case SyntaxKind.CastExpression: return Precedence.Cast; case SyntaxKind.PointerIndirectionExpression: return Precedence.PointerIndirection; case SyntaxKind.AddressOfExpression: return Precedence.AddressOf; case SyntaxKind.RangeExpression: return Precedence.Range; case SyntaxKind.ConditionalExpression: return Precedence.Expression; case SyntaxKind.AliasQualifiedName: case SyntaxKind.AnonymousObjectCreationExpression: case SyntaxKind.ArgListExpression: case SyntaxKind.ArrayCreationExpression: case SyntaxKind.BaseExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.ConditionalAccessExpression: case SyntaxKind.DeclarationExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.DefaultLiteralExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.GenericName: case SyntaxKind.IdentifierName: case SyntaxKind.ImplicitArrayCreationExpression: case SyntaxKind.ImplicitStackAllocArrayCreationExpression: case SyntaxKind.ImplicitObjectCreationExpression: case SyntaxKind.InterpolatedStringExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.PointerMemberAccessExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PredefinedType: case SyntaxKind.RefExpression: case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.SuppressNullableWarningExpression: case SyntaxKind.ThisExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.TupleExpression: return Precedence.Primary; default: throw ExceptionUtilities.UnexpectedValue(op); } } private static bool IsExpectedPrefixUnaryOperator(SyntaxKind kind) { return SyntaxFacts.IsPrefixUnaryExpression(kind) && kind != SyntaxKind.RefKeyword && kind != SyntaxKind.OutKeyword; } private static bool IsExpectedBinaryOperator(SyntaxKind kind) { return SyntaxFacts.IsBinaryExpression(kind); } private static bool IsExpectedAssignmentOperator(SyntaxKind kind) { return SyntaxFacts.IsAssignmentExpressionOperatorToken(kind); } private bool IsPossibleAwaitExpressionStatement() { return (this.IsScript || this.IsInAsync) && this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword; } private bool IsAwaitExpression() { if (this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword) { if (this.IsInAsync) { // If we see an await in an async function, parse it as an unop. return true; } // If we see an await followed by a token that cannot follow an identifier, parse await as a unop. // BindAwait() catches the cases where await successfully parses as a unop but is not in an async // function, and reports an appropriate ERR_BadAwaitWithoutAsync* error. var next = PeekToken(1); switch (next.Kind) { case SyntaxKind.IdentifierToken: return next.ContextualKind != SyntaxKind.WithKeyword; // Keywords case SyntaxKind.NewKeyword: case SyntaxKind.ThisKeyword: case SyntaxKind.BaseKeyword: case SyntaxKind.DelegateKeyword: case SyntaxKind.TypeOfKeyword: case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: case SyntaxKind.DefaultKeyword: // Literals case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.StringLiteralToken: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringToken: case SyntaxKind.NumericLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.CharacterLiteralToken: return true; } } return false; } /// <summary> /// Parse a subexpression of the enclosing operator of the given precedence. /// </summary> private ExpressionSyntax ParseSubExpression(Precedence precedence) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); var result = ParseSubExpressionCore(precedence); #if DEBUG // Ensure every expression kind is handled in GetPrecedence _ = GetPrecedence(result.Kind); #endif _recursionDepth--; return result; } private ExpressionSyntax ParseSubExpressionCore(Precedence precedence) { ExpressionSyntax leftOperand; Precedence newPrecedence = 0; // all of these are tokens that start statements and are invalid // to start a expression with. if we see one, then we must have // something like: // // return // if (... // parse out a missing name node for the expression, and keep on going var tk = this.CurrentToken.Kind; if (IsInvalidSubExpression(tk)) { return this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); } // Parse a left operand -- possibly preceded by a unary operator. if (IsExpectedPrefixUnaryOperator(tk)) { var opKind = SyntaxFacts.GetPrefixUnaryExpression(tk); newPrecedence = GetPrecedence(opKind); var opToken = this.EatToken(); var operand = this.ParseSubExpression(newPrecedence); leftOperand = _syntaxFactory.PrefixUnaryExpression(opKind, opToken, operand); } else if (tk == SyntaxKind.DotDotToken) { // Operator ".." here can either be a prefix unary operator or a stand alone empty range: var opToken = this.EatToken(); newPrecedence = GetPrecedence(SyntaxKind.RangeExpression); ExpressionSyntax rightOperand; if (CanStartExpression()) { rightOperand = this.ParseSubExpression(newPrecedence); } else { rightOperand = null; } leftOperand = _syntaxFactory.RangeExpression(leftOperand: null, opToken, rightOperand); } else if (IsAwaitExpression()) { newPrecedence = GetPrecedence(SyntaxKind.AwaitExpression); var awaitToken = this.EatContextualToken(SyntaxKind.AwaitKeyword); awaitToken = CheckFeatureAvailability(awaitToken, MessageID.IDS_FeatureAsync); var operand = this.ParseSubExpression(newPrecedence); leftOperand = _syntaxFactory.AwaitExpression(awaitToken, operand); } else if (this.IsQueryExpression(mayBeVariableDeclaration: false, mayBeMemberDeclaration: false)) { leftOperand = this.ParseQueryExpression(precedence); } else if (this.CurrentToken.ContextualKind == SyntaxKind.FromKeyword && IsInQuery) { // If this "from" token wasn't the start of a query then it's not really an expression. // Consume it so that we don't try to parse it again as the next argument in an // argument list. SyntaxToken skipped = this.EatToken(); // consume but skip "from" skipped = this.AddError(skipped, ErrorCode.ERR_InvalidExprTerm, this.CurrentToken.Text); leftOperand = AddTrailingSkippedSyntax(this.CreateMissingIdentifierName(), skipped); } else if (tk == SyntaxKind.ThrowKeyword) { var result = ParseThrowExpression(); // we parse a throw expression even at the wrong precedence for better recovery return (precedence <= Precedence.Coalescing) ? result : this.AddError(result, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); } else if (this.IsPossibleDeconstructionLeft(precedence)) { leftOperand = ParseDeclarationExpression(ParseTypeMode.Normal, MessageID.IDS_FeatureTuples); } else { // Not a unary operator - get a primary expression. leftOperand = this.ParseTerm(precedence); } return ParseExpressionContinued(leftOperand, precedence); } private ExpressionSyntax ParseExpressionContinued(ExpressionSyntax leftOperand, Precedence precedence) { while (true) { // We either have a binary or assignment operator here, or we're finished. var tk = this.CurrentToken.ContextualKind; bool isAssignmentOperator = false; SyntaxKind opKind; if (IsExpectedBinaryOperator(tk)) { opKind = SyntaxFacts.GetBinaryExpression(tk); } else if (IsExpectedAssignmentOperator(tk)) { opKind = SyntaxFacts.GetAssignmentExpression(tk); isAssignmentOperator = true; } else if (tk == SyntaxKind.DotDotToken) { opKind = SyntaxKind.RangeExpression; } else if (tk == SyntaxKind.SwitchKeyword && this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken) { opKind = SyntaxKind.SwitchExpression; } else if (tk == SyntaxKind.WithKeyword && this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken) { opKind = SyntaxKind.WithExpression; } else { break; } var newPrecedence = GetPrecedence(opKind); // check for >> or >>= bool doubleOp = false; if (tk == SyntaxKind.GreaterThanToken && (this.PeekToken(1).Kind == SyntaxKind.GreaterThanToken || this.PeekToken(1).Kind == SyntaxKind.GreaterThanEqualsToken)) { // check to see if they really are adjacent if (this.CurrentToken.GetTrailingTriviaWidth() == 0 && this.PeekToken(1).GetLeadingTriviaWidth() == 0) { if (this.PeekToken(1).Kind == SyntaxKind.GreaterThanToken) { opKind = SyntaxFacts.GetBinaryExpression(SyntaxKind.GreaterThanGreaterThanToken); } else { opKind = SyntaxFacts.GetAssignmentExpression(SyntaxKind.GreaterThanGreaterThanEqualsToken); isAssignmentOperator = true; } newPrecedence = GetPrecedence(opKind); doubleOp = true; } } // Check the precedence to see if we should "take" this operator if (newPrecedence < precedence) { break; } // Same precedence, but not right-associative -- deal with this "later" if ((newPrecedence == precedence) && !IsRightAssociative(opKind)) { break; } // We'll "take" this operator, as precedence is tentatively OK. var opToken = this.EatContextualToken(tk); var leftPrecedence = GetPrecedence(leftOperand.Kind); if (newPrecedence > leftPrecedence) { // Normally, a left operand with a looser precedence will consume all right operands that // have a tighter precedence. For example, in the expression `a + b * c`, the `* c` part // will be consumed as part of the right operand of the addition. However, there are a // few circumstances in which a tighter precedence is not consumed: that occurs when the // left hand operator does not have an expression as its right operand. This occurs for // the is-type operator and the is-pattern operator. Source text such as // `a is {} + b` should produce a syntax error, as parsing the `+` with an `is` // expression as its left operand would be a precedence inversion. Similarly, it occurs // with an anonymous method expression or a lambda expression with a block body. No // further parsing will find a way to fix things up, so we accept the operator but issue // a diagnostic. ErrorCode errorCode = leftOperand.Kind == SyntaxKind.IsPatternExpression ? ErrorCode.ERR_UnexpectedToken : ErrorCode.WRN_PrecedenceInversion; opToken = this.AddError(opToken, errorCode, opToken.Text); } if (doubleOp) { // combine tokens into a single token var opToken2 = this.EatToken(); var kind = opToken2.Kind == SyntaxKind.GreaterThanToken ? SyntaxKind.GreaterThanGreaterThanToken : SyntaxKind.GreaterThanGreaterThanEqualsToken; opToken = SyntaxFactory.Token(opToken.GetLeadingTrivia(), kind, opToken2.GetTrailingTrivia()); } if (opKind == SyntaxKind.AsExpression) { var type = this.ParseType(ParseTypeMode.AsExpression); leftOperand = _syntaxFactory.BinaryExpression(opKind, leftOperand, opToken, type); } else if (opKind == SyntaxKind.IsExpression) { leftOperand = ParseIsExpression(leftOperand, opToken); } else if (isAssignmentOperator) { ExpressionSyntax rhs = opKind == SyntaxKind.SimpleAssignmentExpression && CurrentToken.Kind == SyntaxKind.RefKeyword ? rhs = CheckFeatureAvailability(ParsePossibleRefExpression(), MessageID.IDS_FeatureRefReassignment) : rhs = this.ParseSubExpression(newPrecedence); if (opKind == SyntaxKind.CoalesceAssignmentExpression) { opToken = CheckFeatureAvailability(opToken, MessageID.IDS_FeatureCoalesceAssignmentExpression); } leftOperand = _syntaxFactory.AssignmentExpression(opKind, leftOperand, opToken, rhs); } else if (opKind == SyntaxKind.SwitchExpression) { leftOperand = ParseSwitchExpression(leftOperand, opToken); } else if (opKind == SyntaxKind.WithExpression) { leftOperand = ParseWithExpression(leftOperand, opToken); } else if (tk == SyntaxKind.DotDotToken) { // Operator ".." here can either be a binary or a postfix unary operator: Debug.Assert(opKind == SyntaxKind.RangeExpression); ExpressionSyntax rightOperand; if (CanStartExpression()) { newPrecedence = GetPrecedence(opKind); rightOperand = this.ParseSubExpression(newPrecedence); } else { rightOperand = null; } leftOperand = _syntaxFactory.RangeExpression(leftOperand, opToken, rightOperand); } else { Debug.Assert(IsExpectedBinaryOperator(tk)); leftOperand = _syntaxFactory.BinaryExpression(opKind, leftOperand, opToken, this.ParseSubExpression(newPrecedence)); } } // From the language spec: // // conditional-expression: // null-coalescing-expression // null-coalescing-expression ? expression : expression // // Only take the conditional if we're at or below its precedence. if (CurrentToken.Kind == SyntaxKind.QuestionToken && precedence <= Precedence.Conditional) { var questionToken = this.EatToken(); var colonLeft = this.ParsePossibleRefExpression(); if (this.CurrentToken.Kind == SyntaxKind.EndOfFileToken && this.lexer.InterpolationFollowedByColon) { // We have an interpolated string with an interpolation that contains a conditional expression. // Unfortunately, the precedence demands that the colon is considered to signal the start of the // format string. Without this code, the compiler would complain about a missing colon, and point // to the colon that is present, which would be confusing. We aim to give a better error message. var colon = SyntaxFactory.MissingToken(SyntaxKind.ColonToken); var colonRight = _syntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); leftOperand = _syntaxFactory.ConditionalExpression(leftOperand, questionToken, colonLeft, colon, colonRight); leftOperand = this.AddError(leftOperand, ErrorCode.ERR_ConditionalInInterpolation); } else { var colon = this.EatToken(SyntaxKind.ColonToken); var colonRight = this.ParsePossibleRefExpression(); leftOperand = _syntaxFactory.ConditionalExpression(leftOperand, questionToken, colonLeft, colon, colonRight); } } return leftOperand; } private ExpressionSyntax ParseDeclarationExpression(ParseTypeMode mode, MessageID feature) { TypeSyntax type = this.ParseType(mode); var designation = ParseDesignation(forPattern: false); if (feature != MessageID.None) { designation = CheckFeatureAvailability(designation, feature); } return _syntaxFactory.DeclarationExpression(type, designation); } private ExpressionSyntax ParseThrowExpression() { var throwToken = this.EatToken(SyntaxKind.ThrowKeyword); var thrown = this.ParseSubExpression(Precedence.Coalescing); var result = _syntaxFactory.ThrowExpression(throwToken, thrown); return CheckFeatureAvailability(result, MessageID.IDS_FeatureThrowExpression); } private ExpressionSyntax ParseIsExpression(ExpressionSyntax leftOperand, SyntaxToken opToken) { var node = this.ParseTypeOrPatternForIsOperator(); switch (node) { case PatternSyntax pattern: var result = _syntaxFactory.IsPatternExpression(leftOperand, opToken, pattern); return CheckFeatureAvailability(result, MessageID.IDS_FeaturePatternMatching); case TypeSyntax type: return _syntaxFactory.BinaryExpression(SyntaxKind.IsExpression, leftOperand, opToken, type); default: throw ExceptionUtilities.UnexpectedValue(node); } } private ExpressionSyntax ParseTerm(Precedence precedence) => this.ParsePostFixExpression(ParseTermWithoutPostfix(precedence)); private ExpressionSyntax ParseTermWithoutPostfix(Precedence precedence) { var tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.TypeOfKeyword: return this.ParseTypeOfExpression(); case SyntaxKind.DefaultKeyword: return this.ParseDefaultExpression(); case SyntaxKind.SizeOfKeyword: return this.ParseSizeOfExpression(); case SyntaxKind.MakeRefKeyword: return this.ParseMakeRefExpression(); case SyntaxKind.RefTypeKeyword: return this.ParseRefTypeExpression(); case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: return this.ParseCheckedOrUncheckedExpression(); case SyntaxKind.RefValueKeyword: return this.ParseRefValueExpression(); case SyntaxKind.ColonColonToken: // misplaced :: // Calling ParseAliasQualifiedName will cause us to create a missing identifier node that then // properly consumes the :: and the reset of the alias name afterwards. return this.ParseAliasQualifiedName(NameOptions.InExpression); case SyntaxKind.EqualsGreaterThanToken: return this.ParseLambdaExpression(); case SyntaxKind.StaticKeyword: if (this.IsPossibleAnonymousMethodExpression()) { return this.ParseAnonymousMethodExpression(); } else if (this.IsPossibleLambdaExpression(precedence)) { return this.ParseLambdaExpression(); } else { return this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, this.CurrentToken.Text); } case SyntaxKind.IdentifierToken: if (this.IsTrueIdentifier()) { if (this.IsPossibleAnonymousMethodExpression()) { return this.ParseAnonymousMethodExpression(); } else if (this.IsPossibleLambdaExpression(precedence) && this.TryParseLambdaExpression() is { } lambda) { return lambda; } else if (this.IsPossibleDeconstructionLeft(precedence)) { return ParseDeclarationExpression(ParseTypeMode.Normal, MessageID.IDS_FeatureTuples); } else { return this.ParseAliasQualifiedName(NameOptions.InExpression); } } else { return this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, this.CurrentToken.Text); } case SyntaxKind.OpenBracketToken: if (!this.IsPossibleLambdaExpression(precedence)) { goto default; } return this.ParseLambdaExpression(); case SyntaxKind.ThisKeyword: return _syntaxFactory.ThisExpression(this.EatToken()); case SyntaxKind.BaseKeyword: return ParseBaseExpression(); case SyntaxKind.ArgListKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.NullKeyword: case SyntaxKind.NumericLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.CharacterLiteralToken: return _syntaxFactory.LiteralExpression(SyntaxFacts.GetLiteralExpression(tk), this.EatToken()); case SyntaxKind.InterpolatedStringStartToken: throw new NotImplementedException(); // this should not occur because these tokens are produced and parsed immediately case SyntaxKind.InterpolatedStringToken: return this.ParseInterpolatedStringToken(); case SyntaxKind.OpenParenToken: if (IsPossibleLambdaExpression(precedence)) { if (this.TryParseLambdaExpression() is { } lambda) { return lambda; } } return this.ParseCastOrParenExpressionOrTuple(); case SyntaxKind.NewKeyword: return this.ParseNewExpression(); case SyntaxKind.StackAllocKeyword: return this.ParseStackAllocExpression(); case SyntaxKind.DelegateKeyword: // check for lambda expression with explicit function pointer return type if (this.IsPossibleLambdaExpression(precedence)) { return this.ParseLambdaExpression(); } return this.ParseAnonymousMethodExpression(); case SyntaxKind.RefKeyword: // check for lambda expression with explicit ref return type: `ref int () => { ... }` if (this.IsPossibleLambdaExpression(precedence)) { return this.ParseLambdaExpression(); } // ref is not expected to appear in this position. return this.AddError(ParsePossibleRefExpression(), ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); default: if (IsPredefinedType(tk)) { if (this.IsPossibleLambdaExpression(precedence)) { return this.ParseLambdaExpression(); } // check for intrinsic type followed by '.' var expr = _syntaxFactory.PredefinedType(this.EatToken()); if (this.CurrentToken.Kind != SyntaxKind.DotToken || tk == SyntaxKind.VoidKeyword) { expr = this.AddError(expr, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); } return expr; } else { var expr = this.CreateMissingIdentifierName(); if (tk == SyntaxKind.EndOfFileToken) { expr = this.AddError(expr, ErrorCode.ERR_ExpressionExpected); } else { expr = this.AddError(expr, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); } return expr; } } } private ExpressionSyntax ParseBaseExpression() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.BaseKeyword); return _syntaxFactory.BaseExpression(this.EatToken()); } /// <summary> /// Returns true if... /// 1. The precedence is less than or equal to Assignment, and /// 2. The current token is the identifier var or a predefined type, and /// 3. it is followed by (, and /// 4. that ( begins a valid parenthesized designation, and /// 5. the token following that designation is = /// </summary> private bool IsPossibleDeconstructionLeft(Precedence precedence) { if (precedence > Precedence.Assignment || !(this.CurrentToken.IsIdentifierVar() || IsPredefinedType(this.CurrentToken.Kind))) { return false; } var resetPoint = this.GetResetPoint(); try { this.EatToken(); // `var` return this.CurrentToken.Kind == SyntaxKind.OpenParenToken && ScanDesignator() && this.CurrentToken.Kind == SyntaxKind.EqualsToken; } finally { // Restore current token index this.Reset(ref resetPoint); this.Release(ref resetPoint); } } private bool ScanDesignator() { switch (this.CurrentToken.Kind) { case SyntaxKind.IdentifierToken: if (!IsTrueIdentifier()) { goto default; } this.EatToken(); // eat the identifier return true; case SyntaxKind.OpenParenToken: while (true) { this.EatToken(); // eat the open paren or comma if (!ScanDesignator()) { return false; } switch (this.CurrentToken.Kind) { case SyntaxKind.CommaToken: continue; case SyntaxKind.CloseParenToken: this.EatToken(); // eat the close paren return true; default: return false; } } default: return false; } } private bool IsPossibleAnonymousMethodExpression() { // Skip past any static/async keywords. var tokenIndex = 0; while (this.PeekToken(tokenIndex).Kind == SyntaxKind.StaticKeyword || this.PeekToken(tokenIndex).ContextualKind == SyntaxKind.AsyncKeyword) { tokenIndex++; } return this.PeekToken(tokenIndex).Kind == SyntaxKind.DelegateKeyword && this.PeekToken(tokenIndex + 1).Kind != SyntaxKind.AsteriskToken; } private ExpressionSyntax ParsePostFixExpression(ExpressionSyntax expr) { Debug.Assert(expr != null); while (true) { SyntaxKind tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.OpenParenToken: expr = _syntaxFactory.InvocationExpression(expr, this.ParseParenthesizedArgumentList()); break; case SyntaxKind.OpenBracketToken: expr = _syntaxFactory.ElementAccessExpression(expr, this.ParseBracketedArgumentList()); break; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: expr = _syntaxFactory.PostfixUnaryExpression(SyntaxFacts.GetPostfixUnaryExpression(tk), expr, this.EatToken()); break; case SyntaxKind.ColonColonToken: if (this.PeekToken(1).Kind == SyntaxKind.IdentifierToken) { // replace :: with missing dot and annotate with skipped text "::" and error var ccToken = this.EatToken(); ccToken = this.AddError(ccToken, ErrorCode.ERR_UnexpectedAliasedName); var dotToken = this.ConvertToMissingWithTrailingTrivia(ccToken, SyntaxKind.DotToken); expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, dotToken, this.ParseSimpleName(NameOptions.InExpression)); } else { // just some random trailing :: ? expr = AddTrailingSkippedSyntax(expr, this.EatTokenWithPrejudice(SyntaxKind.DotToken)); } break; case SyntaxKind.MinusGreaterThanToken: expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.PointerMemberAccessExpression, expr, this.EatToken(), this.ParseSimpleName(NameOptions.InExpression)); break; case SyntaxKind.DotToken: // if we have the error situation: // // expr. // X Y // // Then we don't want to parse this out as "Expr.X" // // It's far more likely the member access expression is simply incomplete and // there is a new declaration on the next line. if (this.CurrentToken.TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia) && this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && this.PeekToken(2).ContextualKind == SyntaxKind.IdentifierToken) { expr = _syntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, expr, this.EatToken(), this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected)); return expr; } expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, this.EatToken(), this.ParseSimpleName(NameOptions.InExpression)); break; case SyntaxKind.QuestionToken: if (CanStartConsequenceExpression(this.PeekToken(1).Kind)) { var qToken = this.EatToken(); var consequence = ParseConsequenceSyntax(); expr = _syntaxFactory.ConditionalAccessExpression(expr, qToken, consequence); expr = CheckFeatureAvailability(expr, MessageID.IDS_FeatureNullPropagatingOperator); break; } goto default; case SyntaxKind.ExclamationToken: expr = _syntaxFactory.PostfixUnaryExpression(SyntaxFacts.GetPostfixUnaryExpression(tk), expr, this.EatToken()); expr = CheckFeatureAvailability(expr, MessageID.IDS_FeatureNullableReferenceTypes); break; default: return expr; } } } private static bool CanStartConsequenceExpression(SyntaxKind kind) { return kind == SyntaxKind.DotToken || kind == SyntaxKind.OpenBracketToken; } internal ExpressionSyntax ParseConsequenceSyntax() { SyntaxKind tk = this.CurrentToken.Kind; ExpressionSyntax expr = null; switch (tk) { case SyntaxKind.DotToken: expr = _syntaxFactory.MemberBindingExpression(this.EatToken(), this.ParseSimpleName(NameOptions.InExpression)); break; case SyntaxKind.OpenBracketToken: expr = _syntaxFactory.ElementBindingExpression(this.ParseBracketedArgumentList()); break; } Debug.Assert(expr != null); while (true) { tk = this.CurrentToken.Kind; // Nullable suppression operators should only be consumed by a conditional access // if there are further conditional operations performed after the suppression if (isOptionalExclamationsFollowedByConditionalOperation()) { while (tk == SyntaxKind.ExclamationToken) { expr = _syntaxFactory.PostfixUnaryExpression(SyntaxKind.SuppressNullableWarningExpression, expr, EatToken()); expr = CheckFeatureAvailability(expr, MessageID.IDS_FeatureNullableReferenceTypes); tk = this.CurrentToken.Kind; } } switch (tk) { case SyntaxKind.OpenParenToken: expr = _syntaxFactory.InvocationExpression(expr, this.ParseParenthesizedArgumentList()); break; case SyntaxKind.OpenBracketToken: expr = _syntaxFactory.ElementAccessExpression(expr, this.ParseBracketedArgumentList()); break; case SyntaxKind.DotToken: expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, this.EatToken(), this.ParseSimpleName(NameOptions.InExpression)); break; case SyntaxKind.QuestionToken: if (CanStartConsequenceExpression(this.PeekToken(1).Kind)) { var qToken = this.EatToken(); var consequence = ParseConsequenceSyntax(); expr = _syntaxFactory.ConditionalAccessExpression(expr, qToken, consequence); } return expr; default: return expr; } } bool isOptionalExclamationsFollowedByConditionalOperation() { var tk = this.CurrentToken.Kind; for (int i = 1; tk == SyntaxKind.ExclamationToken; i++) { tk = this.PeekToken(i).Kind; } return tk is SyntaxKind.OpenParenToken or SyntaxKind.OpenBracketToken or SyntaxKind.DotToken or SyntaxKind.QuestionToken; } } internal ArgumentListSyntax ParseParenthesizedArgumentList() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.ArgumentList) { return (ArgumentListSyntax)this.EatNode(); } ParseArgumentList( openToken: out SyntaxToken openToken, arguments: out SeparatedSyntaxList<ArgumentSyntax> arguments, closeToken: out SyntaxToken closeToken, openKind: SyntaxKind.OpenParenToken, closeKind: SyntaxKind.CloseParenToken); return _syntaxFactory.ArgumentList(openToken, arguments, closeToken); } internal BracketedArgumentListSyntax ParseBracketedArgumentList() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.BracketedArgumentList) { return (BracketedArgumentListSyntax)this.EatNode(); } ParseArgumentList( openToken: out SyntaxToken openToken, arguments: out SeparatedSyntaxList<ArgumentSyntax> arguments, closeToken: out SyntaxToken closeToken, openKind: SyntaxKind.OpenBracketToken, closeKind: SyntaxKind.CloseBracketToken); return _syntaxFactory.BracketedArgumentList(openToken, arguments, closeToken); } private void ParseArgumentList( out SyntaxToken openToken, out SeparatedSyntaxList<ArgumentSyntax> arguments, out SyntaxToken closeToken, SyntaxKind openKind, SyntaxKind closeKind) { Debug.Assert(openKind == SyntaxKind.OpenParenToken || openKind == SyntaxKind.OpenBracketToken); Debug.Assert(closeKind == SyntaxKind.CloseParenToken || closeKind == SyntaxKind.CloseBracketToken); Debug.Assert((openKind == SyntaxKind.OpenParenToken) == (closeKind == SyntaxKind.CloseParenToken)); bool isIndexer = openKind == SyntaxKind.OpenBracketToken; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBracketToken) { // convert `[` into `(` or vice versa for error recovery openToken = this.EatTokenAsKind(openKind); } else { openToken = this.EatToken(openKind); } var saveTerm = _termState; _termState |= TerminatorState.IsEndOfArgumentList; SeparatedSyntaxListBuilder<ArgumentSyntax> list = default(SeparatedSyntaxListBuilder<ArgumentSyntax>); try { if (this.CurrentToken.Kind != closeKind && this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { tryAgain: if (list.IsNull) { list = _pool.AllocateSeparated<ArgumentSyntax>(); } if (this.IsPossibleArgumentExpression() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument list.Add(this.ParseArgumentExpression(isIndexer)); // additional arguments var lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.CloseBracketToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleArgumentExpression()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); list.Add(this.ParseArgumentExpression(isIndexer)); continue; } else if (this.SkipBadArgumentListTokens(ref openToken, list, SyntaxKind.CommaToken, closeKind) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadArgumentListTokens(ref openToken, list, SyntaxKind.IdentifierToken, closeKind) == PostSkipAction.Continue) { goto tryAgain; } } else if (isIndexer && this.CurrentToken.Kind == closeKind) { // An indexer always expects at least one value. And so we need to give an error // for the case where we see only "[]". ParseArgumentExpression gives it. if (list.IsNull) { list = _pool.AllocateSeparated<ArgumentSyntax>(); } list.Add(this.ParseArgumentExpression(isIndexer)); } _termState = saveTerm; if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.CloseBracketToken) { // convert `]` into `)` or vice versa for error recovery closeToken = this.EatTokenAsKind(closeKind); } else { closeToken = this.EatToken(closeKind); } arguments = list.ToList(); } finally { if (!list.IsNull) { _pool.Free(list); } } } private PostSkipAction SkipBadArgumentListTokens(ref SyntaxToken open, SeparatedSyntaxListBuilder<ArgumentSyntax> list, SyntaxKind expected, SyntaxKind closeKind) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref open, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleArgumentExpression(), p => p.CurrentToken.Kind == closeKind || p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsTerminator(), expected); } private bool IsEndOfArgumentList() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.CloseBracketToken; } private bool IsPossibleArgumentExpression() { return IsValidArgumentRefKindKeyword(this.CurrentToken.Kind) || this.IsPossibleExpression(); } private static bool IsValidArgumentRefKindKeyword(SyntaxKind kind) { switch (kind) { case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: return true; default: return false; } } private ArgumentSyntax ParseArgumentExpression(bool isIndexer) { NameColonSyntax nameColon = null; if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.ColonToken) { var name = this.ParseIdentifierName(); var colon = this.EatToken(SyntaxKind.ColonToken); nameColon = _syntaxFactory.NameColon(name, colon); nameColon = CheckFeatureAvailability(nameColon, MessageID.IDS_FeatureNamedArgument); } SyntaxToken refKindKeyword = null; if (IsValidArgumentRefKindKeyword(this.CurrentToken.Kind)) { refKindKeyword = this.EatToken(); } ExpressionSyntax expression; if (isIndexer && (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.CloseBracketToken)) { expression = this.ParseIdentifierName(ErrorCode.ERR_ValueExpected); } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { expression = this.ParseIdentifierName(ErrorCode.ERR_MissingArgument); } else { if (refKindKeyword?.Kind == SyntaxKind.InKeyword) { refKindKeyword = this.CheckFeatureAvailability(refKindKeyword, MessageID.IDS_FeatureReadOnlyReferences); } // According to Language Specification, section 7.6.7 Element access // The argument-list of an element-access is not allowed to contain ref or out arguments. // However, we actually do support ref indexing of indexed properties in COM interop // scenarios, and when indexing an object of static type "dynamic". So we enforce // that the ref/out of the argument must match the parameter when binding the argument list. expression = (refKindKeyword?.Kind == SyntaxKind.OutKeyword) ? ParseExpressionOrDeclaration(ParseTypeMode.Normal, feature: MessageID.IDS_FeatureOutVar, permitTupleDesignation: false) : ParseSubExpression(Precedence.Expression); } return _syntaxFactory.Argument(nameColon, refKindKeyword, expression); } private TypeOfExpressionSyntax ParseTypeOfExpression() { var keyword = this.EatToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var type = this.ParseTypeOrVoid(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.TypeOfExpression(keyword, openParen, type, closeParen); } private ExpressionSyntax ParseDefaultExpression() { var keyword = this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var openParen = this.EatToken(SyntaxKind.OpenParenToken); var type = this.ParseType(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); keyword = CheckFeatureAvailability(keyword, MessageID.IDS_FeatureDefault); return _syntaxFactory.DefaultExpression(keyword, openParen, type, closeParen); } else { keyword = CheckFeatureAvailability(keyword, MessageID.IDS_FeatureDefaultLiteral); return _syntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression, keyword); } } private SizeOfExpressionSyntax ParseSizeOfExpression() { var keyword = this.EatToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var type = this.ParseType(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.SizeOfExpression(keyword, openParen, type, closeParen); } private MakeRefExpressionSyntax ParseMakeRefExpression() { var keyword = this.EatToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expr = this.ParseSubExpression(Precedence.Expression); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.MakeRefExpression(keyword, openParen, expr, closeParen); } private RefTypeExpressionSyntax ParseRefTypeExpression() { var keyword = this.EatToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expr = this.ParseSubExpression(Precedence.Expression); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.RefTypeExpression(keyword, openParen, expr, closeParen); } private CheckedExpressionSyntax ParseCheckedOrUncheckedExpression() { var checkedOrUnchecked = this.EatToken(); Debug.Assert(checkedOrUnchecked.Kind == SyntaxKind.CheckedKeyword || checkedOrUnchecked.Kind == SyntaxKind.UncheckedKeyword); var kind = (checkedOrUnchecked.Kind == SyntaxKind.CheckedKeyword) ? SyntaxKind.CheckedExpression : SyntaxKind.UncheckedExpression; var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expr = this.ParseSubExpression(Precedence.Expression); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.CheckedExpression(kind, checkedOrUnchecked, openParen, expr, closeParen); } private RefValueExpressionSyntax ParseRefValueExpression() { var @refvalue = this.EatToken(SyntaxKind.RefValueKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expr = this.ParseSubExpression(Precedence.Expression); var comma = this.EatToken(SyntaxKind.CommaToken); var type = this.ParseType(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.RefValueExpression(@refvalue, openParen, expr, comma, type, closeParen); } private bool ScanParenthesizedLambda(Precedence precedence) { return ScanParenthesizedImplicitlyTypedLambda(precedence) || ScanExplicitlyTypedLambda(precedence); } private bool ScanParenthesizedImplicitlyTypedLambda(Precedence precedence) { Debug.Assert(CurrentToken.Kind == SyntaxKind.OpenParenToken); if (!(precedence <= Precedence.Lambda)) { return false; } // case 1: ( x , if (this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && (!this.IsInQuery || !IsTokenQueryContextualKeyword(this.PeekToken(1))) && this.PeekToken(2).Kind == SyntaxKind.CommaToken) { // Make sure it really looks like a lambda, not just a tuple int curTk = 3; while (true) { var tk = this.PeekToken(curTk++); // skip identifiers commas and predefined types in any combination for error recovery if (tk.Kind != SyntaxKind.IdentifierToken && !SyntaxFacts.IsPredefinedType(tk.Kind) && tk.Kind != SyntaxKind.CommaToken && (this.IsInQuery || !IsTokenQueryContextualKeyword(tk))) { break; }; } // ) => return this.PeekToken(curTk - 1).Kind == SyntaxKind.CloseParenToken && this.PeekToken(curTk).Kind == SyntaxKind.EqualsGreaterThanToken; } // case 2: ( x ) => if (IsTrueIdentifier(this.PeekToken(1)) && this.PeekToken(2).Kind == SyntaxKind.CloseParenToken && this.PeekToken(3).Kind == SyntaxKind.EqualsGreaterThanToken) { return true; } // case 3: ( ) => if (this.PeekToken(1).Kind == SyntaxKind.CloseParenToken && this.PeekToken(2).Kind == SyntaxKind.EqualsGreaterThanToken) { return true; } // case 4: ( params // This case is interesting in that it is not legal; this error could be caught at parse time but we would rather // recover from the error and let the semantic analyzer deal with it. if (this.PeekToken(1).Kind == SyntaxKind.ParamsKeyword) { return true; } return false; } private bool ScanExplicitlyTypedLambda(Precedence precedence) { Debug.Assert(CurrentToken.Kind == SyntaxKind.OpenParenToken); if (!(precedence <= Precedence.Lambda)) { return false; } var resetPoint = this.GetResetPoint(); try { // Do we have the following, where the attributes, modifier, and type are // optional? If so then parse it as a lambda. // (attributes modifier T x [, ...]) => // // It's not sufficient to assume this is a lambda expression if we see a // modifier such as `(ref x,` because the caller of this method may have // scanned past a preceding identifier, and `F (ref x,` might be a call to // method F rather than a lambda expression with return type F. // Instead, we need to scan to `=>`. while (true) { // Advance past the open paren or comma. this.EatToken(); _ = ParseAttributeDeclarations(); // Eat 'out', 'ref', and 'in'. Even though not allowed in a lambda, // we treat `params` similarly for better error recovery. switch (this.CurrentToken.Kind) { case SyntaxKind.RefKeyword: this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword) { this.EatToken(); } break; case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: case SyntaxKind.ParamsKeyword: this.EatToken(); break; } // NOTE: advances CurrentToken if (this.ScanType() == ScanTypeFlags.NotType) { return false; } if (this.IsTrueIdentifier()) { // eat the identifier this.EatToken(); } switch (this.CurrentToken.Kind) { case SyntaxKind.CommaToken: continue; case SyntaxKind.CloseParenToken: return this.PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken; default: return false; } } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } private ExpressionSyntax ParseCastOrParenExpressionOrTuple() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.OpenParenToken); var resetPoint = this.GetResetPoint(); try { // We have a decision to make -- is this a cast, or is it a parenthesized // expression? Because look-ahead is cheap with our token stream, we check // to see if this "looks like" a cast (without constructing any parse trees) // to help us make the decision. if (this.ScanCast()) { if (!IsCurrentTokenQueryKeywordInQuery()) { // Looks like a cast, so parse it as one. this.Reset(ref resetPoint); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var type = this.ParseType(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var expr = this.ParseSubExpression(Precedence.Cast); return _syntaxFactory.CastExpression(openParen, type, closeParen, expr); } } // Doesn't look like a cast, so parse this as a parenthesized expression or tuple. { this.Reset(ref resetPoint); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expression = this.ParseExpressionOrDeclaration(ParseTypeMode.FirstElementOfPossibleTupleLiteral, feature: 0, permitTupleDesignation: true); // ( <expr>, must be a tuple if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { var firstArg = _syntaxFactory.Argument(nameColon: null, refKindKeyword: null, expression: expression); return ParseTupleExpressionTail(openParen, firstArg); } // ( name: if (expression.Kind == SyntaxKind.IdentifierName && this.CurrentToken.Kind == SyntaxKind.ColonToken) { var nameColon = _syntaxFactory.NameColon((IdentifierNameSyntax)expression, EatToken()); expression = this.ParseExpressionOrDeclaration(ParseTypeMode.FirstElementOfPossibleTupleLiteral, feature: 0, permitTupleDesignation: true); var firstArg = _syntaxFactory.Argument(nameColon, refKindKeyword: null, expression: expression); return ParseTupleExpressionTail(openParen, firstArg); } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.ParenthesizedExpression(openParen, expression, closeParen); } } finally { this.Release(ref resetPoint); } } private TupleExpressionSyntax ParseTupleExpressionTail(SyntaxToken openParen, ArgumentSyntax firstArg) { var list = _pool.AllocateSeparated<ArgumentSyntax>(); try { list.Add(firstArg); while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { var comma = this.EatToken(SyntaxKind.CommaToken); list.AddSeparator(comma); ArgumentSyntax arg; var expression = ParseExpressionOrDeclaration(ParseTypeMode.AfterTupleComma, feature: 0, permitTupleDesignation: true); if (expression.Kind == SyntaxKind.IdentifierName && this.CurrentToken.Kind == SyntaxKind.ColonToken) { var nameColon = _syntaxFactory.NameColon((IdentifierNameSyntax)expression, EatToken()); expression = ParseExpressionOrDeclaration(ParseTypeMode.AfterTupleComma, feature: 0, permitTupleDesignation: true); arg = _syntaxFactory.Argument(nameColon, refKindKeyword: null, expression: expression); } else { arg = _syntaxFactory.Argument(nameColon: null, refKindKeyword: null, expression: expression); } list.Add(arg); } if (list.Count < 2) { list.AddSeparator(SyntaxFactory.MissingToken(SyntaxKind.CommaToken)); var missing = this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_TupleTooFewElements); list.Add(_syntaxFactory.Argument(nameColon: null, refKindKeyword: null, expression: missing)); } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var result = _syntaxFactory.TupleExpression(openParen, list, closeParen); result = CheckFeatureAvailability(result, MessageID.IDS_FeatureTuples); return result; } finally { _pool.Free(list); } } private bool ScanCast(bool forPattern = false) { if (this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { return false; } this.EatToken(); var type = this.ScanType(forPattern: forPattern); if (type == ScanTypeFlags.NotType) { return false; } if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { return false; } this.EatToken(); if (forPattern && this.CurrentToken.Kind == SyntaxKind.IdentifierToken) { // In a pattern, an identifier can follow a cast unless it's a binary pattern token. return !isBinaryPattern(); } switch (type) { // If we have any of the following, we know it must be a cast: // 1) (Goo*)bar; // 2) (Goo?)bar; // 3) "(int)bar" or "(int[])bar" // 4) (G::Goo)bar case ScanTypeFlags.PointerOrMultiplication: case ScanTypeFlags.NullableType: case ScanTypeFlags.MustBeType: case ScanTypeFlags.AliasQualifiedName: // The thing between parens is unambiguously a type. // In a pattern, we need more lookahead to confirm it is a cast and not // a parenthesized type pattern. In this case the tokens that // have both unary and binary operator forms may appear in their unary form // following a cast. return !forPattern || this.CurrentToken.Kind switch { SyntaxKind.PlusToken or SyntaxKind.MinusToken or SyntaxKind.AmpersandToken or SyntaxKind.AsteriskToken or SyntaxKind.DotDotToken => true, var tk => CanFollowCast(tk) }; case ScanTypeFlags.GenericTypeOrMethod: case ScanTypeFlags.GenericTypeOrExpression: case ScanTypeFlags.NonGenericTypeOrExpression: case ScanTypeFlags.TupleType: // check for ambiguous type or expression followed by disambiguating token. i.e. // // "(A)b" is a cast. But "(A)+b" is not a cast. return CanFollowCast(this.CurrentToken.Kind); default: throw ExceptionUtilities.UnexpectedValue(type); } bool isBinaryPattern() { if (!isBinaryPatternKeyword()) { return false; } bool lastTokenIsBinaryOperator = true; EatToken(); while (isBinaryPatternKeyword()) { // If we see a subsequent binary pattern token, it can't be an operator. // Later, it will be parsed as an identifier. lastTokenIsBinaryOperator = !lastTokenIsBinaryOperator; EatToken(); } // In case a combinator token is used as a constant, we explicitly check that a pattern is NOT followed. // Such as `(e is (int)or or >= 0)` versus `(e is (int) or or)` return lastTokenIsBinaryOperator == IsPossibleSubpatternElement(); } bool isBinaryPatternKeyword() { return this.CurrentToken.ContextualKind is SyntaxKind.OrKeyword or SyntaxKind.AndKeyword; } } /// <summary> /// Tokens that match the following are considered a possible lambda expression: /// <code>attribute-list* ('async' | 'static')* type? ('(' | identifier) ...</code> /// For better error recovery 'static =>' is also considered a possible lambda expression. /// </summary> private bool IsPossibleLambdaExpression(Precedence precedence) { if (precedence > Precedence.Lambda) { return false; } var resetPoint = this.GetResetPoint(); try { if (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { _ = ParseAttributeDeclarations(); } bool seenStatic; if (this.CurrentToken.Kind == SyntaxKind.StaticKeyword) { EatToken(); seenStatic = true; } else if (this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword && this.PeekToken(1).Kind == SyntaxKind.StaticKeyword) { EatToken(); EatToken(); seenStatic = true; } else { seenStatic = false; } if (seenStatic) { if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) { // 1. `static =>` // 2. `async static =>` // This is an error case, but we have enough code in front of us to be certain // the user was trying to write a static lambda. return true; } if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { // 1. `static (... // 2. `async static (... return true; } } if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken) { // 1. `a => ...` // 1. `static a => ...` // 2. `async static a => ...` return true; } // Have checked all the static forms. And have checked for the basic `a => a` form. // At this point we have must be on 'async' or an explicit return type for this to still be a lambda. if (this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword && IsAnonymousFunctionAsyncModifier()) { EatToken(); } var nestedResetPoint = this.GetResetPoint(); try { var st = ScanType(); if (st == ScanTypeFlags.NotType || this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { this.Reset(ref nestedResetPoint); } } finally { this.Release(ref nestedResetPoint); } // However, just because we're on `async` doesn't mean we're a lambda. We might have // something lambda-like like: // // async a => ... // or // async (a) => ... // // Or we could have something that isn't a lambda like: // // async (); // 'async <identifier> => ...' looks like an async simple lambda if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken) { // async a => ... return true; } // Non-simple async lambda must be of the form 'async (...' if (this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { return false; } // Check whether looks like implicitly or explicitly typed lambda return ScanParenthesizedLambda(precedence); } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } private static bool CanFollowCast(SyntaxKind kind) { switch (kind) { case SyntaxKind.AsKeyword: case SyntaxKind.IsKeyword: case SyntaxKind.SemicolonToken: case SyntaxKind.CloseParenToken: case SyntaxKind.CloseBracketToken: case SyntaxKind.OpenBraceToken: case SyntaxKind.CloseBraceToken: case SyntaxKind.CommaToken: case SyntaxKind.EqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.QuestionToken: case SyntaxKind.ColonToken: case SyntaxKind.BarBarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.BarToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.LessThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: case SyntaxKind.AsteriskToken: case SyntaxKind.SlashToken: case SyntaxKind.PercentToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.DotToken: case SyntaxKind.MinusGreaterThanToken: case SyntaxKind.QuestionQuestionToken: case SyntaxKind.EndOfFileToken: case SyntaxKind.SwitchKeyword: case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.DotDotToken: return false; default: return true; } } private ExpressionSyntax ParseNewExpression() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NewKeyword); if (this.IsAnonymousType()) { return this.ParseAnonymousTypeExpression(); } else if (this.IsImplicitlyTypedArray()) { return this.ParseImplicitlyTypedArrayCreation(); } else { // assume object creation as default case return this.ParseArrayOrObjectCreationExpression(); } } private bool IsAnonymousType() { return this.CurrentToken.Kind == SyntaxKind.NewKeyword && this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken; } private AnonymousObjectCreationExpressionSyntax ParseAnonymousTypeExpression() { Debug.Assert(IsAnonymousType()); var @new = this.EatToken(SyntaxKind.NewKeyword); @new = CheckFeatureAvailability(@new, MessageID.IDS_FeatureAnonymousTypes); Debug.Assert(this.CurrentToken.Kind == SyntaxKind.OpenBraceToken); var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var expressions = _pool.AllocateSeparated<AnonymousObjectMemberDeclaratorSyntax>(); this.ParseAnonymousTypeMemberInitializers(ref openBrace, ref expressions); var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); var result = _syntaxFactory.AnonymousObjectCreationExpression(@new, openBrace, expressions, closeBrace); _pool.Free(expressions); return result; } private void ParseAnonymousTypeMemberInitializers(ref SyntaxToken openBrace, ref SeparatedSyntaxListBuilder<AnonymousObjectMemberDeclaratorSyntax> list) { if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsPossibleExpression() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument list.Add(this.ParseAnonymousTypeMemberInitializer()); // additional arguments int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleExpression()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); // check for exit case after legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (!this.IsPossibleExpression()) { goto tryAgain; } list.Add(this.ParseAnonymousTypeMemberInitializer()); continue; } else if (this.SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } } private AnonymousObjectMemberDeclaratorSyntax ParseAnonymousTypeMemberInitializer() { var nameEquals = this.IsNamedAssignment() ? ParseNameEquals() : null; var expression = this.ParseExpressionCore(); return _syntaxFactory.AnonymousObjectMemberDeclarator(nameEquals, expression); } private bool IsInitializerMember() { return this.IsComplexElementInitializer() || this.IsNamedAssignment() || this.IsDictionaryInitializer() || this.IsPossibleExpression(); } private bool IsComplexElementInitializer() { return this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; } private bool IsNamedAssignment() { return IsTrueIdentifier() && this.PeekToken(1).Kind == SyntaxKind.EqualsToken; } private bool IsDictionaryInitializer() { return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken; } private ExpressionSyntax ParseArrayOrObjectCreationExpression() { SyntaxToken @new = this.EatToken(SyntaxKind.NewKeyword); TypeSyntax type = null; InitializerExpressionSyntax initializer = null; if (IsImplicitObjectCreation()) { @new = CheckFeatureAvailability(@new, MessageID.IDS_FeatureImplicitObjectCreation); } else { type = this.ParseType(ParseTypeMode.NewExpression); if (type.Kind == SyntaxKind.ArrayType) { // Check for an initializer. if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { initializer = this.ParseArrayInitializer(); } return _syntaxFactory.ArrayCreationExpression(@new, (ArrayTypeSyntax)type, initializer); } } ArgumentListSyntax argumentList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { argumentList = this.ParseParenthesizedArgumentList(); } if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { initializer = this.ParseObjectOrCollectionInitializer(); } // we need one or the other. also, don't bother reporting this if we already complained about the new type. if (argumentList == null && initializer == null) { argumentList = _syntaxFactory.ArgumentList( this.EatToken(SyntaxKind.OpenParenToken, ErrorCode.ERR_BadNewExpr, reportError: type?.ContainsDiagnostics == false), default(SeparatedSyntaxList<ArgumentSyntax>), SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken)); } return type is null ? (ExpressionSyntax)_syntaxFactory.ImplicitObjectCreationExpression(@new, argumentList, initializer) : (ExpressionSyntax)_syntaxFactory.ObjectCreationExpression(@new, type, argumentList, initializer); } private bool IsImplicitObjectCreation() { // The caller is expected to have consumed the new keyword. if (this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { return false; } var point = this.GetResetPoint(); try { this.EatToken(); // open paren ScanTypeFlags scanTypeFlags = ScanTupleType(out _); if (scanTypeFlags != ScanTypeFlags.NotType) { switch (this.CurrentToken.Kind) { case SyntaxKind.QuestionToken: // e.g. `new(a, b)?()` case SyntaxKind.OpenBracketToken: // e.g. `new(a, b)[]` case SyntaxKind.OpenParenToken: // e.g. `new(a, b)()` for better error recovery return false; } } return true; } finally { this.Reset(ref point); this.Release(ref point); } } #nullable enable private ExpressionSyntax ParseWithExpression(ExpressionSyntax receiverExpression, SyntaxToken withKeyword) { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var list = _pool.AllocateSeparated<ExpressionSyntax>(); if (CurrentToken.Kind != SyntaxKind.CloseBraceToken) { bool foundStart = true; // Skip bad starting tokens until we find a valid start, if possible while (!IsPossibleExpression() && CurrentToken.Kind != SyntaxKind.CommaToken) { if (SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.IdentifierToken) == PostSkipAction.Abort) { foundStart = false; break; } } if (foundStart) { // First list.Add(ParseExpressionCore()); // Rest int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (IsPossibleExpression() || CurrentToken.Kind == SyntaxKind.CommaToken) { list.AddSeparator(EatToken(SyntaxKind.CommaToken)); // check for exit case after legal trailing comma if (CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } list.Add(ParseExpressionCore()); } else if (SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); var initializer = _syntaxFactory.InitializerExpression( SyntaxKind.WithInitializerExpression, openBrace, _pool.ToListAndFree(list), closeBrace); withKeyword = CheckFeatureAvailability(withKeyword, MessageID.IDS_FeatureRecords); var result = _syntaxFactory.WithExpression( receiverExpression, withKeyword, initializer); return result; } #nullable disable private InitializerExpressionSyntax ParseObjectOrCollectionInitializer() { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var initializers = _pool.AllocateSeparated<ExpressionSyntax>(); try { bool isObjectInitializer; this.ParseObjectOrCollectionInitializerMembers(ref openBrace, initializers, out isObjectInitializer); Debug.Assert(initializers.Count > 0 || isObjectInitializer); openBrace = CheckFeatureAvailability(openBrace, isObjectInitializer ? MessageID.IDS_FeatureObjectInitializer : MessageID.IDS_FeatureCollectionInitializer); var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); return _syntaxFactory.InitializerExpression( isObjectInitializer ? SyntaxKind.ObjectInitializerExpression : SyntaxKind.CollectionInitializerExpression, openBrace, initializers, closeBrace); } finally { _pool.Free(initializers); } } private void ParseObjectOrCollectionInitializerMembers(ref SyntaxToken startToken, SeparatedSyntaxListBuilder<ExpressionSyntax> list, out bool isObjectInitializer) { // Empty initializer list must be parsed as an object initializer. isObjectInitializer = true; if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsInitializerMember() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // We have at least one initializer expression. // If at least one initializer expression is a named assignment, this is an object initializer. // Otherwise, this is a collection initializer. isObjectInitializer = false; // first argument list.Add(this.ParseObjectOrCollectionInitializerMember(ref isObjectInitializer)); // additional arguments int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsInitializerMember()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); // check for exit case after legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } list.Add(this.ParseObjectOrCollectionInitializerMember(ref isObjectInitializer)); continue; } else if (this.SkipBadInitializerListTokens(ref startToken, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadInitializerListTokens(ref startToken, list, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } // We may have invalid initializer elements. These will be reported during binding. } private ExpressionSyntax ParseObjectOrCollectionInitializerMember(ref bool isObjectInitializer) { if (this.IsComplexElementInitializer()) { return this.ParseComplexElementInitializer(); } else if (IsDictionaryInitializer()) { isObjectInitializer = true; var initializer = this.ParseDictionaryInitializer(); initializer = CheckFeatureAvailability(initializer, MessageID.IDS_FeatureDictionaryInitializer); return initializer; } else if (this.IsNamedAssignment()) { isObjectInitializer = true; return this.ParseObjectInitializerNamedAssignment(); } else { return this.ParseExpressionCore(); } } private PostSkipAction SkipBadInitializerListTokens<T>(ref SyntaxToken startToken, SeparatedSyntaxListBuilder<T> list, SyntaxKind expected) where T : CSharpSyntaxNode { return this.SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), p => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken || p.IsTerminator(), expected); } private ExpressionSyntax ParseObjectInitializerNamedAssignment() { var identifier = this.ParseIdentifierName(); var equal = this.EatToken(SyntaxKind.EqualsToken); ExpressionSyntax expression; if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { expression = this.ParseObjectOrCollectionInitializer(); } else { expression = this.ParseExpressionCore(); } return _syntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, identifier, equal, expression); } private ExpressionSyntax ParseDictionaryInitializer() { var arguments = this.ParseBracketedArgumentList(); var equal = this.EatToken(SyntaxKind.EqualsToken); var expression = this.CurrentToken.Kind == SyntaxKind.OpenBraceToken ? this.ParseObjectOrCollectionInitializer() : this.ParseExpressionCore(); var elementAccess = _syntaxFactory.ImplicitElementAccess(arguments); return _syntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, elementAccess, equal, expression); } private InitializerExpressionSyntax ParseComplexElementInitializer() { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var initializers = _pool.AllocateSeparated<ExpressionSyntax>(); try { DiagnosticInfo closeBraceError; this.ParseExpressionsForComplexElementInitializer(ref openBrace, initializers, out closeBraceError); var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); if (closeBraceError != null) { closeBrace = WithAdditionalDiagnostics(closeBrace, closeBraceError); } return _syntaxFactory.InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, openBrace, initializers, closeBrace); } finally { _pool.Free(initializers); } } private void ParseExpressionsForComplexElementInitializer(ref SyntaxToken openBrace, SeparatedSyntaxListBuilder<ExpressionSyntax> list, out DiagnosticInfo closeBraceError) { closeBraceError = null; if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsPossibleExpression() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument list.Add(this.ParseExpressionCore()); // additional arguments int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleExpression()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { closeBraceError = MakeError(this.CurrentToken, ErrorCode.ERR_ExpressionExpected); break; } list.Add(this.ParseExpressionCore()); continue; } else if (this.SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } } private bool IsImplicitlyTypedArray() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NewKeyword || this.CurrentToken.Kind == SyntaxKind.StackAllocKeyword); return this.PeekToken(1).Kind == SyntaxKind.OpenBracketToken; } private ImplicitArrayCreationExpressionSyntax ParseImplicitlyTypedArrayCreation() { var @new = this.EatToken(SyntaxKind.NewKeyword); @new = CheckFeatureAvailability(@new, MessageID.IDS_FeatureImplicitArray); var openBracket = this.EatToken(SyntaxKind.OpenBracketToken); var commas = _pool.Allocate(); try { int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.IsPossibleExpression()) { var size = this.AddError(this.ParseExpressionCore(), ErrorCode.ERR_InvalidArray); if (commas.Count == 0) { openBracket = AddTrailingSkippedSyntax(openBracket, size); } else { AddTrailingSkippedSyntax(commas, size); } } if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { commas.Add(this.EatToken()); continue; } break; } var closeBracket = this.EatToken(SyntaxKind.CloseBracketToken); var initializer = this.ParseArrayInitializer(); return _syntaxFactory.ImplicitArrayCreationExpression(@new, openBracket, commas.ToList(), closeBracket, initializer); } finally { _pool.Free(commas); } } private InitializerExpressionSyntax ParseArrayInitializer() { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); // NOTE: This loop allows " { <initexpr>, } " but not " { , } " var list = _pool.AllocateSeparated<ExpressionSyntax>(); try { if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsPossibleVariableInitializer() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { list.Add(this.ParseVariableInitializer()); int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.IsPossibleVariableInitializer() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); // check for exit case after legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (!this.IsPossibleVariableInitializer()) { goto tryAgain; } list.Add(this.ParseVariableInitializer()); continue; } else if (SkipBadArrayInitializerTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (SkipBadArrayInitializerTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Continue) { goto tryAgain; } } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); return _syntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, openBrace, list, closeBrace); } finally { _pool.Free(list); } } private PostSkipAction SkipBadArrayInitializerTokens(ref SyntaxToken openBrace, SeparatedSyntaxListBuilder<ExpressionSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openBrace, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleVariableInitializer(), p => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken || p.IsTerminator(), expected); } private ExpressionSyntax ParseStackAllocExpression() { if (this.IsImplicitlyTypedArray()) { return ParseImplicitlyTypedStackAllocExpression(); } else { return ParseRegularStackAllocExpression(); } } private ExpressionSyntax ParseImplicitlyTypedStackAllocExpression() { var @stackalloc = this.EatToken(SyntaxKind.StackAllocKeyword); @stackalloc = CheckFeatureAvailability(@stackalloc, MessageID.IDS_FeatureStackAllocInitializer); var openBracket = this.EatToken(SyntaxKind.OpenBracketToken); int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.IsPossibleExpression()) { var size = this.AddError(this.ParseExpressionCore(), ErrorCode.ERR_InvalidStackAllocArray); openBracket = AddTrailingSkippedSyntax(openBracket, size); } if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { var comma = this.AddError(this.EatToken(), ErrorCode.ERR_InvalidStackAllocArray); openBracket = AddTrailingSkippedSyntax(openBracket, comma); continue; } break; } var closeBracket = this.EatToken(SyntaxKind.CloseBracketToken); var initializer = this.ParseArrayInitializer(); return _syntaxFactory.ImplicitStackAllocArrayCreationExpression(@stackalloc, openBracket, closeBracket, initializer); } private ExpressionSyntax ParseRegularStackAllocExpression() { var @stackalloc = this.EatToken(SyntaxKind.StackAllocKeyword); var elementType = this.ParseType(); InitializerExpressionSyntax initializer = null; if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { @stackalloc = CheckFeatureAvailability(@stackalloc, MessageID.IDS_FeatureStackAllocInitializer); initializer = this.ParseArrayInitializer(); } return _syntaxFactory.StackAllocArrayCreationExpression(@stackalloc, elementType, initializer); } private AnonymousMethodExpressionSyntax ParseAnonymousMethodExpression() { var parentScopeIsInAsync = this.IsInAsync; var result = parseAnonymousMethodExpressionWorker(); this.IsInAsync = parentScopeIsInAsync; return result; AnonymousMethodExpressionSyntax parseAnonymousMethodExpressionWorker() { var modifiers = ParseAnonymousFunctionModifiers(); if (modifiers.Any((int)SyntaxKind.AsyncKeyword)) { this.IsInAsync = true; } var @delegate = this.EatToken(SyntaxKind.DelegateKeyword); @delegate = CheckFeatureAvailability(@delegate, MessageID.IDS_FeatureAnonDelegates); ParameterListSyntax parameterList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { parameterList = this.ParseParenthesizedParameterList(); } // In mismatched braces cases (missing a }) it is possible for delegate declarations to be // parsed as delegate statement expressions. When this situation occurs all subsequent // delegate declarations will also be parsed as delegate statement expressions. In a file with // a sufficient number of delegates, common in generated code, it will put considerable // stack pressure on the parser. // // To help avoid this problem we don't recursively descend into a delegate expression unless // { } are actually present. This keeps the stack pressure lower in bad code scenarios. if (this.CurrentToken.Kind != SyntaxKind.OpenBraceToken) { // There's a special error code for a missing token after an accessor keyword var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); return _syntaxFactory.AnonymousMethodExpression( modifiers, @delegate, parameterList, _syntaxFactory.Block( attributeLists: default, openBrace, statements: default, SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)), expressionBody: null); } var body = this.ParseBlock(attributes: default); return _syntaxFactory.AnonymousMethodExpression( modifiers, @delegate, parameterList, body, expressionBody: null); } } private SyntaxList<SyntaxToken> ParseAnonymousFunctionModifiers() { var modifiers = _pool.Allocate(); while (true) { if (this.CurrentToken.Kind == SyntaxKind.StaticKeyword) { var staticKeyword = this.EatToken(SyntaxKind.StaticKeyword); staticKeyword = CheckFeatureAvailability(staticKeyword, MessageID.IDS_FeatureStaticAnonymousFunction); modifiers.Add(staticKeyword); continue; } if (this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword && IsAnonymousFunctionAsyncModifier()) { var asyncToken = this.EatContextualToken(SyntaxKind.AsyncKeyword); asyncToken = CheckFeatureAvailability(asyncToken, MessageID.IDS_FeatureAsync); modifiers.Add(asyncToken); continue; } break; } var result = modifiers.ToList(); _pool.Free(modifiers); return result; } private bool IsAnonymousFunctionAsyncModifier() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword); switch (this.PeekToken(1).Kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.IdentifierToken: case SyntaxKind.StaticKeyword: case SyntaxKind.RefKeyword: case SyntaxKind.DelegateKeyword: return true; case var kind: return IsPredefinedType(kind); }; } /// <summary> /// Parse expected lambda expression but assume `x ? () => y :` is a conditional /// expression rather than a lambda expression with an explicit return type and /// return null in that case only. /// </summary> private LambdaExpressionSyntax TryParseLambdaExpression() { var resetPoint = this.GetResetPoint(); try { var result = ParseLambdaExpression(); if (this.CurrentToken.Kind == SyntaxKind.ColonToken && result is ParenthesizedLambdaExpressionSyntax { ReturnType: NullableTypeSyntax { } }) { this.Reset(ref resetPoint); return null; } return result; } finally { this.Release(ref resetPoint); } } private LambdaExpressionSyntax ParseLambdaExpression() { var attributes = ParseAttributeDeclarations(); var parentScopeIsInAsync = this.IsInAsync; var result = parseLambdaExpressionWorker(); this.IsInAsync = parentScopeIsInAsync; return result; LambdaExpressionSyntax parseLambdaExpressionWorker() { var modifiers = ParseAnonymousFunctionModifiers(); if (modifiers.Any((int)SyntaxKind.AsyncKeyword)) { this.IsInAsync = true; } TypeSyntax returnType; var resetPoint = this.GetResetPoint(); try { returnType = ParseReturnType(); if (CurrentToken.Kind != SyntaxKind.OpenParenToken) { this.Reset(ref resetPoint); returnType = null; } } finally { this.Release(ref resetPoint); } if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var paramList = this.ParseLambdaParameterList(); var arrow = this.EatToken(SyntaxKind.EqualsGreaterThanToken); arrow = CheckFeatureAvailability(arrow, MessageID.IDS_FeatureLambda); var (block, expression) = ParseLambdaBody(); return _syntaxFactory.ParenthesizedLambdaExpression( attributes, modifiers, returnType, paramList, arrow, block, expression); } else { var name = this.ParseIdentifierToken(); var arrow = this.EatToken(SyntaxKind.EqualsGreaterThanToken); arrow = CheckFeatureAvailability(arrow, MessageID.IDS_FeatureLambda); var parameter = _syntaxFactory.Parameter( attributeLists: default, modifiers: default, type: null, identifier: name, @default: null); var (block, expression) = ParseLambdaBody(); return _syntaxFactory.SimpleLambdaExpression( attributes, modifiers, parameter, arrow, block, expression); } } } private (BlockSyntax, ExpressionSyntax) ParseLambdaBody() => CurrentToken.Kind == SyntaxKind.OpenBraceToken ? (ParseBlock(attributes: default), (ExpressionSyntax)null) : ((BlockSyntax)null, ParsePossibleRefExpression()); private ParameterListSyntax ParseLambdaParameterList() { var openParen = this.EatToken(SyntaxKind.OpenParenToken); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfParameterList; var nodes = _pool.AllocateSeparated<ParameterSyntax>(); try { if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { tryAgain: if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleLambdaParameter()) { // first parameter var parameter = this.ParseLambdaParameter(); nodes.Add(parameter); // additional parameters int tokenProgress = -1; while (IsMakingProgress(ref tokenProgress)) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleLambdaParameter()) { nodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); parameter = this.ParseLambdaParameter(); nodes.Add(parameter); continue; } else if (this.SkipBadLambdaParameterListTokens(ref openParen, nodes, SyntaxKind.CommaToken, SyntaxKind.CloseParenToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadLambdaParameterListTokens(ref openParen, nodes, SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken) == PostSkipAction.Continue) { goto tryAgain; } } _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.ParameterList(openParen, nodes, closeParen); } finally { _pool.Free(nodes); } } private bool IsPossibleLambdaParameter() { switch (this.CurrentToken.Kind) { case SyntaxKind.ParamsKeyword: // params is not actually legal in a lambda, but we allow it for error // recovery purposes and then give an error during semantic analysis. case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: case SyntaxKind.OpenParenToken: // tuple case SyntaxKind.OpenBracketToken: // attribute return true; case SyntaxKind.IdentifierToken: return this.IsTrueIdentifier(); case SyntaxKind.DelegateKeyword: return this.IsFunctionPointerStart(); default: return IsPredefinedType(this.CurrentToken.Kind); } } private PostSkipAction SkipBadLambdaParameterListTokens(ref SyntaxToken openParen, SeparatedSyntaxListBuilder<ParameterSyntax> list, SyntaxKind expected, SyntaxKind closeKind) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openParen, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleLambdaParameter(), p => p.CurrentToken.Kind == closeKind || p.IsTerminator(), expected); } private ParameterSyntax ParseLambdaParameter() { var attributes = ParseAttributeDeclarations(); // Params are actually illegal in a lambda, but we'll allow it for error recovery purposes and // give the "params unexpected" error at semantic analysis time. bool hasModifier = IsParameterModifier(this.CurrentToken.Kind); TypeSyntax paramType = null; SyntaxListBuilder modifiers = _pool.Allocate(); if (ShouldParseLambdaParameterType(hasModifier)) { if (hasModifier) { ParseParameterModifiers(modifiers); } paramType = ParseType(ParseTypeMode.Parameter); } SyntaxToken paramName = this.ParseIdentifierToken(); var parameter = _syntaxFactory.Parameter(attributes, modifiers.ToList(), paramType, paramName, null); _pool.Free(modifiers); return parameter; } private bool ShouldParseLambdaParameterType(bool hasModifier) { // If we have "ref/out/in/params" always try to parse out a type. if (hasModifier) { return true; } // If we have "int/string/etc." always parse out a type. if (IsPredefinedType(this.CurrentToken.Kind)) { return true; } // if we have a tuple type in a lambda. if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { return true; } if (this.IsFunctionPointerStart()) { return true; } if (this.IsTrueIdentifier(this.CurrentToken)) { // Don't parse out a type if we see: // // (a, // (a) // (a => // (a { // // In all other cases, parse out a type. var peek1 = this.PeekToken(1); if (peek1.Kind != SyntaxKind.CommaToken && peek1.Kind != SyntaxKind.CloseParenToken && peek1.Kind != SyntaxKind.EqualsGreaterThanToken && peek1.Kind != SyntaxKind.OpenBraceToken) { return true; } } return false; } private bool IsCurrentTokenQueryContextualKeyword { get { return IsTokenQueryContextualKeyword(this.CurrentToken); } } private static bool IsTokenQueryContextualKeyword(SyntaxToken token) { if (IsTokenStartOfNewQueryClause(token)) { return true; } switch (token.ContextualKind) { case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: case SyntaxKind.ByKeyword: return true; } return false; } private static bool IsTokenStartOfNewQueryClause(SyntaxToken token) { switch (token.ContextualKind) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.IntoKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: case SyntaxKind.LetKeyword: return true; default: return false; } } private bool IsQueryExpression(bool mayBeVariableDeclaration, bool mayBeMemberDeclaration) { if (this.CurrentToken.ContextualKind == SyntaxKind.FromKeyword) { return this.IsQueryExpressionAfterFrom(mayBeVariableDeclaration, mayBeMemberDeclaration); } return false; } // from_clause ::= from <type>? <identifier> in expression private bool IsQueryExpressionAfterFrom(bool mayBeVariableDeclaration, bool mayBeMemberDeclaration) { // from x ... var pk1 = this.PeekToken(1).Kind; if (IsPredefinedType(pk1)) { return true; } if (pk1 == SyntaxKind.IdentifierToken) { var pk2 = this.PeekToken(2).Kind; if (pk2 == SyntaxKind.InKeyword) { return true; } if (mayBeVariableDeclaration) { if (pk2 == SyntaxKind.SemicolonToken || // from x; pk2 == SyntaxKind.CommaToken || // from x, y; pk2 == SyntaxKind.EqualsToken) // from x = null; { return false; } } if (mayBeMemberDeclaration) { // from idf { ... property decl // from idf(... method decl if (pk2 == SyntaxKind.OpenParenToken || pk2 == SyntaxKind.OpenBraceToken) { return false; } // otherwise we need to scan a type } else { return true; } } // from T x ... var resetPoint = this.GetResetPoint(); try { this.EatToken(); ScanTypeFlags isType = this.ScanType(); if (isType != ScanTypeFlags.NotType && (this.CurrentToken.Kind == SyntaxKind.IdentifierToken || this.CurrentToken.Kind == SyntaxKind.InKeyword)) { return true; } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } return false; } private QueryExpressionSyntax ParseQueryExpression(Precedence precedence) { this.EnterQuery(); var fc = this.ParseFromClause(); fc = CheckFeatureAvailability(fc, MessageID.IDS_FeatureQueryExpression); if (precedence > Precedence.Assignment) { fc = this.AddError(fc, ErrorCode.WRN_PrecedenceInversion, SyntaxFacts.GetText(SyntaxKind.FromKeyword)); } var body = this.ParseQueryBody(); this.LeaveQuery(); return _syntaxFactory.QueryExpression(fc, body); } private QueryBodySyntax ParseQueryBody() { var clauses = _pool.Allocate<QueryClauseSyntax>(); try { SelectOrGroupClauseSyntax selectOrGroupBy = null; QueryContinuationSyntax continuation = null; // from, join, let, where and orderby while (true) { switch (this.CurrentToken.ContextualKind) { case SyntaxKind.FromKeyword: var fc = this.ParseFromClause(); clauses.Add(fc); continue; case SyntaxKind.JoinKeyword: clauses.Add(this.ParseJoinClause()); continue; case SyntaxKind.LetKeyword: clauses.Add(this.ParseLetClause()); continue; case SyntaxKind.WhereKeyword: clauses.Add(this.ParseWhereClause()); continue; case SyntaxKind.OrderByKeyword: clauses.Add(this.ParseOrderByClause()); continue; } break; } // select or group clause switch (this.CurrentToken.ContextualKind) { case SyntaxKind.SelectKeyword: selectOrGroupBy = this.ParseSelectClause(); break; case SyntaxKind.GroupKeyword: selectOrGroupBy = this.ParseGroupClause(); break; default: selectOrGroupBy = _syntaxFactory.SelectClause( this.EatToken(SyntaxKind.SelectKeyword, ErrorCode.ERR_ExpectedSelectOrGroup), this.CreateMissingIdentifierName()); break; } // optional query continuation clause if (this.CurrentToken.ContextualKind == SyntaxKind.IntoKeyword) { continuation = this.ParseQueryContinuation(); } return _syntaxFactory.QueryBody(clauses, selectOrGroupBy, continuation); } finally { _pool.Free(clauses); } } private FromClauseSyntax ParseFromClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.FromKeyword); var @from = this.EatContextualToken(SyntaxKind.FromKeyword); @from = CheckFeatureAvailability(@from, MessageID.IDS_FeatureQueryExpression); TypeSyntax type = null; if (this.PeekToken(1).Kind != SyntaxKind.InKeyword) { type = this.ParseType(); } SyntaxToken name; if (this.PeekToken(1).ContextualKind == SyntaxKind.InKeyword && (this.CurrentToken.Kind != SyntaxKind.IdentifierToken || SyntaxFacts.IsQueryContextualKeyword(this.CurrentToken.ContextualKind))) { //if this token is a something other than an identifier (someone accidentally used a contextual //keyword or a literal, for example), but we can see that the "in" is in the right place, then //just replace whatever is here with a missing identifier name = this.EatToken(); name = WithAdditionalDiagnostics(name, this.GetExpectedTokenError(SyntaxKind.IdentifierToken, name.ContextualKind, name.GetLeadingTriviaWidth(), name.Width)); name = this.ConvertToMissingWithTrailingTrivia(name, SyntaxKind.IdentifierToken); } else { name = this.ParseIdentifierToken(); } var @in = this.EatToken(SyntaxKind.InKeyword); var expression = this.ParseExpressionCore(); return _syntaxFactory.FromClause(@from, type, name, @in, expression); } private JoinClauseSyntax ParseJoinClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.JoinKeyword); var @join = this.EatContextualToken(SyntaxKind.JoinKeyword); TypeSyntax type = null; if (this.PeekToken(1).Kind != SyntaxKind.InKeyword) { type = this.ParseType(); } var name = this.ParseIdentifierToken(); var @in = this.EatToken(SyntaxKind.InKeyword); var inExpression = this.ParseExpressionCore(); var @on = this.EatContextualToken(SyntaxKind.OnKeyword, ErrorCode.ERR_ExpectedContextualKeywordOn); var leftExpression = this.ParseExpressionCore(); var @equals = this.EatContextualToken(SyntaxKind.EqualsKeyword, ErrorCode.ERR_ExpectedContextualKeywordEquals); var rightExpression = this.ParseExpressionCore(); JoinIntoClauseSyntax joinInto = null; if (this.CurrentToken.ContextualKind == SyntaxKind.IntoKeyword) { var @into = ConvertToKeyword(this.EatToken()); var intoId = this.ParseIdentifierToken(); joinInto = _syntaxFactory.JoinIntoClause(@into, intoId); } return _syntaxFactory.JoinClause(@join, type, name, @in, inExpression, @on, leftExpression, @equals, rightExpression, joinInto); } private LetClauseSyntax ParseLetClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.LetKeyword); var @let = this.EatContextualToken(SyntaxKind.LetKeyword); var name = this.ParseIdentifierToken(); var equal = this.EatToken(SyntaxKind.EqualsToken); var expression = this.ParseExpressionCore(); return _syntaxFactory.LetClause(@let, name, equal, expression); } private WhereClauseSyntax ParseWhereClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword); var @where = this.EatContextualToken(SyntaxKind.WhereKeyword); var condition = this.ParseExpressionCore(); return _syntaxFactory.WhereClause(@where, condition); } private OrderByClauseSyntax ParseOrderByClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.OrderByKeyword); var @orderby = this.EatContextualToken(SyntaxKind.OrderByKeyword); var list = _pool.AllocateSeparated<OrderingSyntax>(); try { // first argument list.Add(this.ParseOrdering()); // additional arguments while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); list.Add(this.ParseOrdering()); continue; } else if (this.SkipBadOrderingListTokens(list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } return _syntaxFactory.OrderByClause(@orderby, list); } finally { _pool.Free(list); } } private PostSkipAction SkipBadOrderingListTokens(SeparatedSyntaxListBuilder<OrderingSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken, p => p.CurrentToken.Kind == SyntaxKind.CloseParenToken || p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsCurrentTokenQueryContextualKeyword || p.IsTerminator(), expected); } private OrderingSyntax ParseOrdering() { var expression = this.ParseExpressionCore(); SyntaxToken direction = null; SyntaxKind kind = SyntaxKind.AscendingOrdering; if (this.CurrentToken.ContextualKind == SyntaxKind.AscendingKeyword || this.CurrentToken.ContextualKind == SyntaxKind.DescendingKeyword) { direction = ConvertToKeyword(this.EatToken()); if (direction.Kind == SyntaxKind.DescendingKeyword) { kind = SyntaxKind.DescendingOrdering; } } return _syntaxFactory.Ordering(kind, expression, direction); } private SelectClauseSyntax ParseSelectClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.SelectKeyword); var @select = this.EatContextualToken(SyntaxKind.SelectKeyword); var expression = this.ParseExpressionCore(); return _syntaxFactory.SelectClause(@select, expression); } private GroupClauseSyntax ParseGroupClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.GroupKeyword); var @group = this.EatContextualToken(SyntaxKind.GroupKeyword); var groupExpression = this.ParseExpressionCore(); var @by = this.EatContextualToken(SyntaxKind.ByKeyword, ErrorCode.ERR_ExpectedContextualKeywordBy); var byExpression = this.ParseExpressionCore(); return _syntaxFactory.GroupClause(@group, groupExpression, @by, byExpression); } private QueryContinuationSyntax ParseQueryContinuation() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.IntoKeyword); var @into = this.EatContextualToken(SyntaxKind.IntoKeyword); var name = this.ParseIdentifierToken(); var body = this.ParseQueryBody(); return _syntaxFactory.QueryContinuation(@into, name, body); } [Obsolete("Use IsIncrementalAndFactoryContextMatches")] private new bool IsIncremental { get { throw new Exception("Use IsIncrementalAndFactoryContextMatches"); } } private bool IsIncrementalAndFactoryContextMatches { get { if (!base.IsIncremental) { return false; } CSharp.CSharpSyntaxNode current = this.CurrentNode; return current != null && MatchesFactoryContext(current.Green, _syntaxFactoryContext); } } internal static bool MatchesFactoryContext(GreenNode green, SyntaxFactoryContext context) { return context.IsInAsync == green.ParsedInAsync && context.IsInQuery == green.ParsedInQuery; } private bool IsInAsync { get { return _syntaxFactoryContext.IsInAsync; } set { _syntaxFactoryContext.IsInAsync = value; } } private bool IsInQuery { get { return _syntaxFactoryContext.IsInQuery; } } private void EnterQuery() { _syntaxFactoryContext.QueryDepth++; } private void LeaveQuery() { Debug.Assert(_syntaxFactoryContext.QueryDepth > 0); _syntaxFactoryContext.QueryDepth--; } private new ResetPoint GetResetPoint() { return new ResetPoint( base.GetResetPoint(), _termState, _isInTry, _syntaxFactoryContext.IsInAsync, _syntaxFactoryContext.QueryDepth); } private void Reset(ref ResetPoint state) { _termState = state.TerminatorState; _isInTry = state.IsInTry; _syntaxFactoryContext.IsInAsync = state.IsInAsync; _syntaxFactoryContext.QueryDepth = state.QueryDepth; base.Reset(ref state.BaseResetPoint); } private void Release(ref ResetPoint state) { base.Release(ref state.BaseResetPoint); } private new struct ResetPoint { internal SyntaxParser.ResetPoint BaseResetPoint; internal readonly TerminatorState TerminatorState; internal readonly bool IsInTry; internal readonly bool IsInAsync; internal readonly int QueryDepth; internal ResetPoint( SyntaxParser.ResetPoint resetPoint, TerminatorState terminatorState, bool isInTry, bool isInAsync, int queryDepth) { this.BaseResetPoint = resetPoint; this.TerminatorState = terminatorState; this.IsInTry = isInTry; this.IsInAsync = isInAsync; this.QueryDepth = queryDepth; } } internal TNode ConsumeUnexpectedTokens<TNode>(TNode node) where TNode : CSharpSyntaxNode { if (this.CurrentToken.Kind == SyntaxKind.EndOfFileToken) return node; SyntaxListBuilder<SyntaxToken> b = _pool.Allocate<SyntaxToken>(); while (this.CurrentToken.Kind != SyntaxKind.EndOfFileToken) { b.Add(this.EatToken()); } var trailingTrash = b.ToList(); _pool.Free(b); node = this.AddError(node, ErrorCode.ERR_UnexpectedToken, trailingTrash[0].ToString()); node = this.AddTrailingSkippedSyntax(node, trailingTrash.Node); return node; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; internal partial class LanguageParser : SyntaxParser { // list pools - allocators for lists that are used to build sequences of nodes. The lists // can be reused (hence pooled) since the syntax factory methods don't keep references to // them private readonly SyntaxListPool _pool = new SyntaxListPool(); // Don't need to reset this. private readonly SyntaxFactoryContext _syntaxFactoryContext; // Fields are resettable. private readonly ContextAwareSyntax _syntaxFactory; // Has context, the fields of which are resettable. private int _recursionDepth; private TerminatorState _termState; // Resettable private bool _isInTry; // Resettable private bool _checkedTopLevelStatementsFeatureAvailability; // Resettable // NOTE: If you add new state, you should probably add it to ResetPoint as well. internal LanguageParser( Lexer lexer, CSharp.CSharpSyntaxNode oldTree, IEnumerable<TextChangeRange> changes, LexerMode lexerMode = LexerMode.Syntax, CancellationToken cancellationToken = default(CancellationToken)) : base(lexer, lexerMode, oldTree, changes, allowModeReset: false, preLexIfNotIncremental: true, cancellationToken: cancellationToken) { _syntaxFactoryContext = new SyntaxFactoryContext(); _syntaxFactory = new ContextAwareSyntax(_syntaxFactoryContext); } private static bool IsSomeWord(SyntaxKind kind) { return kind == SyntaxKind.IdentifierToken || SyntaxFacts.IsKeywordKind(kind); } // Parsing rule terminating conditions. This is how we know if it is // okay to abort the current parsing rule when unexpected tokens occur. [Flags] internal enum TerminatorState { EndOfFile = 0, IsNamespaceMemberStartOrStop = 1 << 0, IsAttributeDeclarationTerminator = 1 << 1, IsPossibleAggregateClauseStartOrStop = 1 << 2, IsPossibleMemberStartOrStop = 1 << 3, IsEndOfReturnType = 1 << 4, IsEndOfParameterList = 1 << 5, IsEndOfFieldDeclaration = 1 << 6, IsPossibleEndOfVariableDeclaration = 1 << 7, IsEndOfTypeArgumentList = 1 << 8, IsPossibleStatementStartOrStop = 1 << 9, IsEndOfFixedStatement = 1 << 10, IsEndOfTryBlock = 1 << 11, IsEndOfCatchClause = 1 << 12, IsEndOfFilterClause = 1 << 13, IsEndOfCatchBlock = 1 << 14, IsEndOfDoWhileExpression = 1 << 15, IsEndOfForStatementArgument = 1 << 16, IsEndOfDeclarationClause = 1 << 17, IsEndOfArgumentList = 1 << 18, IsSwitchSectionStart = 1 << 19, IsEndOfTypeParameterList = 1 << 20, IsEndOfMethodSignature = 1 << 21, IsEndOfNameInExplicitInterface = 1 << 22, IsEndOfFunctionPointerParameterList = 1 << 23, IsEndOfFunctionPointerParameterListErrored = 1 << 24, IsEndOfFunctionPointerCallingConvention = 1 << 25, IsEndOfRecordSignature = 1 << 26, } private const int LastTerminatorState = (int)TerminatorState.IsEndOfRecordSignature; private bool IsTerminator() { if (this.CurrentToken.Kind == SyntaxKind.EndOfFileToken) { return true; } for (int i = 1; i <= LastTerminatorState; i <<= 1) { switch (_termState & (TerminatorState)i) { case TerminatorState.IsNamespaceMemberStartOrStop when this.IsNamespaceMemberStartOrStop(): case TerminatorState.IsAttributeDeclarationTerminator when this.IsAttributeDeclarationTerminator(): case TerminatorState.IsPossibleAggregateClauseStartOrStop when this.IsPossibleAggregateClauseStartOrStop(): case TerminatorState.IsPossibleMemberStartOrStop when this.IsPossibleMemberStartOrStop(): case TerminatorState.IsEndOfReturnType when this.IsEndOfReturnType(): case TerminatorState.IsEndOfParameterList when this.IsEndOfParameterList(): case TerminatorState.IsEndOfFieldDeclaration when this.IsEndOfFieldDeclaration(): case TerminatorState.IsPossibleEndOfVariableDeclaration when this.IsPossibleEndOfVariableDeclaration(): case TerminatorState.IsEndOfTypeArgumentList when this.IsEndOfTypeArgumentList(): case TerminatorState.IsPossibleStatementStartOrStop when this.IsPossibleStatementStartOrStop(): case TerminatorState.IsEndOfFixedStatement when this.IsEndOfFixedStatement(): case TerminatorState.IsEndOfTryBlock when this.IsEndOfTryBlock(): case TerminatorState.IsEndOfCatchClause when this.IsEndOfCatchClause(): case TerminatorState.IsEndOfFilterClause when this.IsEndOfFilterClause(): case TerminatorState.IsEndOfCatchBlock when this.IsEndOfCatchBlock(): case TerminatorState.IsEndOfDoWhileExpression when this.IsEndOfDoWhileExpression(): case TerminatorState.IsEndOfForStatementArgument when this.IsEndOfForStatementArgument(): case TerminatorState.IsEndOfDeclarationClause when this.IsEndOfDeclarationClause(): case TerminatorState.IsEndOfArgumentList when this.IsEndOfArgumentList(): case TerminatorState.IsSwitchSectionStart when this.IsPossibleSwitchSection(): case TerminatorState.IsEndOfTypeParameterList when this.IsEndOfTypeParameterList(): case TerminatorState.IsEndOfMethodSignature when this.IsEndOfMethodSignature(): case TerminatorState.IsEndOfNameInExplicitInterface when this.IsEndOfNameInExplicitInterface(): case TerminatorState.IsEndOfFunctionPointerParameterList when this.IsEndOfFunctionPointerParameterList(errored: false): case TerminatorState.IsEndOfFunctionPointerParameterListErrored when this.IsEndOfFunctionPointerParameterList(errored: true): case TerminatorState.IsEndOfFunctionPointerCallingConvention when this.IsEndOfFunctionPointerCallingConvention(): case TerminatorState.IsEndOfRecordSignature when this.IsEndOfRecordSignature(): return true; } } return false; } private static CSharp.CSharpSyntaxNode GetOldParent(CSharp.CSharpSyntaxNode node) { return node != null ? node.Parent : null; } private struct NamespaceBodyBuilder { public SyntaxListBuilder<ExternAliasDirectiveSyntax> Externs; public SyntaxListBuilder<UsingDirectiveSyntax> Usings; public SyntaxListBuilder<AttributeListSyntax> Attributes; public SyntaxListBuilder<MemberDeclarationSyntax> Members; public NamespaceBodyBuilder(SyntaxListPool pool) { Externs = pool.Allocate<ExternAliasDirectiveSyntax>(); Usings = pool.Allocate<UsingDirectiveSyntax>(); Attributes = pool.Allocate<AttributeListSyntax>(); Members = pool.Allocate<MemberDeclarationSyntax>(); } internal void Free(SyntaxListPool pool) { pool.Free(Members); pool.Free(Attributes); pool.Free(Usings); pool.Free(Externs); } } internal CompilationUnitSyntax ParseCompilationUnit() { return ParseWithStackGuard( ParseCompilationUnitCore, () => SyntaxFactory.CompilationUnit( new SyntaxList<ExternAliasDirectiveSyntax>(), new SyntaxList<UsingDirectiveSyntax>(), new SyntaxList<AttributeListSyntax>(), new SyntaxList<MemberDeclarationSyntax>(), SyntaxFactory.Token(SyntaxKind.EndOfFileToken))); } internal CompilationUnitSyntax ParseCompilationUnitCore() { SyntaxToken tmp = null; SyntaxListBuilder initialBadNodes = null; var body = new NamespaceBodyBuilder(_pool); try { this.ParseNamespaceBody(ref tmp, ref body, ref initialBadNodes, SyntaxKind.CompilationUnit); var eof = this.EatToken(SyntaxKind.EndOfFileToken); var result = _syntaxFactory.CompilationUnit(body.Externs, body.Usings, body.Attributes, body.Members, eof); if (initialBadNodes != null) { // attach initial bad nodes as leading trivia on first token result = AddLeadingSkippedSyntax(result, initialBadNodes.ToListNode()); _pool.Free(initialBadNodes); } return result; } finally { body.Free(_pool); } } internal TNode ParseWithStackGuard<TNode>(Func<TNode> parseFunc, Func<TNode> createEmptyNodeFunc) where TNode : CSharpSyntaxNode { // If this value is non-zero then we are nesting calls to ParseWithStackGuard which should not be // happening. It's not a bug but it's inefficient and should be changed. Debug.Assert(_recursionDepth == 0); try { return parseFunc(); } catch (InsufficientExecutionStackException) { return CreateForGlobalFailure(lexer.TextWindow.Position, createEmptyNodeFunc()); } } private TNode CreateForGlobalFailure<TNode>(int position, TNode node) where TNode : CSharpSyntaxNode { // Turn the complete input into a single skipped token. This avoids running the lexer, and therefore // the preprocessor directive parser, which may itself run into the same problem that caused the // original failure. var builder = new SyntaxListBuilder(1); builder.Add(SyntaxFactory.BadToken(null, lexer.TextWindow.Text.ToString(), null)); var fileAsTrivia = _syntaxFactory.SkippedTokensTrivia(builder.ToList<SyntaxToken>()); node = AddLeadingSkippedSyntax(node, fileAsTrivia); ForceEndOfFile(); // force the scanner to report that it is at the end of the input. return AddError(node, position, 0, ErrorCode.ERR_InsufficientStack); } private BaseNamespaceDeclarationSyntax ParseNamespaceDeclaration( SyntaxList<AttributeListSyntax> attributeLists, SyntaxListBuilder modifiers) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); var result = ParseNamespaceDeclarationCore(attributeLists, modifiers); _recursionDepth--; return result; } private BaseNamespaceDeclarationSyntax ParseNamespaceDeclarationCore( SyntaxList<AttributeListSyntax> attributeLists, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NamespaceKeyword); var namespaceToken = this.EatToken(SyntaxKind.NamespaceKeyword); if (IsScript) { namespaceToken = this.AddError(namespaceToken, ErrorCode.ERR_NamespaceNotAllowedInScript); } var name = this.ParseQualifiedName(); SyntaxToken openBrace = null; SyntaxToken semicolon = null; if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatToken(SyntaxKind.SemicolonToken); } else if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || IsPossibleNamespaceMemberDeclaration()) { //either we see the brace we expect here or we see something that could come after a brace //so we insert a missing one openBrace = this.EatToken(SyntaxKind.OpenBraceToken); } else { //the next character is neither the brace we expect, nor a token that could follow the expected //brace so we assume it's a mistake and replace it with a missing brace openBrace = this.EatTokenWithPrejudice(SyntaxKind.OpenBraceToken); openBrace = this.ConvertToMissingWithTrailingTrivia(openBrace, SyntaxKind.OpenBraceToken); } Debug.Assert(semicolon != null || openBrace != null); var body = new NamespaceBodyBuilder(_pool); try { if (openBrace == null) { Debug.Assert(semicolon != null); SyntaxListBuilder initialBadNodes = null; this.ParseNamespaceBody(ref semicolon, ref body, ref initialBadNodes, SyntaxKind.FileScopedNamespaceDeclaration); Debug.Assert(initialBadNodes == null); // init bad nodes should have been attached to semicolon... namespaceToken = CheckFeatureAvailability(namespaceToken, MessageID.IDS_FeatureFileScopedNamespace); return _syntaxFactory.FileScopedNamespaceDeclaration( attributeLists, modifiers.ToList(), namespaceToken, name, semicolon, body.Externs, body.Usings, body.Members); } else { SyntaxListBuilder initialBadNodes = null; this.ParseNamespaceBody(ref openBrace, ref body, ref initialBadNodes, SyntaxKind.NamespaceDeclaration); Debug.Assert(initialBadNodes == null); // init bad nodes should have been attached to open brace... return _syntaxFactory.NamespaceDeclaration( attributeLists, modifiers.ToList(), namespaceToken, name, openBrace, body.Externs, body.Usings, body.Members, this.EatToken(SyntaxKind.CloseBraceToken), this.TryEatToken(SyntaxKind.SemicolonToken)); } } finally { body.Free(_pool); } } private static bool IsPossibleStartOfTypeDeclaration(SyntaxKind kind) { switch (kind) { case SyntaxKind.EnumKeyword: case SyntaxKind.DelegateKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.StructKeyword: case SyntaxKind.AbstractKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.NewKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PublicKeyword: case SyntaxKind.SealedKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.OpenBracketToken: return true; default: return false; } } private void AddSkippedNamespaceText( ref SyntaxToken openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes, CSharpSyntaxNode skippedSyntax) { if (body.Members.Count > 0) { AddTrailingSkippedSyntax(body.Members, skippedSyntax); } else if (body.Attributes.Count > 0) { AddTrailingSkippedSyntax(body.Attributes, skippedSyntax); } else if (body.Usings.Count > 0) { AddTrailingSkippedSyntax(body.Usings, skippedSyntax); } else if (body.Externs.Count > 0) { AddTrailingSkippedSyntax(body.Externs, skippedSyntax); } else if (openBraceOrSemicolon != null) { openBraceOrSemicolon = AddTrailingSkippedSyntax(openBraceOrSemicolon, skippedSyntax); } else { if (initialBadNodes == null) { initialBadNodes = _pool.Allocate(); } initialBadNodes.AddRange(skippedSyntax); } } // Parts of a namespace declaration in the order they can be defined. private enum NamespaceParts { None = 0, ExternAliases = 1, Usings = 2, GlobalAttributes = 3, MembersAndStatements = 4, TypesAndNamespaces = 5, TopLevelStatementsAfterTypesAndNamespaces = 6, } private void ParseNamespaceBody(ref SyntaxToken openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes, SyntaxKind parentKind) { // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); bool isGlobal = openBraceOrSemicolon == null; var saveTerm = _termState; _termState |= TerminatorState.IsNamespaceMemberStartOrStop; NamespaceParts seen = NamespaceParts.None; var pendingIncompleteMembers = _pool.Allocate<MemberDeclarationSyntax>(); bool reportUnexpectedToken = true; try { while (true) { switch (this.CurrentToken.Kind) { case SyntaxKind.NamespaceKeyword: // incomplete members must be processed before we add any nodes to the body: AddIncompleteMembers(ref pendingIncompleteMembers, ref body); var attributeLists = _pool.Allocate<AttributeListSyntax>(); var modifiers = _pool.Allocate(); body.Members.Add(adjustStateAndReportStatementOutOfOrder(ref seen, this.ParseNamespaceDeclaration(attributeLists, modifiers))); _pool.Free(attributeLists); _pool.Free(modifiers); reportUnexpectedToken = true; break; case SyntaxKind.CloseBraceToken: // A very common user error is to type an additional } // somewhere in the file. This will cause us to stop parsing // the root (global) namespace too early and will make the // rest of the file unparseable and unusable by intellisense. // We detect that case here and we skip the close curly and // continue parsing as if we did not see the } if (isGlobal) { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); var token = this.EatToken(); token = this.AddError(token, IsScript ? ErrorCode.ERR_GlobalDefinitionOrStatementExpected : ErrorCode.ERR_EOFExpected); this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, token); reportUnexpectedToken = true; break; } else { // This token marks the end of a namespace body return; } case SyntaxKind.EndOfFileToken: // This token marks the end of a namespace body return; case SyntaxKind.ExternKeyword: if (isGlobal && !ScanExternAliasDirective()) { // extern member or a local function goto default; } else { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); var @extern = ParseExternAliasDirective(); if (seen > NamespaceParts.ExternAliases) { @extern = this.AddErrorToFirstToken(@extern, ErrorCode.ERR_ExternAfterElements); this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, @extern); } else { body.Externs.Add(@extern); seen = NamespaceParts.ExternAliases; } reportUnexpectedToken = true; break; } case SyntaxKind.UsingKeyword: if (isGlobal && (this.PeekToken(1).Kind == SyntaxKind.OpenParenToken || (!IsScript && IsPossibleTopLevelUsingLocalDeclarationStatement()))) { // Top-level using statement or using local declaration goto default; } else { parseUsingDirective(ref openBraceOrSemicolon, ref body, ref initialBadNodes, ref seen, ref pendingIncompleteMembers); } reportUnexpectedToken = true; break; case SyntaxKind.IdentifierToken: if (this.CurrentToken.ContextualKind != SyntaxKind.GlobalKeyword || this.PeekToken(1).Kind != SyntaxKind.UsingKeyword) { goto default; } else { parseUsingDirective(ref openBraceOrSemicolon, ref body, ref initialBadNodes, ref seen, ref pendingIncompleteMembers); } reportUnexpectedToken = true; break; case SyntaxKind.OpenBracketToken: if (this.IsPossibleGlobalAttributeDeclaration()) { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); var attribute = this.ParseAttributeDeclaration(); if (!isGlobal || seen > NamespaceParts.GlobalAttributes) { attribute = this.AddError(attribute, attribute.Target.Identifier, ErrorCode.ERR_GlobalAttributesNotFirst); this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, attribute); } else { body.Attributes.Add(attribute); seen = NamespaceParts.GlobalAttributes; } reportUnexpectedToken = true; break; } goto default; default: var memberOrStatement = isGlobal ? this.ParseMemberDeclarationOrStatement(parentKind) : this.ParseMemberDeclaration(parentKind); if (memberOrStatement == null) { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBraceOrSemicolon, ref body, ref initialBadNodes); // eat one token and try to parse declaration or statement again: var skippedToken = EatToken(); if (reportUnexpectedToken && !skippedToken.ContainsDiagnostics) { skippedToken = this.AddError(skippedToken, IsScript ? ErrorCode.ERR_GlobalDefinitionOrStatementExpected : ErrorCode.ERR_EOFExpected); // do not report the error multiple times for subsequent tokens: reportUnexpectedToken = false; } this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, skippedToken); } else if (memberOrStatement.Kind == SyntaxKind.IncompleteMember && seen < NamespaceParts.MembersAndStatements) { pendingIncompleteMembers.Add(memberOrStatement); reportUnexpectedToken = true; } else { // incomplete members must be processed before we add any nodes to the body: AddIncompleteMembers(ref pendingIncompleteMembers, ref body); body.Members.Add(adjustStateAndReportStatementOutOfOrder(ref seen, memberOrStatement)); reportUnexpectedToken = true; } break; } } } finally { _termState = saveTerm; // adds pending incomplete nodes: AddIncompleteMembers(ref pendingIncompleteMembers, ref body); _pool.Free(pendingIncompleteMembers); } MemberDeclarationSyntax adjustStateAndReportStatementOutOfOrder(ref NamespaceParts seen, MemberDeclarationSyntax memberOrStatement) { switch (memberOrStatement.Kind) { case SyntaxKind.GlobalStatement: if (seen < NamespaceParts.MembersAndStatements) { seen = NamespaceParts.MembersAndStatements; } else if (seen == NamespaceParts.TypesAndNamespaces) { seen = NamespaceParts.TopLevelStatementsAfterTypesAndNamespaces; if (!IsScript) { memberOrStatement = this.AddError(memberOrStatement, ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType); } } break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: if (seen < NamespaceParts.TypesAndNamespaces) { seen = NamespaceParts.TypesAndNamespaces; } break; default: if (seen < NamespaceParts.MembersAndStatements) { seen = NamespaceParts.MembersAndStatements; } break; } return memberOrStatement; } void parseUsingDirective(ref SyntaxToken openBrace, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes, ref NamespaceParts seen, ref SyntaxListBuilder<MemberDeclarationSyntax> pendingIncompleteMembers) { // incomplete members must be processed before we add any nodes to the body: ReduceIncompleteMembers(ref pendingIncompleteMembers, ref openBrace, ref body, ref initialBadNodes); var @using = this.ParseUsingDirective(); if (seen > NamespaceParts.Usings) { @using = this.AddError(@using, ErrorCode.ERR_UsingAfterElements); this.AddSkippedNamespaceText(ref openBrace, ref body, ref initialBadNodes, @using); } else { body.Usings.Add(@using); seen = NamespaceParts.Usings; } } } private GlobalStatementSyntax CheckTopLevelStatementsFeatureAvailability(GlobalStatementSyntax globalStatementSyntax) { if (IsScript || _checkedTopLevelStatementsFeatureAvailability) { return globalStatementSyntax; } _checkedTopLevelStatementsFeatureAvailability = true; return CheckFeatureAvailability(globalStatementSyntax, MessageID.IDS_TopLevelStatements); } private static void AddIncompleteMembers(ref SyntaxListBuilder<MemberDeclarationSyntax> incompleteMembers, ref NamespaceBodyBuilder body) { if (incompleteMembers.Count > 0) { body.Members.AddRange(incompleteMembers); incompleteMembers.Clear(); } } private void ReduceIncompleteMembers( ref SyntaxListBuilder<MemberDeclarationSyntax> incompleteMembers, ref SyntaxToken openBraceOrSemicolon, ref NamespaceBodyBuilder body, ref SyntaxListBuilder initialBadNodes) { for (int i = 0; i < incompleteMembers.Count; i++) { this.AddSkippedNamespaceText(ref openBraceOrSemicolon, ref body, ref initialBadNodes, incompleteMembers[i]); } incompleteMembers.Clear(); } private bool IsPossibleNamespaceMemberDeclaration() { switch (this.CurrentToken.Kind) { case SyntaxKind.ExternKeyword: case SyntaxKind.UsingKeyword: case SyntaxKind.NamespaceKeyword: return true; case SyntaxKind.IdentifierToken: return IsPartialInNamespaceMemberDeclaration(); default: return IsPossibleStartOfTypeDeclaration(this.CurrentToken.Kind); } } private bool IsPartialInNamespaceMemberDeclaration() { if (this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword) { if (this.IsPartialType()) { return true; } else if (this.PeekToken(1).Kind == SyntaxKind.NamespaceKeyword) { return true; } } return false; } public bool IsEndOfNamespace() { return this.CurrentToken.Kind == SyntaxKind.CloseBraceToken; } public bool IsGobalAttributesTerminator() { return this.IsEndOfNamespace() || this.IsPossibleNamespaceMemberDeclaration(); } private bool IsNamespaceMemberStartOrStop() { return this.IsEndOfNamespace() || this.IsPossibleNamespaceMemberDeclaration(); } /// <summary> /// Returns true if the lookahead tokens compose extern alias directive. /// </summary> private bool ScanExternAliasDirective() { // The check also includes the ending semicolon so that we can disambiguate among: // extern alias goo; // extern alias goo(); // extern alias goo { get; } return this.CurrentToken.Kind == SyntaxKind.ExternKeyword && this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).ContextualKind == SyntaxKind.AliasKeyword && this.PeekToken(2).Kind == SyntaxKind.IdentifierToken && this.PeekToken(3).Kind == SyntaxKind.SemicolonToken; } private ExternAliasDirectiveSyntax ParseExternAliasDirective() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.ExternAliasDirective) { return (ExternAliasDirectiveSyntax)this.EatNode(); } Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ExternKeyword); var externToken = this.EatToken(SyntaxKind.ExternKeyword); var aliasToken = this.EatContextualToken(SyntaxKind.AliasKeyword); externToken = CheckFeatureAvailability(externToken, MessageID.IDS_FeatureExternAlias); var name = this.ParseIdentifierToken(); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.ExternAliasDirective(externToken, aliasToken, name, semicolon); } private NameEqualsSyntax ParseNameEquals() { Debug.Assert(this.IsNamedAssignment()); return _syntaxFactory.NameEquals( _syntaxFactory.IdentifierName(this.ParseIdentifierToken()), this.EatToken(SyntaxKind.EqualsToken)); } private UsingDirectiveSyntax ParseUsingDirective() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.UsingDirective) { return (UsingDirectiveSyntax)this.EatNode(); } SyntaxToken globalToken = null; if (this.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword) { globalToken = ConvertToKeyword(this.EatToken()); } Debug.Assert(this.CurrentToken.Kind == SyntaxKind.UsingKeyword); var usingToken = this.EatToken(SyntaxKind.UsingKeyword); var staticToken = this.TryEatToken(SyntaxKind.StaticKeyword); var alias = this.IsNamedAssignment() ? ParseNameEquals() : null; NameSyntax name; SyntaxToken semicolon; if (IsPossibleNamespaceMemberDeclaration()) { //We're worried about the case where someone already has a correct program //and they've gone back to add a using directive, but have not finished the //new directive. e.g. // // using // namespace Goo { // //... // } // //If the token we see after "using" could be its own top-level construct, then //we just want to insert a missing identifier and semicolon and then return to //parsing at the top-level. // //NB: there's no way this could be true for a set of tokens that form a valid //using directive, so there's no danger in checking the error case first. name = WithAdditionalDiagnostics(CreateMissingIdentifierName(), GetExpectedTokenError(SyntaxKind.IdentifierToken, this.CurrentToken.Kind)); semicolon = SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken); } else { name = this.ParseQualifiedName(); if (name.IsMissing && this.PeekToken(1).Kind == SyntaxKind.SemicolonToken) { //if we can see a semicolon ahead, then the current token was //probably supposed to be an identifier name = AddTrailingSkippedSyntax(name, this.EatToken()); } semicolon = this.EatToken(SyntaxKind.SemicolonToken); } var usingDirective = _syntaxFactory.UsingDirective(globalToken, usingToken, staticToken, alias, name, semicolon); if (staticToken != null) { usingDirective = CheckFeatureAvailability(usingDirective, MessageID.IDS_FeatureUsingStatic); } if (globalToken != null) { usingDirective = CheckFeatureAvailability(usingDirective, MessageID.IDS_FeatureGlobalUsing); } return usingDirective; } private bool IsPossibleGlobalAttributeDeclaration() { return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken && IsGlobalAttributeTarget(this.PeekToken(1)) && this.PeekToken(2).Kind == SyntaxKind.ColonToken; } private static bool IsGlobalAttributeTarget(SyntaxToken token) { switch (token.ToAttributeLocation()) { case AttributeLocation.Assembly: case AttributeLocation.Module: return true; default: return false; } } private bool IsPossibleAttributeDeclaration() { return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken; } private SyntaxList<AttributeListSyntax> ParseAttributeDeclarations() { var attributes = _pool.Allocate<AttributeListSyntax>(); try { var saveTerm = _termState; _termState |= TerminatorState.IsAttributeDeclarationTerminator; while (this.IsPossibleAttributeDeclaration()) { var attribute = this.ParseAttributeDeclaration(); attributes.Add(attribute); } _termState = saveTerm; return attributes.ToList(); } finally { _pool.Free(attributes); } } private bool IsAttributeDeclarationTerminator() { return this.CurrentToken.Kind == SyntaxKind.CloseBracketToken || this.IsPossibleAttributeDeclaration(); // start of a new one... } private AttributeListSyntax ParseAttributeDeclaration() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.AttributeList) { return (AttributeListSyntax)this.EatNode(); } var openBracket = this.EatToken(SyntaxKind.OpenBracketToken); // Check for optional location : AttributeTargetSpecifierSyntax attrLocation = null; if (IsSomeWord(this.CurrentToken.Kind) && this.PeekToken(1).Kind == SyntaxKind.ColonToken) { var id = ConvertToKeyword(this.EatToken()); var colon = this.EatToken(SyntaxKind.ColonToken); attrLocation = _syntaxFactory.AttributeTargetSpecifier(id, colon); } var attributes = _pool.AllocateSeparated<AttributeSyntax>(); try { if (attrLocation != null && attrLocation.Identifier.ToAttributeLocation() == AttributeLocation.Module) { attrLocation = CheckFeatureAvailability(attrLocation, MessageID.IDS_FeatureModuleAttrLoc); } this.ParseAttributes(attributes); var closeBracket = this.EatToken(SyntaxKind.CloseBracketToken); var declaration = _syntaxFactory.AttributeList(openBracket, attrLocation, attributes, closeBracket); return declaration; } finally { _pool.Free(attributes); } } private void ParseAttributes(SeparatedSyntaxListBuilder<AttributeSyntax> nodes) { // always expect at least one attribute nodes.Add(this.ParseAttribute()); // remaining attributes while (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { // comma is optional, but if it is present it may be followed by another attribute nodes.AddSeparator(this.EatToken()); // check for legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBracketToken) { break; } nodes.Add(this.ParseAttribute()); } else if (this.IsPossibleAttribute()) { // report missing comma nodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); nodes.Add(this.ParseAttribute()); } else if (this.SkipBadAttributeListTokens(nodes, SyntaxKind.IdentifierToken) == PostSkipAction.Abort) { break; } } } private PostSkipAction SkipBadAttributeListTokens(SeparatedSyntaxListBuilder<AttributeSyntax> list, SyntaxKind expected) { Debug.Assert(list.Count > 0); SyntaxToken tmp = null; return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttribute(), p => p.CurrentToken.Kind == SyntaxKind.CloseBracketToken || p.IsTerminator(), expected); } private bool IsPossibleAttribute() { return this.IsTrueIdentifier(); } private AttributeSyntax ParseAttribute() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.Attribute) { return (AttributeSyntax)this.EatNode(); } var name = this.ParseQualifiedName(); var argList = this.ParseAttributeArgumentList(); return _syntaxFactory.Attribute(name, argList); } internal AttributeArgumentListSyntax ParseAttributeArgumentList() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.AttributeArgumentList) { return (AttributeArgumentListSyntax)this.EatNode(); } AttributeArgumentListSyntax argList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var openParen = this.EatToken(SyntaxKind.OpenParenToken); var argNodes = _pool.AllocateSeparated<AttributeArgumentSyntax>(); try { tryAgain: if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { if (this.IsPossibleAttributeArgument() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument argNodes.Add(this.ParseAttributeArgument()); // comma + argument or end? int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleAttributeArgument()) { argNodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); argNodes.Add(this.ParseAttributeArgument()); } else if (this.SkipBadAttributeArgumentTokens(ref openParen, argNodes, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadAttributeArgumentTokens(ref openParen, argNodes, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); argList = _syntaxFactory.AttributeArgumentList(openParen, argNodes, closeParen); } finally { _pool.Free(argNodes); } } return argList; } private PostSkipAction SkipBadAttributeArgumentTokens(ref SyntaxToken openParen, SeparatedSyntaxListBuilder<AttributeArgumentSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openParen, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttributeArgument(), p => p.CurrentToken.Kind == SyntaxKind.CloseParenToken || p.IsTerminator(), expected); } private bool IsPossibleAttributeArgument() { return this.IsPossibleExpression(); } private AttributeArgumentSyntax ParseAttributeArgument() { // Need to parse both "real" named arguments and attribute-style named arguments. // We track attribute-style named arguments only with fShouldHaveName. NameEqualsSyntax nameEquals = null; NameColonSyntax nameColon = null; if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken) { SyntaxKind nextTokenKind = this.PeekToken(1).Kind; switch (nextTokenKind) { case SyntaxKind.EqualsToken: { var name = this.ParseIdentifierToken(); var equals = this.EatToken(SyntaxKind.EqualsToken); nameEquals = _syntaxFactory.NameEquals(_syntaxFactory.IdentifierName(name), equals); } break; case SyntaxKind.ColonToken: { var name = this.ParseIdentifierName(); var colonToken = this.EatToken(SyntaxKind.ColonToken); nameColon = _syntaxFactory.NameColon(name, colonToken); nameColon = CheckFeatureAvailability(nameColon, MessageID.IDS_FeatureNamedArgument); } break; } } return _syntaxFactory.AttributeArgument( nameEquals, nameColon, this.ParseExpressionCore()); } private static DeclarationModifiers GetModifier(SyntaxToken token) => GetModifier(token.Kind, token.ContextualKind); internal static DeclarationModifiers GetModifier(SyntaxKind kind, SyntaxKind contextualKind) { switch (kind) { case SyntaxKind.PublicKeyword: return DeclarationModifiers.Public; case SyntaxKind.InternalKeyword: return DeclarationModifiers.Internal; case SyntaxKind.ProtectedKeyword: return DeclarationModifiers.Protected; case SyntaxKind.PrivateKeyword: return DeclarationModifiers.Private; case SyntaxKind.SealedKeyword: return DeclarationModifiers.Sealed; case SyntaxKind.AbstractKeyword: return DeclarationModifiers.Abstract; case SyntaxKind.StaticKeyword: return DeclarationModifiers.Static; case SyntaxKind.VirtualKeyword: return DeclarationModifiers.Virtual; case SyntaxKind.ExternKeyword: return DeclarationModifiers.Extern; case SyntaxKind.NewKeyword: return DeclarationModifiers.New; case SyntaxKind.OverrideKeyword: return DeclarationModifiers.Override; case SyntaxKind.ReadOnlyKeyword: return DeclarationModifiers.ReadOnly; case SyntaxKind.VolatileKeyword: return DeclarationModifiers.Volatile; case SyntaxKind.UnsafeKeyword: return DeclarationModifiers.Unsafe; case SyntaxKind.PartialKeyword: return DeclarationModifiers.Partial; case SyntaxKind.AsyncKeyword: return DeclarationModifiers.Async; case SyntaxKind.RefKeyword: return DeclarationModifiers.Ref; case SyntaxKind.IdentifierToken: switch (contextualKind) { case SyntaxKind.PartialKeyword: return DeclarationModifiers.Partial; case SyntaxKind.AsyncKeyword: return DeclarationModifiers.Async; } goto default; default: return DeclarationModifiers.None; } } private void ParseModifiers(SyntaxListBuilder tokens, bool forAccessors) { while (true) { var newMod = GetModifier(this.CurrentToken); if (newMod == DeclarationModifiers.None) { break; } SyntaxToken modTok; switch (newMod) { case DeclarationModifiers.Partial: var nextToken = PeekToken(1); var isPartialType = this.IsPartialType(); var isPartialMember = this.IsPartialMember(); if (isPartialType || isPartialMember) { // Standard legal cases. modTok = ConvertToKeyword(this.EatToken()); modTok = CheckFeatureAvailability(modTok, isPartialType ? MessageID.IDS_FeaturePartialTypes : MessageID.IDS_FeaturePartialMethod); } else if (nextToken.Kind == SyntaxKind.NamespaceKeyword) { // Error reported in binding modTok = ConvertToKeyword(this.EatToken()); } else if ( nextToken.Kind == SyntaxKind.EnumKeyword || nextToken.Kind == SyntaxKind.DelegateKeyword || (IsPossibleStartOfTypeDeclaration(nextToken.Kind) && GetModifier(nextToken) != DeclarationModifiers.None)) { // Misplaced partial // TODO(https://github.com/dotnet/roslyn/issues/22439): // We should consider moving this check into binding, but avoid holding on to trees modTok = AddError(ConvertToKeyword(this.EatToken()), ErrorCode.ERR_PartialMisplaced); } else { return; } break; case DeclarationModifiers.Ref: // 'ref' is only a modifier if used on a ref struct // it must be either immediately before the 'struct' // keyword, or immediately before 'partial struct' if // this is a partial ref struct declaration { var next = PeekToken(1); if (isStructOrRecordKeyword(next) || (next.ContextualKind == SyntaxKind.PartialKeyword && isStructOrRecordKeyword(PeekToken(2)))) { modTok = this.EatToken(); modTok = CheckFeatureAvailability(modTok, MessageID.IDS_FeatureRefStructs); } else if (forAccessors && this.IsPossibleAccessorModifier()) { // Accept ref as a modifier for properties and event accessors, to produce an error later during binding. modTok = this.EatToken(); } else { return; } break; } case DeclarationModifiers.Async: if (!ShouldAsyncBeTreatedAsModifier(parsingStatementNotDeclaration: false)) { return; } modTok = ConvertToKeyword(this.EatToken()); modTok = CheckFeatureAvailability(modTok, MessageID.IDS_FeatureAsync); break; default: modTok = this.EatToken(); break; } tokens.Add(modTok); } bool isStructOrRecordKeyword(SyntaxToken token) { if (token.Kind == SyntaxKind.StructKeyword) { return true; } if (token.ContextualKind == SyntaxKind.RecordKeyword) { // This is an unusual use of LangVersion. Normally we only produce errors when the langversion // does not support a feature, but in this case we are effectively making a language breaking // change to consider "record" a type declaration in all ambiguous cases. To avoid breaking // older code that is not using C# 9 we conditionally parse based on langversion return IsFeatureEnabled(MessageID.IDS_FeatureRecords); } return false; } } private bool ShouldAsyncBeTreatedAsModifier(bool parsingStatementNotDeclaration) { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword); // Adapted from CParser::IsAsyncMethod. if (IsNonContextualModifier(PeekToken(1))) { // If the next token is a (non-contextual) modifier keyword, then this token is // definitely the async keyword return true; } // Some of our helpers start at the current token, so we'll have to advance for their // sake and then backtrack when we're done. Don't leave this block without releasing // the reset point. ResetPoint resetPoint = GetResetPoint(); try { this.EatToken(); //move past contextual 'async' if (!parsingStatementNotDeclaration && (this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword)) { this.EatToken(); // "partial" doesn't affect our decision, so look past it. } // Comment directly from CParser::IsAsyncMethod. // ... 'async' [partial] <typedecl> ... // ... 'async' [partial] <event> ... // ... 'async' [partial] <implicit> <operator> ... // ... 'async' [partial] <explicit> <operator> ... // ... 'async' [partial] <typename> <operator> ... // ... 'async' [partial] <typename> <membername> ... // DEVNOTE: Although we parse async user defined conversions, operators, etc. here, // anything other than async methods are detected as erroneous later, during the define phase if (!parsingStatementNotDeclaration) { var ctk = this.CurrentToken.Kind; if (IsPossibleStartOfTypeDeclaration(ctk) || ctk == SyntaxKind.EventKeyword || ((ctk == SyntaxKind.ExplicitKeyword || ctk == SyntaxKind.ImplicitKeyword) && PeekToken(1).Kind == SyntaxKind.OperatorKeyword)) { return true; } } if (ScanType() != ScanTypeFlags.NotType) { // We've seen "async TypeName". Now we have to determine if we should we treat // 'async' as a modifier. Or is the user actually writing something like // "public async Goo" where 'async' is actually the return type. if (IsPossibleMemberName()) { // we have: "async Type X" or "async Type this", 'async' is definitely a // modifier here. return true; } var currentTokenKind = this.CurrentToken.Kind; // The file ends with "async TypeName", it's not legal code, and it's much // more likely that this is meant to be a modifier. if (currentTokenKind == SyntaxKind.EndOfFileToken) { return true; } // "async TypeName }". In this case, we just have an incomplete member, and // we should definitely default to 'async' being considered a return type here. if (currentTokenKind == SyntaxKind.CloseBraceToken) { return true; } // "async TypeName void". In this case, we just have an incomplete member before // an existing member. Treat this 'async' as a keyword. if (SyntaxFacts.IsPredefinedType(this.CurrentToken.Kind)) { return true; } // "async TypeName public". In this case, we just have an incomplete member before // an existing member. Treat this 'async' as a keyword. if (IsNonContextualModifier(this.CurrentToken)) { return true; } // "async TypeName class". In this case, we just have an incomplete member before // an existing type declaration. Treat this 'async' as a keyword. if (IsTypeDeclarationStart()) { return true; } // "async TypeName namespace". In this case, we just have an incomplete member before // an existing namespace declaration. Treat this 'async' as a keyword. if (currentTokenKind == SyntaxKind.NamespaceKeyword) { return true; } if (!parsingStatementNotDeclaration && currentTokenKind == SyntaxKind.OperatorKeyword) { return true; } } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } return false; } private static bool IsNonContextualModifier(SyntaxToken nextToken) { return GetModifier(nextToken) != DeclarationModifiers.None && !SyntaxFacts.IsContextualKeyword(nextToken.ContextualKind); } private bool IsPartialType() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword); var nextToken = this.PeekToken(1); switch (nextToken.Kind) { case SyntaxKind.StructKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.InterfaceKeyword: return true; } if (nextToken.ContextualKind == SyntaxKind.RecordKeyword) { // This is an unusual use of LangVersion. Normally we only produce errors when the langversion // does not support a feature, but in this case we are effectively making a language breaking // change to consider "record" a type declaration in all ambiguous cases. To avoid breaking // older code that is not using C# 9 we conditionally parse based on langversion return IsFeatureEnabled(MessageID.IDS_FeatureRecords); } return false; } private bool IsPartialMember() { // note(cyrusn): this could have been written like so: // // return // this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword && // this.PeekToken(1).Kind == SyntaxKind.VoidKeyword; // // However, we want to be lenient and allow the user to write // 'partial' in most modifier lists. We will then provide them with // a more specific message later in binding that they are doing // something wrong. // // Some might argue that the simple check would suffice. // However, we'd like to maintain behavior with // previously shipped versions, and so we're keeping this code. // Here we check for: // partial ReturnType MemberName Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword); var point = this.GetResetPoint(); try { this.EatToken(); // partial if (this.ScanType() == ScanTypeFlags.NotType) { return false; } return IsPossibleMemberName(); } finally { this.Reset(ref point); this.Release(ref point); } } private bool IsPossibleMemberName() { switch (this.CurrentToken.Kind) { case SyntaxKind.IdentifierToken: if (this.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword && this.PeekToken(1).Kind == SyntaxKind.UsingKeyword) { return false; } return true; case SyntaxKind.ThisKeyword: return true; default: return false; } } private MemberDeclarationSyntax ParseTypeDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); cancellationToken.ThrowIfCancellationRequested(); switch (this.CurrentToken.Kind) { case SyntaxKind.ClassKeyword: // report use of "static class" if feature is unsupported CheckForVersionSpecificModifiers(modifiers, SyntaxKind.StaticKeyword, MessageID.IDS_FeatureStaticClasses); return this.ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers); case SyntaxKind.StructKeyword: // report use of "readonly struct" if feature is unsupported CheckForVersionSpecificModifiers(modifiers, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyStructs); return this.ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers); case SyntaxKind.InterfaceKeyword: return this.ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers); case SyntaxKind.DelegateKeyword: return this.ParseDelegateDeclaration(attributes, modifiers); case SyntaxKind.EnumKeyword: return this.ParseEnumDeclaration(attributes, modifiers); case SyntaxKind.IdentifierToken: Debug.Assert(CurrentToken.ContextualKind == SyntaxKind.RecordKeyword); return ParseClassOrStructOrInterfaceDeclaration(attributes, modifiers); default: throw ExceptionUtilities.UnexpectedValue(this.CurrentToken.Kind); } } /// <summary> /// checks for modifiers whose feature is not available /// </summary> private void CheckForVersionSpecificModifiers(SyntaxListBuilder modifiers, SyntaxKind kind, MessageID feature) { for (int i = 0, n = modifiers.Count; i < n; i++) { if (modifiers[i].RawKind == (int)kind) { modifiers[i] = CheckFeatureAvailability(modifiers[i], feature); } } } #nullable enable private TypeDeclarationSyntax ParseClassOrStructOrInterfaceDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ClassKeyword || this.CurrentToken.Kind == SyntaxKind.StructKeyword || this.CurrentToken.Kind == SyntaxKind.InterfaceKeyword || CurrentToken.ContextualKind == SyntaxKind.RecordKeyword); // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); var keyword = ConvertToKeyword(this.EatToken()); var outerSaveTerm = _termState; SyntaxToken? recordModifier = null; if (keyword.Kind == SyntaxKind.RecordKeyword) { _termState |= TerminatorState.IsEndOfRecordSignature; recordModifier = eatRecordModifierIfAvailable(); } var saveTerm = _termState; _termState |= TerminatorState.IsPossibleAggregateClauseStartOrStop; var name = this.ParseIdentifierToken(); var typeParameters = this.ParseTypeParameterList(); var paramList = keyword.Kind == SyntaxKind.RecordKeyword && CurrentToken.Kind == SyntaxKind.OpenParenToken ? ParseParenthesizedParameterList() : null; var baseList = this.ParseBaseList(); _termState = saveTerm; // Parse class body bool parseMembers = true; SyntaxListBuilder<MemberDeclarationSyntax> members = default; SyntaxListBuilder<TypeParameterConstraintClauseSyntax> constraints = default; try { if (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { constraints = _pool.Allocate<TypeParameterConstraintClauseSyntax>(); this.ParseTypeParameterConstraintClauses(constraints); } _termState = outerSaveTerm; SyntaxToken semicolon; SyntaxToken? openBrace; SyntaxToken? closeBrace; if (!(keyword.Kind == SyntaxKind.RecordKeyword) || CurrentToken.Kind != SyntaxKind.SemicolonToken) { openBrace = this.EatToken(SyntaxKind.OpenBraceToken); // ignore members if missing type name or missing open curly if (name.IsMissing || openBrace.IsMissing) { parseMembers = false; } // even if we saw a { or think we should parse members bail out early since // we know namespaces can't be nested inside types if (parseMembers) { members = _pool.Allocate<MemberDeclarationSyntax>(); while (true) { SyntaxKind kind = this.CurrentToken.Kind; if (CanStartMember(kind)) { // This token can start a member -- go parse it var saveTerm2 = _termState; _termState |= TerminatorState.IsPossibleMemberStartOrStop; var member = this.ParseMemberDeclaration(keyword.Kind); if (member != null) { // statements are accepted here, a semantic error will be reported later members.Add(member); } else { // we get here if we couldn't parse the lookahead as a statement or a declaration (we haven't consumed any tokens): this.SkipBadMemberListTokens(ref openBrace, members); } _termState = saveTerm2; } else if (kind == SyntaxKind.CloseBraceToken || kind == SyntaxKind.EndOfFileToken || this.IsTerminator()) { // This marks the end of members of this class break; } else { // Error -- try to sync up with intended reality this.SkipBadMemberListTokens(ref openBrace, members); } } } if (openBrace.IsMissing) { closeBrace = SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken); closeBrace = WithAdditionalDiagnostics(closeBrace, this.GetExpectedTokenError(SyntaxKind.CloseBraceToken, this.CurrentToken.Kind)); } else { closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); } semicolon = TryEatToken(SyntaxKind.SemicolonToken); } else { semicolon = CheckFeatureAvailability(EatToken(SyntaxKind.SemicolonToken), MessageID.IDS_FeatureRecords); openBrace = null; closeBrace = null; } return constructTypeDeclaration(_syntaxFactory, attributes, modifiers, keyword, recordModifier, name, typeParameters, paramList, baseList, constraints, openBrace, members, closeBrace, semicolon); } finally { if (!members.IsNull) { _pool.Free(members); } if (!constraints.IsNull) { _pool.Free(constraints); } } SyntaxToken? eatRecordModifierIfAvailable() { Debug.Assert(keyword.Kind == SyntaxKind.RecordKeyword); if (CurrentToken.Kind is SyntaxKind.ClassKeyword or SyntaxKind.StructKeyword) { var result = EatToken(); result = CheckFeatureAvailability(result, MessageID.IDS_FeatureRecordStructs); return result; } return null; } static TypeDeclarationSyntax constructTypeDeclaration(ContextAwareSyntax syntaxFactory, SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxToken keyword, SyntaxToken? recordModifier, SyntaxToken name, TypeParameterListSyntax typeParameters, ParameterListSyntax? paramList, BaseListSyntax baseList, SyntaxListBuilder<TypeParameterConstraintClauseSyntax> constraints, SyntaxToken? openBrace, SyntaxListBuilder<MemberDeclarationSyntax> members, SyntaxToken? closeBrace, SyntaxToken semicolon) { var modifiersList = (SyntaxList<SyntaxToken>)modifiers.ToList(); var membersList = (SyntaxList<MemberDeclarationSyntax>)members; var constraintsList = (SyntaxList<TypeParameterConstraintClauseSyntax>)constraints; switch (keyword.Kind) { case SyntaxKind.ClassKeyword: RoslynDebug.Assert(paramList is null); RoslynDebug.Assert(openBrace != null); RoslynDebug.Assert(closeBrace != null); return syntaxFactory.ClassDeclaration( attributes, modifiersList, keyword, name, typeParameters, baseList, constraintsList, openBrace, membersList, closeBrace, semicolon); case SyntaxKind.StructKeyword: RoslynDebug.Assert(paramList is null); RoslynDebug.Assert(openBrace != null); RoslynDebug.Assert(closeBrace != null); return syntaxFactory.StructDeclaration( attributes, modifiersList, keyword, name, typeParameters, baseList, constraintsList, openBrace, membersList, closeBrace, semicolon); case SyntaxKind.InterfaceKeyword: RoslynDebug.Assert(paramList is null); RoslynDebug.Assert(openBrace != null); RoslynDebug.Assert(closeBrace != null); return syntaxFactory.InterfaceDeclaration( attributes, modifiersList, keyword, name, typeParameters, baseList, constraintsList, openBrace, membersList, closeBrace, semicolon); case SyntaxKind.RecordKeyword: // record struct ... // record ... // record class ... SyntaxKind declarationKind = recordModifier?.Kind == SyntaxKind.StructKeyword ? SyntaxKind.RecordStructDeclaration : SyntaxKind.RecordDeclaration; return syntaxFactory.RecordDeclaration( declarationKind, attributes, modifiers.ToList(), keyword, classOrStructKeyword: recordModifier, name, typeParameters, paramList, baseList, constraints, openBrace, members, closeBrace, semicolon); default: throw ExceptionUtilities.UnexpectedValue(keyword.Kind); } } } #nullable disable private void SkipBadMemberListTokens(ref SyntaxToken openBrace, SyntaxListBuilder members) { if (members.Count > 0) { var tmp = members[members.Count - 1]; this.SkipBadMemberListTokens(ref tmp); members[members.Count - 1] = tmp; } else { GreenNode tmp = openBrace; this.SkipBadMemberListTokens(ref tmp); openBrace = (SyntaxToken)tmp; } } private void SkipBadMemberListTokens(ref GreenNode previousNode) { int curlyCount = 0; var tokens = _pool.Allocate(); try { bool done = false; // always consume at least one token. var token = this.EatToken(); token = this.AddError(token, ErrorCode.ERR_InvalidMemberDecl, token.Text); tokens.Add(token); while (!done) { SyntaxKind kind = this.CurrentToken.Kind; // If this token can start a member, we're done if (CanStartMember(kind) && !(kind == SyntaxKind.DelegateKeyword && (this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken || this.PeekToken(1).Kind == SyntaxKind.OpenParenToken))) { done = true; continue; } // <UNDONE> UNDONE: Seems like this makes sense, // but if this token can start a namespace element, but not a member, then // perhaps we should bail back up to parsing a namespace body somehow...</UNDONE> // Watch curlies and look for end of file/close curly switch (kind) { case SyntaxKind.OpenBraceToken: curlyCount++; break; case SyntaxKind.CloseBraceToken: if (curlyCount-- == 0) { done = true; continue; } break; case SyntaxKind.EndOfFileToken: done = true; continue; default: break; } tokens.Add(this.EatToken()); } previousNode = AddTrailingSkippedSyntax((CSharpSyntaxNode)previousNode, tokens.ToListNode()); } finally { _pool.Free(tokens); } } private bool IsPossibleMemberStartOrStop() { return this.IsPossibleMemberStart() || this.CurrentToken.Kind == SyntaxKind.CloseBraceToken; } private bool IsPossibleAggregateClauseStartOrStop() { return this.CurrentToken.Kind == SyntaxKind.ColonToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.IsCurrentTokenWhereOfConstraintClause(); } private BaseListSyntax ParseBaseList() { if (this.CurrentToken.Kind != SyntaxKind.ColonToken) { return null; } var colon = this.EatToken(); var list = _pool.AllocateSeparated<BaseTypeSyntax>(); try { // first type TypeSyntax firstType = this.ParseType(); ArgumentListSyntax argumentList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { argumentList = this.ParseParenthesizedArgumentList(); } list.Add(argumentList is object ? _syntaxFactory.PrimaryConstructorBaseType(firstType, argumentList) : (BaseTypeSyntax)_syntaxFactory.SimpleBaseType(firstType)); // any additional types while (true) { if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || ((_termState & TerminatorState.IsEndOfRecordSignature) != 0 && this.CurrentToken.Kind == SyntaxKind.SemicolonToken) || this.IsCurrentTokenWhereOfConstraintClause()) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleType()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); list.Add(_syntaxFactory.SimpleBaseType(this.ParseType())); continue; } else if (this.SkipBadBaseListTokens(ref colon, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } return _syntaxFactory.BaseList(colon, list); } finally { _pool.Free(list); } } private PostSkipAction SkipBadBaseListTokens(ref SyntaxToken colon, SeparatedSyntaxListBuilder<BaseTypeSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref colon, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleAttribute(), p => p.CurrentToken.Kind == SyntaxKind.OpenBraceToken || p.IsCurrentTokenWhereOfConstraintClause() || p.IsTerminator(), expected); } private bool IsCurrentTokenWhereOfConstraintClause() { return this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword && this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && this.PeekToken(2).Kind == SyntaxKind.ColonToken; } private void ParseTypeParameterConstraintClauses(SyntaxListBuilder list) { while (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { list.Add(this.ParseTypeParameterConstraintClause()); } } private TypeParameterConstraintClauseSyntax ParseTypeParameterConstraintClause() { var where = this.EatContextualToken(SyntaxKind.WhereKeyword); var name = !IsTrueIdentifier() ? this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected) : this.ParseIdentifierName(); var colon = this.EatToken(SyntaxKind.ColonToken); var bounds = _pool.AllocateSeparated<TypeParameterConstraintSyntax>(); try { // first bound if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.IsCurrentTokenWhereOfConstraintClause()) { bounds.Add(_syntaxFactory.TypeConstraint(this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_TypeExpected))); } else { bounds.Add(this.ParseTypeParameterConstraint()); // remaining bounds while (true) { if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || ((_termState & TerminatorState.IsEndOfRecordSignature) != 0 && this.CurrentToken.Kind == SyntaxKind.SemicolonToken) || this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken || this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleTypeParameterConstraint()) { bounds.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); if (this.IsCurrentTokenWhereOfConstraintClause()) { bounds.Add(_syntaxFactory.TypeConstraint(this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_TypeExpected))); break; } else { bounds.Add(this.ParseTypeParameterConstraint()); } } else if (this.SkipBadTypeParameterConstraintTokens(bounds, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } return _syntaxFactory.TypeParameterConstraintClause(where, name, colon, bounds); } finally { _pool.Free(bounds); } } private bool IsPossibleTypeParameterConstraint() { switch (this.CurrentToken.Kind) { case SyntaxKind.NewKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.StructKeyword: case SyntaxKind.DefaultKeyword: return true; case SyntaxKind.IdentifierToken: return this.IsTrueIdentifier(); default: return IsPredefinedType(this.CurrentToken.Kind); } } private TypeParameterConstraintSyntax ParseTypeParameterConstraint() { SyntaxToken questionToken = null; var syntaxKind = this.CurrentToken.Kind; switch (this.CurrentToken.Kind) { case SyntaxKind.NewKeyword: var newToken = this.EatToken(); var open = this.EatToken(SyntaxKind.OpenParenToken); var close = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.ConstructorConstraint(newToken, open, close); case SyntaxKind.StructKeyword: var structToken = this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.QuestionToken) { questionToken = this.EatToken(); questionToken = this.AddError(questionToken, ErrorCode.ERR_UnexpectedToken, questionToken.Text); } return _syntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint, structToken, questionToken); case SyntaxKind.ClassKeyword: var classToken = this.EatToken(); questionToken = this.TryEatToken(SyntaxKind.QuestionToken); return _syntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint, classToken, questionToken); case SyntaxKind.DefaultKeyword: var defaultToken = this.EatToken(); return CheckFeatureAvailability(_syntaxFactory.DefaultConstraint(defaultToken), MessageID.IDS_FeatureDefaultTypeParameterConstraint); default: var type = this.ParseType(); return _syntaxFactory.TypeConstraint(type); } } private PostSkipAction SkipBadTypeParameterConstraintTokens(SeparatedSyntaxListBuilder<TypeParameterConstraintSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleTypeParameterConstraint(), p => p.CurrentToken.Kind == SyntaxKind.OpenBraceToken || p.IsCurrentTokenWhereOfConstraintClause() || p.IsTerminator(), expected); } private bool IsPossibleMemberStart() { return CanStartMember(this.CurrentToken.Kind); } private static bool CanStartMember(SyntaxKind kind) { switch (kind) { case SyntaxKind.AbstractKeyword: case SyntaxKind.BoolKeyword: case SyntaxKind.ByteKeyword: case SyntaxKind.CharKeyword: case SyntaxKind.ClassKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DecimalKeyword: case SyntaxKind.DelegateKeyword: case SyntaxKind.DoubleKeyword: case SyntaxKind.EnumKeyword: case SyntaxKind.EventKeyword: case SyntaxKind.ExternKeyword: case SyntaxKind.FixedKeyword: case SyntaxKind.FloatKeyword: case SyntaxKind.IntKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.LongKeyword: case SyntaxKind.NewKeyword: case SyntaxKind.ObjectKeyword: case SyntaxKind.OverrideKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PublicKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.SByteKeyword: case SyntaxKind.SealedKeyword: case SyntaxKind.ShortKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.StructKeyword: case SyntaxKind.UIntKeyword: case SyntaxKind.ULongKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.UShortKeyword: case SyntaxKind.VirtualKeyword: case SyntaxKind.VoidKeyword: case SyntaxKind.VolatileKeyword: case SyntaxKind.IdentifierToken: case SyntaxKind.TildeToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.ImplicitKeyword: case SyntaxKind.ExplicitKeyword: case SyntaxKind.OpenParenToken: //tuple case SyntaxKind.RefKeyword: return true; default: return false; } } private bool IsTypeDeclarationStart() { switch (this.CurrentToken.Kind) { case SyntaxKind.ClassKeyword: case SyntaxKind.DelegateKeyword when !IsFunctionPointerStart(): case SyntaxKind.EnumKeyword: case SyntaxKind.InterfaceKeyword: case SyntaxKind.StructKeyword: return true; case SyntaxKind.IdentifierToken: if (CurrentToken.ContextualKind == SyntaxKind.RecordKeyword) { // This is an unusual use of LangVersion. Normally we only produce errors when the langversion // does not support a feature, but in this case we are effectively making a language breaking // change to consider "record" a type declaration in all ambiguous cases. To avoid breaking // older code that is not using C# 9 we conditionally parse based on langversion return IsFeatureEnabled(MessageID.IDS_FeatureRecords); } return false; default: return false; } } private bool CanReuseMemberDeclaration(SyntaxKind kind, bool isGlobal) { switch (kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return true; case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: if (!isGlobal || IsScript) { return true; } // We can reuse original nodes if they came from the global context as well. return (this.CurrentNode.Parent is Syntax.CompilationUnitSyntax); case SyntaxKind.GlobalStatement: return isGlobal; default: return false; } } public MemberDeclarationSyntax ParseMemberDeclaration() { // Use a parent kind that causes inclusion of only member declarations that could appear in a struct // e.g. including fixed member declarations, but not statements. const SyntaxKind parentKind = SyntaxKind.StructDeclaration; return ParseWithStackGuard( () => this.ParseMemberDeclaration(parentKind), () => createEmptyNodeFunc()); // Creates a dummy declaration node to which we can attach a stack overflow message MemberDeclarationSyntax createEmptyNodeFunc() { return _syntaxFactory.IncompleteMember( new SyntaxList<AttributeListSyntax>(), new SyntaxList<SyntaxToken>(), CreateMissingIdentifierName() ); } } // Returns null if we can't parse anything (even partially). internal MemberDeclarationSyntax ParseMemberDeclarationOrStatement(SyntaxKind parentKind) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); var result = ParseMemberDeclarationOrStatementCore(parentKind); _recursionDepth--; return result; } /// <summary> /// Changes in this function around member parsing should be mirrored in <see cref="ParseMemberDeclarationCore"/>. /// Try keeping structure of both functions similar to simplify this task. The split was made to /// reduce the stack usage during recursive parsing. /// </summary> /// <returns>Returns null if we can't parse anything (even partially).</returns> private MemberDeclarationSyntax ParseMemberDeclarationOrStatementCore(SyntaxKind parentKind) { // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); Debug.Assert(parentKind == SyntaxKind.CompilationUnit); cancellationToken.ThrowIfCancellationRequested(); // don't reuse members if they were previously declared under a different type keyword kind if (this.IsIncrementalAndFactoryContextMatches) { if (CanReuseMemberDeclaration(CurrentNodeKind, isGlobal: true)) { return (MemberDeclarationSyntax)this.EatNode(); } } var saveTermState = _termState; var attributes = this.ParseAttributeDeclarations(); bool haveAttributes = (attributes.Count > 0); var afterAttributesPoint = this.GetResetPoint(); var modifiers = _pool.Allocate(); try { // // Check for the following cases to disambiguate between member declarations and expressions. // Doing this before parsing modifiers simplifies further analysis since some of these keywords can act as modifiers as well. // // unsafe { ... } // fixed (...) { ... } // delegate (...) { ... } // delegate { ... } // new { ... } // new[] { ... } // new T (...) // new T [...] // if (!haveAttributes || !IsScript) { bool wasInAsync = IsInAsync; if (!IsScript) { IsInAsync = true; // We are implicitly in an async context } try { switch (this.CurrentToken.Kind) { case SyntaxKind.UnsafeKeyword: if (this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken) { return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(ParseUnsafeStatement(attributes))); } break; case SyntaxKind.FixedKeyword: if (this.PeekToken(1).Kind == SyntaxKind.OpenParenToken) { return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(ParseFixedStatement(attributes))); } break; case SyntaxKind.DelegateKeyword: switch (this.PeekToken(1).Kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.OpenBraceToken: return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(ParseExpressionStatement(attributes))); } break; case SyntaxKind.NewKeyword: if (IsPossibleNewExpression()) { return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(ParseExpressionStatement(attributes))); } break; } } finally { IsInAsync = wasInAsync; } } // All modifiers that might start an expression are processed above. this.ParseModifiers(modifiers, forAccessors: false); bool haveModifiers = (modifiers.Count > 0); MemberDeclarationSyntax result; // Check for constructor form if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.OpenParenToken) { // Script: // Constructor definitions are not allowed. We parse them as method calls with semicolon missing error: // // Script(...) { ... } // ^ // missing ';' // // Unless modifiers or attributes are present this is more likely to be a method call than a method definition. if (haveAttributes || haveModifiers) { var token = SyntaxFactory.MissingToken(SyntaxKind.VoidKeyword); token = this.AddError(token, ErrorCode.ERR_MemberNeedsType); var voidType = _syntaxFactory.PredefinedType(token); if (!IsScript) { if (tryParseLocalDeclarationStatementFromStartPoint<LocalFunctionStatementSyntax>(attributes, ref afterAttributesPoint, out result)) { return result; } } else { var identifier = this.EatToken(); return this.ParseMethodDeclaration(attributes, modifiers, voidType, explicitInterfaceOpt: null, identifier: identifier, typeParameterList: null); } } } // Destructors are disallowed in global code, skipping check for them. // TODO: better error messages for script // Check for constant if (this.CurrentToken.Kind == SyntaxKind.ConstKeyword) { if (!IsScript && tryParseLocalDeclarationStatementFromStartPoint<LocalDeclarationStatementSyntax>(attributes, ref afterAttributesPoint, out result)) { return result; } // Prefers const field over const local variable decl return this.ParseConstantFieldDeclaration(attributes, modifiers, parentKind); } // Check for event. if (this.CurrentToken.Kind == SyntaxKind.EventKeyword) { return this.ParseEventDeclaration(attributes, modifiers, parentKind); } // check for fixed size buffers. if (this.CurrentToken.Kind == SyntaxKind.FixedKeyword) { return this.ParseFixedSizeBufferDeclaration(attributes, modifiers, parentKind); } // Check for conversion operators (implicit/explicit) result = this.TryParseConversionOperatorDeclaration(attributes, modifiers); if (result is not null) { return result; } if (this.CurrentToken.Kind == SyntaxKind.NamespaceKeyword) { return ParseNamespaceDeclaration(attributes, modifiers); } // It's valid to have a type declaration here -- check for those if (IsTypeDeclarationStart()) { return this.ParseTypeDeclaration(attributes, modifiers); } TypeSyntax type = ParseReturnType(); var afterTypeResetPoint = this.GetResetPoint(); try { // Try as a regular statement rather than a member declaration, if appropriate. if ((!haveAttributes || !IsScript) && !haveModifiers && (type.Kind == SyntaxKind.RefType || !IsOperatorStart(out _, advanceParser: false))) { this.Reset(ref afterAttributesPoint); if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken && this.CurrentToken.Kind != SyntaxKind.EndOfFileToken && this.IsPossibleStatement(acceptAccessibilityMods: true)) { var saveTerm = _termState; _termState |= TerminatorState.IsPossibleStatementStartOrStop; // partial statements can abort if a new statement starts bool wasInAsync = IsInAsync; if (!IsScript) { IsInAsync = true; // We are implicitly in an async context } // In Script we don't allow local declaration statements at the top level. We want // to fall out below and parse them instead as fields. For top-level statements, we allow // them, but want to try properties , etc. first. var statement = this.ParseStatementCore(attributes, isGlobal: true); IsInAsync = wasInAsync; _termState = saveTerm; if (isAcceptableNonDeclarationStatement(statement, IsScript)) { return CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(statement)); } } this.Reset(ref afterTypeResetPoint); } // Everything that's left -- methods, fields, properties, locals, // indexers, and non-conversion operators -- starts with a type // (possibly void). // Check for misplaced modifiers. if we see any, then consider this member // terminated and restart parsing. if (IsMisplacedModifier(modifiers, attributes, type, out result)) { return result; } parse_member_name:; // If we've seen the ref keyword, we know we must have an indexer, method, property, or local. bool typeIsRef = type.IsRef; ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; // Check here for operators // Allow old-style implicit/explicit casting operator syntax, just so we can give a better error if (!typeIsRef && IsOperatorStart(out explicitInterfaceOpt)) { return this.ParseOperatorDeclaration(attributes, modifiers, type, explicitInterfaceOpt); } if ((!typeIsRef || !IsScript) && IsFieldDeclaration(isEvent: false)) { var saveTerm = _termState; if ((!haveAttributes && !haveModifiers) || !IsScript) { // if we are at top-level then statements can occur _termState |= TerminatorState.IsPossibleStatementStartOrStop; if (!IsScript) { this.Reset(ref afterAttributesPoint); if (tryParseLocalDeclarationStatement<LocalDeclarationStatementSyntax>(attributes, out result)) { return result; } this.Reset(ref afterTypeResetPoint); } } if (!typeIsRef) { return this.ParseNormalFieldDeclaration(attributes, modifiers, type, parentKind); } else { _termState = saveTerm; } } // At this point we can either have indexers, methods, or // properties (or something unknown). Try to break apart // the following name and determine what to do from there. SyntaxToken identifierOrThisOpt; TypeParameterListSyntax typeParameterListOpt; this.ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterListOpt, isEvent: false); // First, check if we got absolutely nothing. If so, then // We need to consume a bad member and try again. if (IsNoneOrIncompleteMember(parentKind, attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) { return result; } // If the modifiers did not include "async", and the type we got was "async", and there was an // error in the identifier or its type parameters, then the user is probably in the midst of typing // an async method. In that case we reconsider "async" to be a modifier, and treat the identifier // (with the type parameters) as the type (with type arguments). Then we go back to looking for // the member name again. // For example, if we get // async Task< // then we want async to be a modifier and Task<MISSING> to be a type. if (ReconsideredTypeAsAsyncModifier(ref modifiers, ref type, ref afterTypeResetPoint, ref explicitInterfaceOpt, ref identifierOrThisOpt, ref typeParameterListOpt)) { goto parse_member_name; } Debug.Assert(identifierOrThisOpt != null); // check availability of readonly members feature for indexers, properties and methods CheckForVersionSpecificModifiers(modifiers, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyMembers); if (TryParseIndexerOrPropertyDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) { return result; } // treat anything else as a method. if (!IsScript && explicitInterfaceOpt is null && tryParseLocalDeclarationStatementFromStartPoint<LocalFunctionStatementSyntax>(attributes, ref afterAttributesPoint, out result)) { return result; } return this.ParseMethodDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); } finally { this.Release(ref afterTypeResetPoint); } } finally { _pool.Free(modifiers); _termState = saveTermState; this.Release(ref afterAttributesPoint); } bool tryParseLocalDeclarationStatement<DeclarationSyntax>(SyntaxList<AttributeListSyntax> attributes, out MemberDeclarationSyntax result) where DeclarationSyntax : StatementSyntax { bool wasInAsync = IsInAsync; IsInAsync = true; // We are implicitly in an async context int lastTokenPosition = -1; IsMakingProgress(ref lastTokenPosition); var topLevelStatement = ParseLocalDeclarationStatement(attributes); IsInAsync = wasInAsync; if (topLevelStatement is DeclarationSyntax declaration && IsMakingProgress(ref lastTokenPosition, assertIfFalse: false)) { result = CheckTopLevelStatementsFeatureAvailability(_syntaxFactory.GlobalStatement(declaration)); return true; } result = null; return false; } bool tryParseLocalDeclarationStatementFromStartPoint<DeclarationSyntax>(SyntaxList<AttributeListSyntax> attributes, ref ResetPoint startPoint, out MemberDeclarationSyntax result) where DeclarationSyntax : StatementSyntax { var resetOnFailurePoint = this.GetResetPoint(); try { this.Reset(ref startPoint); if (tryParseLocalDeclarationStatement<DeclarationSyntax>(attributes, out result)) { return true; } this.Reset(ref resetOnFailurePoint); return false; } finally { this.Release(ref resetOnFailurePoint); } } static bool isAcceptableNonDeclarationStatement(StatementSyntax statement, bool isScript) { switch (statement?.Kind) { case null: case SyntaxKind.LocalFunctionStatement: case SyntaxKind.ExpressionStatement when !isScript && // Do not parse a single identifier as an expression statement in a Simple Program, this could be a beginning of a keyword and // we want completion to offer it. ((ExpressionStatementSyntax)statement) is var exprStatement && exprStatement.Expression.Kind == SyntaxKind.IdentifierName && exprStatement.SemicolonToken.IsMissing: return false; case SyntaxKind.LocalDeclarationStatement: return !isScript && ((LocalDeclarationStatementSyntax)statement).UsingKeyword is object; default: return true; } } } private bool IsMisplacedModifier(SyntaxListBuilder modifiers, SyntaxList<AttributeListSyntax> attributes, TypeSyntax type, out MemberDeclarationSyntax result) { if (GetModifier(this.CurrentToken) != DeclarationModifiers.None && this.CurrentToken.ContextualKind != SyntaxKind.PartialKeyword && this.CurrentToken.ContextualKind != SyntaxKind.AsyncKeyword && IsComplete(type)) { var misplacedModifier = this.CurrentToken; type = this.AddError( type, type.FullWidth + misplacedModifier.GetLeadingTriviaWidth(), misplacedModifier.Width, ErrorCode.ERR_BadModifierLocation, misplacedModifier.Text); result = _syntaxFactory.IncompleteMember(attributes, modifiers.ToList(), type); return true; } result = null; return false; } private bool IsNoneOrIncompleteMember(SyntaxKind parentKind, SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifierOrThisOpt, TypeParameterListSyntax typeParameterListOpt, out MemberDeclarationSyntax result) { if (explicitInterfaceOpt == null && identifierOrThisOpt == null && typeParameterListOpt == null) { if (attributes.Count == 0 && modifiers.Count == 0 && type.IsMissing && type.Kind != SyntaxKind.RefType) { // we haven't advanced, the caller needs to consume the tokens ahead result = null; return true; } var incompleteMember = _syntaxFactory.IncompleteMember(attributes, modifiers.ToList(), type.IsMissing ? null : type); if (incompleteMember.ContainsDiagnostics) { result = incompleteMember; } else if (parentKind is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || parentKind == SyntaxKind.CompilationUnit && !IsScript) { result = this.AddErrorToLastToken(incompleteMember, ErrorCode.ERR_NamespaceUnexpected); } else { //the error position should indicate CurrentToken result = this.AddError( incompleteMember, incompleteMember.FullWidth + this.CurrentToken.GetLeadingTriviaWidth(), this.CurrentToken.Width, ErrorCode.ERR_InvalidMemberDecl, this.CurrentToken.Text); } return true; } result = null; return false; } private bool ReconsideredTypeAsAsyncModifier(ref SyntaxListBuilder modifiers, ref TypeSyntax type, ref ResetPoint afterTypeResetPoint, ref ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, ref SyntaxToken identifierOrThisOpt, ref TypeParameterListSyntax typeParameterListOpt) { if (type.Kind != SyntaxKind.RefType && identifierOrThisOpt != null && (typeParameterListOpt != null && typeParameterListOpt.ContainsDiagnostics || this.CurrentToken.Kind != SyntaxKind.OpenParenToken && this.CurrentToken.Kind != SyntaxKind.OpenBraceToken && this.CurrentToken.Kind != SyntaxKind.EqualsGreaterThanToken) && ReconsiderTypeAsAsyncModifier(ref modifiers, type, identifierOrThisOpt)) { this.Reset(ref afterTypeResetPoint); explicitInterfaceOpt = null; identifierOrThisOpt = null; typeParameterListOpt = null; this.Release(ref afterTypeResetPoint); type = ParseReturnType(); afterTypeResetPoint = this.GetResetPoint(); return true; } return false; } private bool TryParseIndexerOrPropertyDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifierOrThisOpt, TypeParameterListSyntax typeParameterListOpt, out MemberDeclarationSyntax result) { if (identifierOrThisOpt.Kind == SyntaxKind.ThisKeyword) { result = this.ParseIndexerDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); return true; } switch (this.CurrentToken.Kind) { case SyntaxKind.OpenBraceToken: case SyntaxKind.EqualsGreaterThanToken: result = this.ParsePropertyDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); return true; } result = null; return false; } // Returns null if we can't parse anything (even partially). internal MemberDeclarationSyntax ParseMemberDeclaration(SyntaxKind parentKind) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); var result = ParseMemberDeclarationCore(parentKind); _recursionDepth--; return result; } /// <summary> /// Changes in this function should be mirrored in <see cref="ParseMemberDeclarationOrStatementCore"/>. /// Try keeping structure of both functions similar to simplify this task. The split was made to /// reduce the stack usage during recursive parsing. /// </summary> /// <returns>Returns null if we can't parse anything (even partially).</returns> private MemberDeclarationSyntax ParseMemberDeclarationCore(SyntaxKind parentKind) { // "top-level" expressions and statements should never occur inside an asynchronous context Debug.Assert(!IsInAsync); Debug.Assert(parentKind != SyntaxKind.CompilationUnit); cancellationToken.ThrowIfCancellationRequested(); // don't reuse members if they were previously declared under a different type keyword kind if (this.IsIncrementalAndFactoryContextMatches) { if (CanReuseMemberDeclaration(CurrentNodeKind, isGlobal: false)) { return (MemberDeclarationSyntax)this.EatNode(); } } var modifiers = _pool.Allocate(); var saveTermState = _termState; try { var attributes = this.ParseAttributeDeclarations(); this.ParseModifiers(modifiers, forAccessors: false); // Check for constructor form if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.OpenParenToken) { return this.ParseConstructorDeclaration(attributes, modifiers); } // Check for destructor form if (this.CurrentToken.Kind == SyntaxKind.TildeToken) { return this.ParseDestructorDeclaration(attributes, modifiers); } // Check for constant if (this.CurrentToken.Kind == SyntaxKind.ConstKeyword) { return this.ParseConstantFieldDeclaration(attributes, modifiers, parentKind); } // Check for event. if (this.CurrentToken.Kind == SyntaxKind.EventKeyword) { return this.ParseEventDeclaration(attributes, modifiers, parentKind); } // check for fixed size buffers. if (this.CurrentToken.Kind == SyntaxKind.FixedKeyword) { return this.ParseFixedSizeBufferDeclaration(attributes, modifiers, parentKind); } // Check for conversion operators (implicit/explicit) MemberDeclarationSyntax result = this.TryParseConversionOperatorDeclaration(attributes, modifiers); if (result is not null) { return result; } // Namespaces should be handled by the caller, not checking for them // It's valid to have a type declaration here -- check for those if (IsTypeDeclarationStart()) { return this.ParseTypeDeclaration(attributes, modifiers); } // Everything that's left -- methods, fields, properties, // indexers, and non-conversion operators -- starts with a type // (possibly void). TypeSyntax type = ParseReturnType(); var afterTypeResetPoint = this.GetResetPoint(); try { // Check for misplaced modifiers. if we see any, then consider this member // terminated and restart parsing. if (IsMisplacedModifier(modifiers, attributes, type, out result)) { return result; } parse_member_name:; ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; // If we've seen the ref keyword, we know we must have an indexer, method, or property. if (type.Kind != SyntaxKind.RefType) { // Check here for operators // Allow old-style implicit/explicit casting operator syntax, just so we can give a better error if (IsOperatorStart(out explicitInterfaceOpt)) { return this.ParseOperatorDeclaration(attributes, modifiers, type, explicitInterfaceOpt); } if (IsFieldDeclaration(isEvent: false)) { return this.ParseNormalFieldDeclaration(attributes, modifiers, type, parentKind); } } // At this point we can either have indexers, methods, or // properties (or something unknown). Try to break apart // the following name and determine what to do from there. SyntaxToken identifierOrThisOpt; TypeParameterListSyntax typeParameterListOpt; this.ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterListOpt, isEvent: false); // First, check if we got absolutely nothing. If so, then // We need to consume a bad member and try again. if (IsNoneOrIncompleteMember(parentKind, attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) { return result; } // If the modifiers did not include "async", and the type we got was "async", and there was an // error in the identifier or its type parameters, then the user is probably in the midst of typing // an async method. In that case we reconsider "async" to be a modifier, and treat the identifier // (with the type parameters) as the type (with type arguments). Then we go back to looking for // the member name again. // For example, if we get // async Task< // then we want async to be a modifier and Task<MISSING> to be a type. if (ReconsideredTypeAsAsyncModifier(ref modifiers, ref type, ref afterTypeResetPoint, ref explicitInterfaceOpt, ref identifierOrThisOpt, ref typeParameterListOpt)) { goto parse_member_name; } Debug.Assert(identifierOrThisOpt != null); // check availability of readonly members feature for indexers, properties and methods CheckForVersionSpecificModifiers(modifiers, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyMembers); if (TryParseIndexerOrPropertyDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt, out result)) { return result; } // treat anything else as a method. return this.ParseMethodDeclaration(attributes, modifiers, type, explicitInterfaceOpt, identifierOrThisOpt, typeParameterListOpt); } finally { this.Release(ref afterTypeResetPoint); } } finally { _pool.Free(modifiers); _termState = saveTermState; } } // if the modifiers do not contain async or replace and the type is the identifier "async" or "replace", then // add that identifier to the modifiers and assign a new type from the identifierOrThisOpt and the // type parameter list private bool ReconsiderTypeAsAsyncModifier( ref SyntaxListBuilder modifiers, TypeSyntax type, SyntaxToken identifierOrThisOpt) { if (type.Kind != SyntaxKind.IdentifierName) return false; if (identifierOrThisOpt.Kind != SyntaxKind.IdentifierToken) return false; var identifier = ((IdentifierNameSyntax)type).Identifier; var contextualKind = identifier.ContextualKind; if (contextualKind != SyntaxKind.AsyncKeyword || modifiers.Any((int)contextualKind)) { return false; } modifiers.Add(ConvertToKeyword(identifier)); return true; } private bool IsFieldDeclaration(bool isEvent) { if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return false; } if (this.CurrentToken.ContextualKind == SyntaxKind.GlobalKeyword && this.PeekToken(1).Kind == SyntaxKind.UsingKeyword) { return false; } // Treat this as a field, unless we have anything following that // makes us: // a) explicit // b) generic // c) a property // d) a method (unless we already know we're parsing an event) var kind = this.PeekToken(1).Kind; switch (kind) { case SyntaxKind.DotToken: // Goo. explicit case SyntaxKind.ColonColonToken: // Goo:: explicit case SyntaxKind.DotDotToken: // Goo.. explicit case SyntaxKind.LessThanToken: // Goo< explicit or generic method case SyntaxKind.OpenBraceToken: // Goo { property case SyntaxKind.EqualsGreaterThanToken: // Goo => property return false; case SyntaxKind.OpenParenToken: // Goo( method return isEvent; default: return true; } } private bool IsOperatorKeyword() { return this.CurrentToken.Kind == SyntaxKind.ImplicitKeyword || this.CurrentToken.Kind == SyntaxKind.ExplicitKeyword || this.CurrentToken.Kind == SyntaxKind.OperatorKeyword; } public static bool IsComplete(CSharpSyntaxNode node) { if (node == null) { return false; } foreach (var child in node.ChildNodesAndTokens().Reverse()) { var token = child as SyntaxToken; if (token == null) { return IsComplete((CSharpSyntaxNode)child); } if (token.IsMissing) { return false; } if (token.Kind != SyntaxKind.None) { return true; } // if token was optional, consider the next one.. } return true; } private ConstructorDeclarationSyntax ParseConstructorDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { var name = this.ParseIdentifierToken(); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfMethodSignature; try { var paramList = this.ParseParenthesizedParameterList(); ConstructorInitializerSyntax initializer = this.CurrentToken.Kind == SyntaxKind.ColonToken ? this.ParseConstructorInitializer() : null; this.ParseBlockAndExpressionBodiesWithSemicolon( out BlockSyntax body, out ArrowExpressionClauseSyntax expressionBody, out SyntaxToken semicolon, requestedExpressionBodyFeature: MessageID.IDS_FeatureExpressionBodiedDeOrConstructor); return _syntaxFactory.ConstructorDeclaration(attributes, modifiers.ToList(), name, paramList, initializer, body, expressionBody, semicolon); } finally { _termState = saveTerm; } } private ConstructorInitializerSyntax ParseConstructorInitializer() { var colon = this.EatToken(SyntaxKind.ColonToken); var reportError = true; var kind = this.CurrentToken.Kind == SyntaxKind.BaseKeyword ? SyntaxKind.BaseConstructorInitializer : SyntaxKind.ThisConstructorInitializer; SyntaxToken token; if (this.CurrentToken.Kind == SyntaxKind.BaseKeyword || this.CurrentToken.Kind == SyntaxKind.ThisKeyword) { token = this.EatToken(); } else { token = this.EatToken(SyntaxKind.ThisKeyword, ErrorCode.ERR_ThisOrBaseExpected); // No need to report further errors at this point: reportError = false; } ArgumentListSyntax argumentList; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { argumentList = this.ParseParenthesizedArgumentList(); } else { var openToken = this.EatToken(SyntaxKind.OpenParenToken, reportError); var closeToken = this.EatToken(SyntaxKind.CloseParenToken, reportError); argumentList = _syntaxFactory.ArgumentList(openToken, default, closeToken); } return _syntaxFactory.ConstructorInitializer(kind, colon, token, argumentList); } private DestructorDeclarationSyntax ParseDestructorDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.TildeToken); var tilde = this.EatToken(SyntaxKind.TildeToken); var name = this.ParseIdentifierToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); this.ParseBlockAndExpressionBodiesWithSemicolon( out BlockSyntax body, out ArrowExpressionClauseSyntax expressionBody, out SyntaxToken semicolon, requestedExpressionBodyFeature: MessageID.IDS_FeatureExpressionBodiedDeOrConstructor); var parameterList = _syntaxFactory.ParameterList(openParen, default(SeparatedSyntaxList<ParameterSyntax>), closeParen); return _syntaxFactory.DestructorDeclaration(attributes, modifiers.ToList(), tilde, name, parameterList, body, expressionBody, semicolon); } /// <summary> /// Parses any block or expression bodies that are present. Also parses /// the trailing semicolon if one is present. /// </summary> private void ParseBlockAndExpressionBodiesWithSemicolon( out BlockSyntax blockBody, out ArrowExpressionClauseSyntax expressionBody, out SyntaxToken semicolon, bool parseSemicolonAfterBlock = true, MessageID requestedExpressionBodyFeature = MessageID.IDS_FeatureExpressionBodiedMethod) { // Check for 'forward' declarations with no block of any kind if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { blockBody = null; expressionBody = null; semicolon = this.EatToken(SyntaxKind.SemicolonToken); return; } blockBody = null; expressionBody = null; if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { blockBody = this.ParseMethodOrAccessorBodyBlock(attributes: default, isAccessorBody: false); } if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) { Debug.Assert(requestedExpressionBodyFeature == MessageID.IDS_FeatureExpressionBodiedMethod || requestedExpressionBodyFeature == MessageID.IDS_FeatureExpressionBodiedAccessor || requestedExpressionBodyFeature == MessageID.IDS_FeatureExpressionBodiedDeOrConstructor, "Only IDS_FeatureExpressionBodiedMethod, IDS_FeatureExpressionBodiedAccessor or IDS_FeatureExpressionBodiedDeOrConstructor can be requested"); expressionBody = this.ParseArrowExpressionClause(); expressionBody = CheckFeatureAvailability(expressionBody, requestedExpressionBodyFeature); } semicolon = null; // Expression-bodies need semicolons and native behavior // expects a semicolon if there is no body if (expressionBody != null || blockBody == null) { semicolon = this.EatToken(SyntaxKind.SemicolonToken); } // Check for bad semicolon after block body else if (parseSemicolonAfterBlock && this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); } } private bool IsEndOfTypeParameterList() { if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { // void Goo<T ( return true; } if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { // class C<T : return true; } if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { // class C<T { return true; } if (IsCurrentTokenWhereOfConstraintClause()) { // class C<T where T : return true; } return false; } private bool IsEndOfMethodSignature() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; } private bool IsEndOfRecordSignature() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; } private bool IsEndOfNameInExplicitInterface() { return this.CurrentToken.Kind == SyntaxKind.DotToken || this.CurrentToken.Kind == SyntaxKind.ColonColonToken; } private bool IsEndOfFunctionPointerParameterList(bool errored) => this.CurrentToken.Kind == (errored ? SyntaxKind.CloseParenToken : SyntaxKind.GreaterThanToken); private bool IsEndOfFunctionPointerCallingConvention() => this.CurrentToken.Kind == SyntaxKind.CloseBracketToken; private MethodDeclarationSyntax ParseMethodDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifier, TypeParameterListSyntax typeParameterList) { // Parse the name (it could be qualified) var saveTerm = _termState; _termState |= TerminatorState.IsEndOfMethodSignature; var paramList = this.ParseParenthesizedParameterList(); var constraints = default(SyntaxListBuilder<TypeParameterConstraintClauseSyntax>); try { if (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { constraints = _pool.Allocate<TypeParameterConstraintClauseSyntax>(); this.ParseTypeParameterConstraintClauses(constraints); } else if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { // Use else if, rather than if, because if we see both a constructor initializer and a constraint clause, we're too lost to recover. var colonToken = this.CurrentToken; ConstructorInitializerSyntax initializer = this.ParseConstructorInitializer(); initializer = this.AddErrorToFirstToken(initializer, ErrorCode.ERR_UnexpectedToken, colonToken.Text); paramList = AddTrailingSkippedSyntax(paramList, initializer); // CONSIDER: Parsing an invalid constructor initializer could, conceivably, get us way // off track. If this becomes a problem, an alternative approach would be to generalize // EatTokenWithPrejudice in such a way that we can just skip everything until we recognize // our context again (perhaps an open brace). } _termState = saveTerm; BlockSyntax blockBody; ArrowExpressionClauseSyntax expressionBody; SyntaxToken semicolon; // Method declarations cannot be nested or placed inside async lambdas, and so cannot occur in an // asynchronous context. Therefore the IsInAsync state of the parent scope is not saved and // restored, just assumed to be false and reset accordingly after parsing the method body. Debug.Assert(!IsInAsync); IsInAsync = modifiers.Any((int)SyntaxKind.AsyncKeyword); this.ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon); IsInAsync = false; return _syntaxFactory.MethodDeclaration( attributes, modifiers.ToList(), type, explicitInterfaceOpt, identifier, typeParameterList, paramList, constraints, blockBody, expressionBody, semicolon); } finally { if (!constraints.IsNull) { _pool.Free(constraints); } } } private TypeSyntax ParseReturnType() { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfReturnType; var type = this.ParseTypeOrVoid(); _termState = saveTerm; return type; } private bool IsEndOfReturnType() { switch (this.CurrentToken.Kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.OpenBraceToken: case SyntaxKind.SemicolonToken: return true; default: return false; } } private ConversionOperatorDeclarationSyntax TryParseConversionOperatorDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { var point = GetResetPoint(); try { SyntaxToken style; if (this.CurrentToken.Kind == SyntaxKind.ImplicitKeyword || this.CurrentToken.Kind == SyntaxKind.ExplicitKeyword) { style = this.EatToken(); } else { style = this.EatToken(SyntaxKind.ExplicitKeyword); } ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt = tryParseExplicitInterfaceSpecifier(); SyntaxToken opKeyword; TypeSyntax type; ParameterListSyntax paramList; if (style.IsMissing) { if (this.CurrentToken.Kind != SyntaxKind.OperatorKeyword || SyntaxFacts.IsAnyOverloadableOperator(this.PeekToken(1).Kind) || explicitInterfaceOpt?.DotToken.IsMissing == true) { this.Reset(ref point); return null; } } else if (explicitInterfaceOpt is not null && this.CurrentToken.Kind != SyntaxKind.OperatorKeyword && style.TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia)) { // Not likely an explicit interface implementation. Likely a beginning of the next member on the next line. this.Reset(ref point); style = this.EatToken(); explicitInterfaceOpt = null; opKeyword = this.EatToken(SyntaxKind.OperatorKeyword); type = this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected); SyntaxToken open = SyntaxFactory.MissingToken(SyntaxKind.OpenParenToken); SyntaxToken close = SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken); var parameters = _pool.AllocateSeparated<ParameterSyntax>(); paramList = _syntaxFactory.ParameterList(open, parameters, close); _pool.Free(parameters); return _syntaxFactory.ConversionOperatorDeclaration( attributes, modifiers.ToList(), style, explicitInterfaceOpt, opKeyword, type, paramList, body: null, expressionBody: null, semicolonToken: SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken)); } opKeyword = this.EatToken(SyntaxKind.OperatorKeyword); this.Release(ref point); point = GetResetPoint(); bool couldBeParameterList = this.CurrentToken.Kind == SyntaxKind.OpenParenToken; type = this.ParseType(); if (couldBeParameterList && type is TupleTypeSyntax { Elements: { Count: 2, SeparatorCount: 1 } } tupleType && tupleType.Elements.GetSeparator(0).IsMissing && tupleType.Elements[1].IsMissing && this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { // It looks like the type is missing and we parsed parameter list as the type. Recover. this.Reset(ref point); type = ParseIdentifierName(); } paramList = this.ParseParenthesizedParameterList(); BlockSyntax blockBody; ArrowExpressionClauseSyntax expressionBody; SyntaxToken semicolon; this.ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon); return _syntaxFactory.ConversionOperatorDeclaration( attributes, modifiers.ToList(), style, explicitInterfaceOpt, opKeyword, type, paramList, blockBody, expressionBody, semicolon); } finally { this.Release(ref point); } ExplicitInterfaceSpecifierSyntax tryParseExplicitInterfaceSpecifier() { if (this.CurrentToken.Kind == SyntaxKind.OperatorKeyword) { return null; } if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return null; } NameSyntax explicitInterfaceName = null; SyntaxToken separator = null; while (true) { // now, scan past the next name. if it's followed by a dot then // it's part of the explicit name we're building up. Otherwise, // it should be an operator token var point = GetResetPoint(); bool isPartOfInterfaceName; try { if (this.CurrentToken.Kind == SyntaxKind.OperatorKeyword) { isPartOfInterfaceName = false; } else { int lastTokenPosition = -1; IsMakingProgress(ref lastTokenPosition, assertIfFalse: true); ScanNamedTypePart(); isPartOfInterfaceName = IsDotOrColonColonOrDotDot() || (IsMakingProgress(ref lastTokenPosition, assertIfFalse: false) && this.CurrentToken.Kind != SyntaxKind.OpenParenToken); } } finally { this.Reset(ref point); this.Release(ref point); } if (!isPartOfInterfaceName) { // We're past any explicit interface portion if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) { separator = this.AddError(separator, ErrorCode.ERR_AliasQualAsExpression); separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } break; } else { // If we saw a . or :: then we must have something explicit. AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator); } } if (explicitInterfaceName is null) { return null; } if (separator.Kind != SyntaxKind.DotToken) { separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, separator.GetLeadingTriviaWidth(), separator.Width)); separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } return CheckFeatureAvailability(_syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator), MessageID.IDS_FeatureStaticAbstractMembersInInterfaces); } } private OperatorDeclarationSyntax ParseOperatorDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt) { var opKeyword = this.EatToken(SyntaxKind.OperatorKeyword); SyntaxToken opToken; int opTokenErrorOffset; int opTokenErrorWidth; if (SyntaxFacts.IsAnyOverloadableOperator(this.CurrentToken.Kind)) { opToken = this.EatToken(); Debug.Assert(!opToken.IsMissing); opTokenErrorOffset = opToken.GetLeadingTriviaWidth(); opTokenErrorWidth = opToken.Width; } else { if (this.CurrentToken.Kind == SyntaxKind.ImplicitKeyword || this.CurrentToken.Kind == SyntaxKind.ExplicitKeyword) { // Grab the offset and width before we consume the invalid keyword and change our position. GetDiagnosticSpanForMissingToken(out opTokenErrorOffset, out opTokenErrorWidth); opToken = this.ConvertToMissingWithTrailingTrivia(this.EatToken(), SyntaxKind.PlusToken); Debug.Assert(opToken.IsMissing); //Which is why we used GetDiagnosticSpanForMissingToken above. Debug.Assert(type != null); // How could it be? The only caller got it from ParseReturnType. if (type.IsMissing) { SyntaxDiagnosticInfo diagInfo = MakeError(opTokenErrorOffset, opTokenErrorWidth, ErrorCode.ERR_BadOperatorSyntax, SyntaxFacts.GetText(SyntaxKind.PlusToken)); opToken = WithAdditionalDiagnostics(opToken, diagInfo); } else { // Dev10 puts this error on the type (if there is one). type = this.AddError(type, ErrorCode.ERR_BadOperatorSyntax, SyntaxFacts.GetText(SyntaxKind.PlusToken)); } } else { //Consume whatever follows the operator keyword as the operator token. If it is not //we'll add an error below (when we can guess the arity). opToken = EatToken(); Debug.Assert(!opToken.IsMissing); opTokenErrorOffset = opToken.GetLeadingTriviaWidth(); opTokenErrorWidth = opToken.Width; } } // check for >> var opKind = opToken.Kind; var tk = this.CurrentToken; if (opToken.Kind == SyntaxKind.GreaterThanToken && tk.Kind == SyntaxKind.GreaterThanToken) { // no trailing trivia and no leading trivia if (opToken.GetTrailingTriviaWidth() == 0 && tk.GetLeadingTriviaWidth() == 0) { var opToken2 = this.EatToken(); opToken = SyntaxFactory.Token(opToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanToken, opToken2.GetTrailingTrivia()); } } var paramList = this.ParseParenthesizedParameterList(); switch (paramList.Parameters.Count) { case 1: if (opToken.IsMissing || !SyntaxFacts.IsOverloadableUnaryOperator(opKind)) { SyntaxDiagnosticInfo diagInfo = MakeError(opTokenErrorOffset, opTokenErrorWidth, ErrorCode.ERR_OvlUnaryOperatorExpected); opToken = WithAdditionalDiagnostics(opToken, diagInfo); } break; case 2: if (opToken.IsMissing || !SyntaxFacts.IsOverloadableBinaryOperator(opKind)) { SyntaxDiagnosticInfo diagInfo = MakeError(opTokenErrorOffset, opTokenErrorWidth, ErrorCode.ERR_OvlBinaryOperatorExpected); opToken = WithAdditionalDiagnostics(opToken, diagInfo); } break; default: if (opToken.IsMissing) { SyntaxDiagnosticInfo diagInfo = MakeError(opTokenErrorOffset, opTokenErrorWidth, ErrorCode.ERR_OvlOperatorExpected); opToken = WithAdditionalDiagnostics(opToken, diagInfo); } else if (SyntaxFacts.IsOverloadableBinaryOperator(opKind)) { opToken = this.AddError(opToken, ErrorCode.ERR_BadBinOpArgs, SyntaxFacts.GetText(opKind)); } else if (SyntaxFacts.IsOverloadableUnaryOperator(opKind)) { opToken = this.AddError(opToken, ErrorCode.ERR_BadUnOpArgs, SyntaxFacts.GetText(opKind)); } else { opToken = this.AddError(opToken, ErrorCode.ERR_OvlOperatorExpected); } break; } BlockSyntax blockBody; ArrowExpressionClauseSyntax expressionBody; SyntaxToken semicolon; this.ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon); // if the operator is invalid, then switch it to plus (which will work either way) so that // we can finish building the tree if (!(opKind == SyntaxKind.IsKeyword || SyntaxFacts.IsOverloadableUnaryOperator(opKind) || SyntaxFacts.IsOverloadableBinaryOperator(opKind))) { opToken = ConvertToMissingWithTrailingTrivia(opToken, SyntaxKind.PlusToken); } return _syntaxFactory.OperatorDeclaration( attributes, modifiers.ToList(), type, explicitInterfaceOpt, opKeyword, opToken, paramList, blockBody, expressionBody, semicolon); } private IndexerDeclarationSyntax ParseIndexerDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken thisKeyword, TypeParameterListSyntax typeParameterList) { Debug.Assert(thisKeyword.Kind == SyntaxKind.ThisKeyword); // check to see if the user tried to create a generic indexer. if (typeParameterList != null) { thisKeyword = AddTrailingSkippedSyntax(thisKeyword, typeParameterList); thisKeyword = this.AddError(thisKeyword, ErrorCode.ERR_UnexpectedGenericName); } var parameterList = this.ParseBracketedParameterList(); AccessorListSyntax accessorList = null; ArrowExpressionClauseSyntax expressionBody = null; SyntaxToken semicolon = null; // Try to parse accessor list unless there is an expression // body and no accessor list if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) { expressionBody = this.ParseArrowExpressionClause(); expressionBody = CheckFeatureAvailability(expressionBody, MessageID.IDS_FeatureExpressionBodiedIndexer); semicolon = this.EatToken(SyntaxKind.SemicolonToken); } else { accessorList = this.ParseAccessorList(isEvent: false); if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); } } // If the user has erroneously provided both an accessor list // and an expression body, but no semicolon, we want to parse // the expression body and report the error (which is done later) if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken && semicolon == null) { expressionBody = this.ParseArrowExpressionClause(); expressionBody = CheckFeatureAvailability(expressionBody, MessageID.IDS_FeatureExpressionBodiedIndexer); semicolon = this.EatToken(SyntaxKind.SemicolonToken); } return _syntaxFactory.IndexerDeclaration( attributes, modifiers.ToList(), type, explicitInterfaceOpt, thisKeyword, parameterList, accessorList, expressionBody, semicolon); } private PropertyDeclarationSyntax ParsePropertyDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, SyntaxToken identifier, TypeParameterListSyntax typeParameterList) { // check to see if the user tried to create a generic property. if (typeParameterList != null) { identifier = AddTrailingSkippedSyntax(identifier, typeParameterList); identifier = this.AddError(identifier, ErrorCode.ERR_UnexpectedGenericName); } // We know we are parsing a property because we have seen either an // open brace or an arrow token Debug.Assert(this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken); AccessorListSyntax accessorList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { accessorList = this.ParseAccessorList(isEvent: false); } ArrowExpressionClauseSyntax expressionBody = null; EqualsValueClauseSyntax initializer = null; // Check for expression body if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) { expressionBody = this.ParseArrowExpressionClause(); expressionBody = CheckFeatureAvailability(expressionBody, MessageID.IDS_FeatureExpressionBodiedProperty); } // Check if we have an initializer else if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { var equals = this.EatToken(SyntaxKind.EqualsToken); var value = this.ParseVariableInitializer(); initializer = _syntaxFactory.EqualsValueClause(equals, value: value); initializer = CheckFeatureAvailability(initializer, MessageID.IDS_FeatureAutoPropertyInitializer); } SyntaxToken semicolon = null; if (expressionBody != null || initializer != null) { semicolon = this.EatToken(SyntaxKind.SemicolonToken); } else if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatTokenWithPrejudice(ErrorCode.ERR_UnexpectedSemicolon); } return _syntaxFactory.PropertyDeclaration( attributes, modifiers.ToList(), type, explicitInterfaceOpt, identifier, accessorList, expressionBody, initializer, semicolon); } private AccessorListSyntax ParseAccessorList(bool isEvent) { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var accessors = default(SyntaxList<AccessorDeclarationSyntax>); if (!openBrace.IsMissing || !this.IsTerminator()) { // parse property accessors var builder = _pool.Allocate<AccessorDeclarationSyntax>(); try { while (true) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.IsPossibleAccessor()) { var acc = this.ParseAccessorDeclaration(isEvent); builder.Add(acc); } else if (this.SkipBadAccessorListTokens(ref openBrace, builder, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected) == PostSkipAction.Abort) { break; } } accessors = builder.ToList(); } finally { _pool.Free(builder); } } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); return _syntaxFactory.AccessorList(openBrace, accessors, closeBrace); } private ArrowExpressionClauseSyntax ParseArrowExpressionClause() { var arrowToken = this.EatToken(SyntaxKind.EqualsGreaterThanToken); return _syntaxFactory.ArrowExpressionClause(arrowToken, ParsePossibleRefExpression()); } private ExpressionSyntax ParsePossibleRefExpression() { var refKeyword = (SyntaxToken)null; if (this.CurrentToken.Kind == SyntaxKind.RefKeyword) { refKeyword = this.EatToken(); refKeyword = CheckFeatureAvailability(refKeyword, MessageID.IDS_FeatureRefLocalsReturns); } var expression = this.ParseExpressionCore(); if (refKeyword != null) { expression = _syntaxFactory.RefExpression(refKeyword, expression); } return expression; } private PostSkipAction SkipBadAccessorListTokens(ref SyntaxToken openBrace, SyntaxListBuilder<AccessorDeclarationSyntax> list, ErrorCode error) { return this.SkipBadListTokensWithErrorCode(ref openBrace, list, p => p.CurrentToken.Kind != SyntaxKind.CloseBraceToken && !p.IsPossibleAccessor(), p => p.IsTerminator(), error); } private bool IsPossibleAccessor() { return this.CurrentToken.Kind == SyntaxKind.IdentifierToken || IsPossibleAttributeDeclaration() || SyntaxFacts.GetAccessorDeclarationKind(this.CurrentToken.ContextualKind) != SyntaxKind.None || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken // for accessor blocks w/ missing keyword || this.CurrentToken.Kind == SyntaxKind.SemicolonToken // for empty body accessors w/ missing keyword || IsPossibleAccessorModifier(); } private bool IsPossibleAccessorModifier() { // We only want to accept a modifier as the start of an accessor if the modifiers are // actually followed by "get/set/add/remove". Otherwise, we might thing think we're // starting an accessor when we're actually starting a normal class member. For example: // // class C { // public int Prop { get { this. // private DateTime x; // // We don't want to think of the "private" in "private DateTime x" as starting an accessor // here. If we do, we'll get totally thrown off in parsing the remainder and that will // throw off the rest of the features that depend on a good syntax tree. // // Note: we allow all modifiers here. That's because we want to parse things like // "abstract get" as an accessor. This way we can provide a good error message // to the user that this is not allowed. if (GetModifier(this.CurrentToken) == DeclarationModifiers.None) { return false; } var peekIndex = 1; while (GetModifier(this.PeekToken(peekIndex)) != DeclarationModifiers.None) { peekIndex++; } var token = this.PeekToken(peekIndex); if (token.Kind == SyntaxKind.CloseBraceToken || token.Kind == SyntaxKind.EndOfFileToken) { // If we see "{ get { } public } // then we will think that "public" likely starts an accessor. return true; } switch (token.ContextualKind) { case SyntaxKind.GetKeyword: case SyntaxKind.SetKeyword: case SyntaxKind.InitKeyword: case SyntaxKind.AddKeyword: case SyntaxKind.RemoveKeyword: return true; default: return false; } } private enum PostSkipAction { Continue, Abort } private PostSkipAction SkipBadSeparatedListTokensWithExpectedKind<T, TNode>( ref T startToken, SeparatedSyntaxListBuilder<TNode> list, Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, SyntaxKind expected) where T : CSharpSyntaxNode where TNode : CSharpSyntaxNode { // We're going to cheat here and pass the underlying SyntaxListBuilder of "list" to the helper method so that // it can append skipped trivia to the last element, regardless of whether that element is a node or a token. GreenNode trailingTrivia; var action = this.SkipBadListTokensWithExpectedKindHelper(list.UnderlyingBuilder, isNotExpectedFunction, abortFunction, expected, out trailingTrivia); if (trailingTrivia != null) { startToken = AddTrailingSkippedSyntax(startToken, trailingTrivia); } return action; } private PostSkipAction SkipBadListTokensWithErrorCode<T, TNode>( ref T startToken, SyntaxListBuilder<TNode> list, Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, ErrorCode error) where T : CSharpSyntaxNode where TNode : CSharpSyntaxNode { GreenNode trailingTrivia; var action = this.SkipBadListTokensWithErrorCodeHelper(list, isNotExpectedFunction, abortFunction, error, out trailingTrivia); if (trailingTrivia != null) { startToken = AddTrailingSkippedSyntax(startToken, trailingTrivia); } return action; } /// <remarks> /// WARNING: it is possible that "list" is really the underlying builder of a SeparateSyntaxListBuilder, /// so it is important that we not add anything to the list. /// </remarks> private PostSkipAction SkipBadListTokensWithExpectedKindHelper( SyntaxListBuilder list, Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, SyntaxKind expected, out GreenNode trailingTrivia) { if (list.Count == 0) { return SkipBadTokensWithExpectedKind(isNotExpectedFunction, abortFunction, expected, out trailingTrivia); } else { GreenNode lastItemTrailingTrivia; var action = SkipBadTokensWithExpectedKind(isNotExpectedFunction, abortFunction, expected, out lastItemTrailingTrivia); if (lastItemTrailingTrivia != null) { AddTrailingSkippedSyntax(list, lastItemTrailingTrivia); } trailingTrivia = null; return action; } } private PostSkipAction SkipBadListTokensWithErrorCodeHelper<TNode>( SyntaxListBuilder<TNode> list, Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, ErrorCode error, out GreenNode trailingTrivia) where TNode : CSharpSyntaxNode { if (list.Count == 0) { return SkipBadTokensWithErrorCode(isNotExpectedFunction, abortFunction, error, out trailingTrivia); } else { GreenNode lastItemTrailingTrivia; var action = SkipBadTokensWithErrorCode(isNotExpectedFunction, abortFunction, error, out lastItemTrailingTrivia); if (lastItemTrailingTrivia != null) { AddTrailingSkippedSyntax(list, lastItemTrailingTrivia); } trailingTrivia = null; return action; } } private PostSkipAction SkipBadTokensWithExpectedKind( Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, SyntaxKind expected, out GreenNode trailingTrivia) { var nodes = _pool.Allocate(); try { bool first = true; var action = PostSkipAction.Continue; while (isNotExpectedFunction(this)) { if (abortFunction(this)) { action = PostSkipAction.Abort; break; } var token = (first && !this.CurrentToken.ContainsDiagnostics) ? this.EatTokenWithPrejudice(expected) : this.EatToken(); first = false; nodes.Add(token); } trailingTrivia = (nodes.Count > 0) ? nodes.ToListNode() : null; return action; } finally { _pool.Free(nodes); } } private PostSkipAction SkipBadTokensWithErrorCode( Func<LanguageParser, bool> isNotExpectedFunction, Func<LanguageParser, bool> abortFunction, ErrorCode errorCode, out GreenNode trailingTrivia) { var nodes = _pool.Allocate(); try { bool first = true; var action = PostSkipAction.Continue; while (isNotExpectedFunction(this)) { if (abortFunction(this)) { action = PostSkipAction.Abort; break; } var token = (first && !this.CurrentToken.ContainsDiagnostics) ? this.EatTokenWithPrejudice(errorCode) : this.EatToken(); first = false; nodes.Add(token); } trailingTrivia = (nodes.Count > 0) ? nodes.ToListNode() : null; return action; } finally { _pool.Free(nodes); } } private AccessorDeclarationSyntax ParseAccessorDeclaration(bool isEvent) { if (this.IsIncrementalAndFactoryContextMatches && SyntaxFacts.IsAccessorDeclaration(this.CurrentNodeKind)) { return (AccessorDeclarationSyntax)this.EatNode(); } var accMods = _pool.Allocate(); try { var accAttrs = this.ParseAttributeDeclarations(); this.ParseModifiers(accMods, forAccessors: true); // check availability of readonly members feature for accessors CheckForVersionSpecificModifiers(accMods, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyMembers); if (!isEvent) { if (accMods != null && accMods.Count > 0) { accMods[0] = CheckFeatureAvailability(accMods[0], MessageID.IDS_FeaturePropertyAccessorMods); } } var accessorName = this.EatToken(SyntaxKind.IdentifierToken, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected); var accessorKind = GetAccessorKind(accessorName); // Only convert the identifier to a keyword if it's a valid one. Otherwise any // other contextual keyword (like 'partial') will be converted into a keyword // and will be invalid. if (accessorKind == SyntaxKind.UnknownAccessorDeclaration) { // We'll have an UnknownAccessorDeclaration either because we didn't have // an IdentifierToken or because we have an IdentifierToken which is not // add/remove/get/set. In the former case, we'll already have reported // an error and will have a missing token. But in the latter case we need // to report that the identifier is incorrect. if (!accessorName.IsMissing) { accessorName = this.AddError(accessorName, isEvent ? ErrorCode.ERR_AddOrRemoveExpected : ErrorCode.ERR_GetOrSetExpected); } else { Debug.Assert(accessorName.ContainsDiagnostics); } } else { accessorName = ConvertToKeyword(accessorName); } BlockSyntax blockBody = null; ArrowExpressionClauseSyntax expressionBody = null; SyntaxToken semicolon = null; bool currentTokenIsSemicolon = this.CurrentToken.Kind == SyntaxKind.SemicolonToken; bool currentTokenIsArrow = this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken; bool currentTokenIsOpenBraceToken = this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; if (currentTokenIsOpenBraceToken || currentTokenIsArrow) { this.ParseBlockAndExpressionBodiesWithSemicolon( out blockBody, out expressionBody, out semicolon, requestedExpressionBodyFeature: MessageID.IDS_FeatureExpressionBodiedAccessor); } else if (currentTokenIsSemicolon) { semicolon = EatAccessorSemicolon(); } else { // We didn't get something we recognized. If we got an accessor type we // recognized (i.e. get/set/init/add/remove) then try to parse out a block. // Only do this if it doesn't seem like we're at the end of the accessor/property. // for example, if we have "get set", don't actually try to parse out the // block. Otherwise we'll consume the 'set'. In that case, just end the // current accessor with a semicolon so we can properly consume the next // in the calling method's loop. if (accessorKind != SyntaxKind.UnknownAccessorDeclaration) { if (!IsTerminator()) { blockBody = this.ParseMethodOrAccessorBodyBlock(attributes: default, isAccessorBody: true); } else { semicolon = EatAccessorSemicolon(); } } else { // Don't bother eating anything if we didn't even have a valid accessor. // It will just lead to more errors. Note: we will have already produced // a good error by now. Debug.Assert(accessorName.ContainsDiagnostics); } } return _syntaxFactory.AccessorDeclaration( accessorKind, accAttrs, accMods.ToList(), accessorName, blockBody, expressionBody, semicolon); } finally { _pool.Free(accMods); } } private SyntaxToken EatAccessorSemicolon() => this.EatToken(SyntaxKind.SemicolonToken, IsFeatureEnabled(MessageID.IDS_FeatureExpressionBodiedAccessor) ? ErrorCode.ERR_SemiOrLBraceOrArrowExpected : ErrorCode.ERR_SemiOrLBraceExpected); private SyntaxKind GetAccessorKind(SyntaxToken accessorName) { switch (accessorName.ContextualKind) { case SyntaxKind.GetKeyword: return SyntaxKind.GetAccessorDeclaration; case SyntaxKind.SetKeyword: return SyntaxKind.SetAccessorDeclaration; case SyntaxKind.InitKeyword: return SyntaxKind.InitAccessorDeclaration; case SyntaxKind.AddKeyword: return SyntaxKind.AddAccessorDeclaration; case SyntaxKind.RemoveKeyword: return SyntaxKind.RemoveAccessorDeclaration; } return SyntaxKind.UnknownAccessorDeclaration; } internal ParameterListSyntax ParseParenthesizedParameterList() { if (this.IsIncrementalAndFactoryContextMatches && CanReuseParameterList(this.CurrentNode as CSharp.Syntax.ParameterListSyntax)) { return (ParameterListSyntax)this.EatNode(); } var parameters = _pool.AllocateSeparated<ParameterSyntax>(); try { var openKind = SyntaxKind.OpenParenToken; var closeKind = SyntaxKind.CloseParenToken; SyntaxToken open; SyntaxToken close; this.ParseParameterList(out open, parameters, out close, openKind, closeKind); return _syntaxFactory.ParameterList(open, parameters, close); } finally { _pool.Free(parameters); } } internal BracketedParameterListSyntax ParseBracketedParameterList() { if (this.IsIncrementalAndFactoryContextMatches && CanReuseBracketedParameterList(this.CurrentNode as CSharp.Syntax.BracketedParameterListSyntax)) { return (BracketedParameterListSyntax)this.EatNode(); } var parameters = _pool.AllocateSeparated<ParameterSyntax>(); try { var openKind = SyntaxKind.OpenBracketToken; var closeKind = SyntaxKind.CloseBracketToken; SyntaxToken open; SyntaxToken close; this.ParseParameterList(out open, parameters, out close, openKind, closeKind); return _syntaxFactory.BracketedParameterList(open, parameters, close); } finally { _pool.Free(parameters); } } private static bool CanReuseParameterList(CSharp.Syntax.ParameterListSyntax list) { if (list == null) { return false; } if (list.OpenParenToken.IsMissing) { return false; } if (list.CloseParenToken.IsMissing) { return false; } foreach (var parameter in list.Parameters) { if (!CanReuseParameter(parameter)) { return false; } } return true; } private static bool CanReuseBracketedParameterList(CSharp.Syntax.BracketedParameterListSyntax list) { if (list == null) { return false; } if (list.OpenBracketToken.IsMissing) { return false; } if (list.CloseBracketToken.IsMissing) { return false; } foreach (var parameter in list.Parameters) { if (!CanReuseParameter(parameter)) { return false; } } return true; } private void ParseParameterList( out SyntaxToken open, SeparatedSyntaxListBuilder<ParameterSyntax> nodes, out SyntaxToken close, SyntaxKind openKind, SyntaxKind closeKind) { open = this.EatToken(openKind); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfParameterList; if (this.CurrentToken.Kind != closeKind) { tryAgain: if (this.IsPossibleParameter() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first parameter var parameter = this.ParseParameter(); nodes.Add(parameter); // additional parameters while (true) { if (this.CurrentToken.Kind == closeKind) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleParameter()) { nodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); parameter = this.ParseParameter(); if (parameter.IsMissing && this.IsPossibleParameter()) { // ensure we always consume tokens parameter = AddTrailingSkippedSyntax(parameter, this.EatToken()); } nodes.Add(parameter); continue; } else if (this.SkipBadParameterListTokens(ref open, nodes, SyntaxKind.CommaToken, closeKind) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadParameterListTokens(ref open, nodes, SyntaxKind.IdentifierToken, closeKind) == PostSkipAction.Continue) { goto tryAgain; } } _termState = saveTerm; close = this.EatToken(closeKind); } private bool IsEndOfParameterList() { return this.CurrentToken.Kind is SyntaxKind.CloseParenToken or SyntaxKind.CloseBracketToken or SyntaxKind.SemicolonToken; } private PostSkipAction SkipBadParameterListTokens( ref SyntaxToken open, SeparatedSyntaxListBuilder<ParameterSyntax> list, SyntaxKind expected, SyntaxKind closeKind) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref open, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleParameter(), p => p.CurrentToken.Kind == closeKind || p.IsTerminator(), expected); } private bool IsPossibleParameter() { switch (this.CurrentToken.Kind) { case SyntaxKind.OpenBracketToken: // attribute case SyntaxKind.ArgListKeyword: case SyntaxKind.OpenParenToken: // tuple case SyntaxKind.DelegateKeyword when IsFunctionPointerStart(): // Function pointer type return true; case SyntaxKind.IdentifierToken: return this.IsTrueIdentifier(); default: return IsParameterModifier(this.CurrentToken.Kind) || IsPredefinedType(this.CurrentToken.Kind); } } private static bool CanReuseParameter(CSharp.Syntax.ParameterSyntax parameter) { if (parameter == null) { return false; } // cannot reuse a node that possibly ends in an expression if (parameter.Default != null) { return false; } // cannot reuse lambda parameters as normal parameters (parsed with // different rules) CSharp.CSharpSyntaxNode parent = parameter.Parent; if (parent != null) { if (parent.Kind() == SyntaxKind.SimpleLambdaExpression) { return false; } CSharp.CSharpSyntaxNode grandparent = parent.Parent; if (grandparent != null && grandparent.Kind() == SyntaxKind.ParenthesizedLambdaExpression) { Debug.Assert(parent.Kind() == SyntaxKind.ParameterList); return false; } } return true; } private ParameterSyntax ParseParameter() { if (this.IsIncrementalAndFactoryContextMatches && CanReuseParameter(this.CurrentNode as CSharp.Syntax.ParameterSyntax)) { return (ParameterSyntax)this.EatNode(); } var attributes = this.ParseAttributeDeclarations(); var modifiers = _pool.Allocate(); try { this.ParseParameterModifiers(modifiers); TypeSyntax type; SyntaxToken name; if (this.CurrentToken.Kind != SyntaxKind.ArgListKeyword) { type = this.ParseType(mode: ParseTypeMode.Parameter); name = this.ParseIdentifierToken(); // When the user type "int goo[]", give them a useful error if (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken && this.PeekToken(1).Kind == SyntaxKind.CloseBracketToken) { var open = this.EatToken(); var close = this.EatToken(); open = this.AddError(open, ErrorCode.ERR_BadArraySyntax); name = AddTrailingSkippedSyntax(name, SyntaxList.List(open, close)); } } else { // We store an __arglist parameter as a parameter with null type and whose // .Identifier has the kind ArgListKeyword. type = null; name = this.EatToken(SyntaxKind.ArgListKeyword); } EqualsValueClauseSyntax def = null; if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { var equals = this.EatToken(SyntaxKind.EqualsToken); var value = this.ParseExpressionCore(); def = _syntaxFactory.EqualsValueClause(equals, value: value); def = CheckFeatureAvailability(def, MessageID.IDS_FeatureOptionalParameter); } return _syntaxFactory.Parameter(attributes, modifiers.ToList(), type, name, def); } finally { _pool.Free(modifiers); } } private static bool IsParameterModifier(SyntaxKind kind, bool isFunctionPointerParameter = false) { switch (kind) { case SyntaxKind.ThisKeyword: case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: case SyntaxKind.ParamsKeyword: case SyntaxKind.ReadOnlyKeyword when isFunctionPointerParameter: return true; } return false; } private void ParseParameterModifiers(SyntaxListBuilder modifiers, bool isFunctionPointerParameter = false) { while (IsParameterModifier(this.CurrentToken.Kind, isFunctionPointerParameter)) { var modifier = this.EatToken(); switch (modifier.Kind) { case SyntaxKind.ThisKeyword: modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureExtensionMethod); if (this.CurrentToken.Kind == SyntaxKind.RefKeyword || this.CurrentToken.Kind == SyntaxKind.InKeyword) { modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureRefExtensionMethods); } break; case SyntaxKind.RefKeyword: { if (this.CurrentToken.Kind == SyntaxKind.ThisKeyword) { modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureRefExtensionMethods); } break; } case SyntaxKind.InKeyword: { modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureReadOnlyReferences); if (this.CurrentToken.Kind == SyntaxKind.ThisKeyword) { modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureRefExtensionMethods); } break; } } modifiers.Add(modifier); } } private FieldDeclarationSyntax ParseFixedSizeBufferDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.FixedKeyword); var fixedToken = this.EatToken(); fixedToken = CheckFeatureAvailability(fixedToken, MessageID.IDS_FeatureFixedBuffer); modifiers.Add(fixedToken); var type = this.ParseType(); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFieldDeclaration; var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseVariableDeclarators(type, VariableFlags.Fixed, variables, parentKind); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.FieldDeclaration( attributes, modifiers.ToList(), _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _termState = saveTerm; _pool.Free(variables); } } private MemberDeclarationSyntax ParseEventDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.EventKeyword); var eventToken = this.EatToken(); var type = this.ParseType(); if (IsFieldDeclaration(isEvent: true)) { return this.ParseEventFieldDeclaration(attributes, modifiers, eventToken, type, parentKind); } else { return this.ParseEventDeclarationWithAccessors(attributes, modifiers, eventToken, type); } } private EventDeclarationSyntax ParseEventDeclarationWithAccessors( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxToken eventToken, TypeSyntax type) { ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; SyntaxToken identifierOrThisOpt; TypeParameterListSyntax typeParameterList; this.ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterList, isEvent: true); // check availability of readonly members feature for custom events CheckForVersionSpecificModifiers(modifiers, SyntaxKind.ReadOnlyKeyword, MessageID.IDS_FeatureReadOnlyMembers); // If we got an explicitInterfaceOpt but not an identifier, then we're in the special // case for ERR_ExplicitEventFieldImpl (see ParseMemberName for details). if (explicitInterfaceOpt != null && this.CurrentToken.Kind != SyntaxKind.OpenBraceToken && this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { Debug.Assert(typeParameterList == null, "Exit condition of ParseMemberName in this scenario"); // No need for a diagnostic, ParseMemberName has already added one. var missingIdentifier = (identifierOrThisOpt == null) ? CreateMissingIdentifierToken() : identifierOrThisOpt; var missingAccessorList = _syntaxFactory.AccessorList( SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken), default(SyntaxList<AccessorDeclarationSyntax>), SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)); return _syntaxFactory.EventDeclaration( attributes, modifiers.ToList(), eventToken, type, explicitInterfaceOpt, //already has an appropriate error attached missingIdentifier, missingAccessorList, semicolonToken: null); } SyntaxToken identifier; if (identifierOrThisOpt == null) { identifier = CreateMissingIdentifierToken(); } else if (identifierOrThisOpt.Kind != SyntaxKind.IdentifierToken) { Debug.Assert(identifierOrThisOpt.Kind == SyntaxKind.ThisKeyword); identifier = ConvertToMissingWithTrailingTrivia(identifierOrThisOpt, SyntaxKind.IdentifierToken); } else { identifier = identifierOrThisOpt; } Debug.Assert(identifier != null); Debug.Assert(identifier.Kind == SyntaxKind.IdentifierToken); if (identifier.IsMissing && !type.IsMissing) { identifier = this.AddError(identifier, ErrorCode.ERR_IdentifierExpected); } if (typeParameterList != null) // check to see if the user tried to create a generic event. { identifier = AddTrailingSkippedSyntax(identifier, typeParameterList); identifier = this.AddError(identifier, ErrorCode.ERR_UnexpectedGenericName); } AccessorListSyntax accessorList = null; SyntaxToken semicolon = null; if (explicitInterfaceOpt != null && this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { semicolon = this.EatToken(SyntaxKind.SemicolonToken); } else { accessorList = this.ParseAccessorList(isEvent: true); } var decl = _syntaxFactory.EventDeclaration( attributes, modifiers.ToList(), eventToken, type, explicitInterfaceOpt, identifier, accessorList, semicolon); decl = EatUnexpectedTrailingSemicolon(decl); return decl; } private TNode EatUnexpectedTrailingSemicolon<TNode>(TNode decl) where TNode : CSharpSyntaxNode { // allow for case of one unexpected semicolon... if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { var semi = this.EatToken(); semi = this.AddError(semi, ErrorCode.ERR_UnexpectedSemicolon); decl = AddTrailingSkippedSyntax(decl, semi); } return decl; } private FieldDeclarationSyntax ParseNormalFieldDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, TypeSyntax type, SyntaxKind parentKind) { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFieldDeclaration; var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseVariableDeclarators(type, flags: 0, variables: variables, parentKind: parentKind); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.FieldDeclaration( attributes, modifiers.ToList(), _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _termState = saveTerm; _pool.Free(variables); } } private EventFieldDeclarationSyntax ParseEventFieldDeclaration( SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxToken eventToken, TypeSyntax type, SyntaxKind parentKind) { // An attribute specified on an event declaration that omits event accessors can apply // to the event being declared, to the associated field (if the event is not abstract), // or to the associated add and remove methods. In the absence of an // attribute-target-specifier, the attribute applies to the event. The presence of the // event attribute-target-specifier indicates that the attribute applies to the event; // the presence of the field attribute-target-specifier indicates that the attribute // applies to the field; and the presence of the method attribute-target-specifier // indicates that the attribute applies to the methods. // // NOTE(cyrusn): We allow more than the above here. Specifically, even if the event is // abstract, we allow the attribute to specify that it belongs to a field. Later, in the // semantic pass, we will disallow this. var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFieldDeclaration; var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseVariableDeclarators(type, flags: 0, variables: variables, parentKind: parentKind); if (this.CurrentToken.Kind == SyntaxKind.DotToken) { eventToken = this.AddError(eventToken, ErrorCode.ERR_ExplicitEventFieldImpl); // Better error message for confusing event situation. } var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.EventFieldDeclaration( attributes, modifiers.ToList(), eventToken, _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _termState = saveTerm; _pool.Free(variables); } } private bool IsEndOfFieldDeclaration() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken; } private void ParseVariableDeclarators(TypeSyntax type, VariableFlags flags, SeparatedSyntaxListBuilder<VariableDeclaratorSyntax> variables, SyntaxKind parentKind) { // Although we try parse variable declarations in contexts where they are not allowed (non-interactive top-level or a namespace) // the reported errors should take into consideration whether or not one expects them in the current context. bool variableDeclarationsExpected = parentKind != SyntaxKind.NamespaceDeclaration && parentKind != SyntaxKind.FileScopedNamespaceDeclaration && (parentKind != SyntaxKind.CompilationUnit || IsScript); LocalFunctionStatementSyntax localFunction; ParseVariableDeclarators( type: type, flags: flags, variables: variables, variableDeclarationsExpected: variableDeclarationsExpected, allowLocalFunctions: false, attributes: default, mods: default, localFunction: out localFunction); Debug.Assert(localFunction == null); } private void ParseVariableDeclarators( TypeSyntax type, VariableFlags flags, SeparatedSyntaxListBuilder<VariableDeclaratorSyntax> variables, bool variableDeclarationsExpected, bool allowLocalFunctions, SyntaxList<AttributeListSyntax> attributes, SyntaxList<SyntaxToken> mods, out LocalFunctionStatementSyntax localFunction) { variables.Add( this.ParseVariableDeclarator( type, flags, isFirst: true, allowLocalFunctions: allowLocalFunctions, attributes: attributes, mods: mods, localFunction: out localFunction)); if (localFunction != null) { // ParseVariableDeclarator returns null, so it is not added to variables Debug.Assert(variables.Count == 0); return; } while (true) { if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { variables.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); variables.Add( this.ParseVariableDeclarator( type, flags, isFirst: false, allowLocalFunctions: false, attributes: attributes, mods: mods, localFunction: out localFunction)); } else if (!variableDeclarationsExpected || this.SkipBadVariableListTokens(variables, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } private PostSkipAction SkipBadVariableListTokens(SeparatedSyntaxListBuilder<VariableDeclaratorSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken, p => p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsTerminator(), expected); } [Flags] private enum VariableFlags { Fixed = 0x01, Const = 0x02, Local = 0x04 } private static SyntaxTokenList GetOriginalModifiers(CSharp.CSharpSyntaxNode decl) { if (decl != null) { switch (decl.Kind()) { case SyntaxKind.FieldDeclaration: return ((CSharp.Syntax.FieldDeclarationSyntax)decl).Modifiers; case SyntaxKind.MethodDeclaration: return ((CSharp.Syntax.MethodDeclarationSyntax)decl).Modifiers; case SyntaxKind.ConstructorDeclaration: return ((CSharp.Syntax.ConstructorDeclarationSyntax)decl).Modifiers; case SyntaxKind.DestructorDeclaration: return ((CSharp.Syntax.DestructorDeclarationSyntax)decl).Modifiers; case SyntaxKind.PropertyDeclaration: return ((CSharp.Syntax.PropertyDeclarationSyntax)decl).Modifiers; case SyntaxKind.EventFieldDeclaration: return ((CSharp.Syntax.EventFieldDeclarationSyntax)decl).Modifiers; case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return ((CSharp.Syntax.AccessorDeclarationSyntax)decl).Modifiers; case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((CSharp.Syntax.TypeDeclarationSyntax)decl).Modifiers; case SyntaxKind.DelegateDeclaration: return ((CSharp.Syntax.DelegateDeclarationSyntax)decl).Modifiers; } } return default(SyntaxTokenList); } private static bool WasFirstVariable(CSharp.Syntax.VariableDeclaratorSyntax variable) { var parent = GetOldParent(variable) as CSharp.Syntax.VariableDeclarationSyntax; if (parent != null) { return parent.Variables[0] == variable; } return false; } private static VariableFlags GetOriginalVariableFlags(CSharp.Syntax.VariableDeclaratorSyntax old) { var parent = GetOldParent(old); var mods = GetOriginalModifiers(parent); VariableFlags flags = default(VariableFlags); if (mods.Any(SyntaxKind.FixedKeyword)) { flags |= VariableFlags.Fixed; } if (mods.Any(SyntaxKind.ConstKeyword)) { flags |= VariableFlags.Const; } if (parent != null && (parent.Kind() == SyntaxKind.VariableDeclaration || parent.Kind() == SyntaxKind.LocalDeclarationStatement)) { flags |= VariableFlags.Local; } return flags; } private static bool CanReuseVariableDeclarator(CSharp.Syntax.VariableDeclaratorSyntax old, VariableFlags flags, bool isFirst) { if (old == null) { return false; } SyntaxKind oldKind; return (flags == GetOriginalVariableFlags(old)) && (isFirst == WasFirstVariable(old)) && old.Initializer == null // can't reuse node that possibly ends in an expression && (oldKind = GetOldParent(old).Kind()) != SyntaxKind.VariableDeclaration // or in a method body && oldKind != SyntaxKind.LocalDeclarationStatement; } private VariableDeclaratorSyntax ParseVariableDeclarator( TypeSyntax parentType, VariableFlags flags, bool isFirst, bool allowLocalFunctions, SyntaxList<AttributeListSyntax> attributes, SyntaxList<SyntaxToken> mods, out LocalFunctionStatementSyntax localFunction, bool isExpressionContext = false) { if (this.IsIncrementalAndFactoryContextMatches && CanReuseVariableDeclarator(this.CurrentNode as CSharp.Syntax.VariableDeclaratorSyntax, flags, isFirst)) { localFunction = null; return (VariableDeclaratorSyntax)this.EatNode(); } if (!isExpressionContext) { // Check for the common pattern of: // // C //<-- here // Console.WriteLine(); // // Standard greedy parsing will assume that this should be parsed as a variable // declaration: "C Console". We want to avoid that as it can confused parts of the // system further up. So, if we see certain things following the identifier, then we can // assume it's not the actual name. // // So, if we're after a newline and we see a name followed by the list below, then we // assume that we're accidentally consuming too far into the next statement. // // <dot>, <arrow>, any binary operator (except =), <question>. None of these characters // are allowed in a normal variable declaration. This also provides a more useful error // message to the user. Instead of telling them that a semicolon is expected after the // following token, then instead get a useful message about an identifier being missing. // The above list prevents: // // C //<-- here // Console.WriteLine(); // // C //<-- here // Console->WriteLine(); // // C // A + B; // // C // A ? B : D; // // C // A() var resetPoint = this.GetResetPoint(); try { var currentTokenKind = this.CurrentToken.Kind; if (currentTokenKind == SyntaxKind.IdentifierToken && !parentType.IsMissing) { var isAfterNewLine = parentType.GetLastToken().TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia); if (isAfterNewLine) { int offset, width; this.GetDiagnosticSpanForMissingToken(out offset, out width); this.EatToken(); currentTokenKind = this.CurrentToken.Kind; var isNonEqualsBinaryToken = currentTokenKind != SyntaxKind.EqualsToken && SyntaxFacts.IsBinaryExpressionOperatorToken(currentTokenKind); if (currentTokenKind == SyntaxKind.DotToken || currentTokenKind == SyntaxKind.OpenParenToken || currentTokenKind == SyntaxKind.MinusGreaterThanToken || isNonEqualsBinaryToken) { var isPossibleLocalFunctionToken = currentTokenKind == SyntaxKind.OpenParenToken || currentTokenKind == SyntaxKind.LessThanToken; // Make sure this isn't a local function if (!isPossibleLocalFunctionToken || !IsLocalFunctionAfterIdentifier()) { var missingIdentifier = CreateMissingIdentifierToken(); missingIdentifier = this.AddError(missingIdentifier, offset, width, ErrorCode.ERR_IdentifierExpected); localFunction = null; return _syntaxFactory.VariableDeclarator(missingIdentifier, null, null); } } } } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } // NOTE: Diverges from Dev10. // // When we see parse an identifier and we see the partial contextual keyword, we check // to see whether it is already attached to a partial class or partial method // declaration. However, in the specific case of variable declarators, Dev10 // specifically treats it as a variable name, even if it could be interpreted as a // keyword. var name = this.ParseIdentifierToken(); BracketedArgumentListSyntax argumentList = null; EqualsValueClauseSyntax initializer = null; TerminatorState saveTerm = _termState; bool isFixed = (flags & VariableFlags.Fixed) != 0; bool isConst = (flags & VariableFlags.Const) != 0; bool isLocal = (flags & VariableFlags.Local) != 0; // Give better error message in the case where the user did something like: // // X x = 1, Y y = 2; // using (X x = expr1, Y y = expr2) ... // // The superfluous type name is treated as variable (it is an identifier) and a missing ',' is injected after it. if (!isFirst && this.IsTrueIdentifier()) { name = this.AddError(name, ErrorCode.ERR_MultiTypeInDeclaration); } switch (this.CurrentToken.Kind) { case SyntaxKind.EqualsToken: if (isFixed) { goto default; } var equals = this.EatToken(); SyntaxToken refKeyword = null; if (isLocal && !isConst && this.CurrentToken.Kind == SyntaxKind.RefKeyword) { refKeyword = this.EatToken(); refKeyword = CheckFeatureAvailability(refKeyword, MessageID.IDS_FeatureRefLocalsReturns); } var init = this.ParseVariableInitializer(); if (refKeyword != null) { init = _syntaxFactory.RefExpression(refKeyword, init); } initializer = _syntaxFactory.EqualsValueClause(equals, init); break; case SyntaxKind.LessThanToken: if (allowLocalFunctions && isFirst) { localFunction = TryParseLocalFunctionStatementBody(attributes, mods, parentType, name); if (localFunction != null) { return null; } } goto default; case SyntaxKind.OpenParenToken: if (allowLocalFunctions && isFirst) { localFunction = TryParseLocalFunctionStatementBody(attributes, mods, parentType, name); if (localFunction != null) { return null; } } // Special case for accidental use of C-style constructors // Fake up something to hold the arguments. _termState |= TerminatorState.IsPossibleEndOfVariableDeclaration; argumentList = this.ParseBracketedArgumentList(); _termState = saveTerm; argumentList = this.AddError(argumentList, ErrorCode.ERR_BadVarDecl); break; case SyntaxKind.OpenBracketToken: bool sawNonOmittedSize; _termState |= TerminatorState.IsPossibleEndOfVariableDeclaration; var specifier = this.ParseArrayRankSpecifier(sawNonOmittedSize: out sawNonOmittedSize); _termState = saveTerm; var open = specifier.OpenBracketToken; var sizes = specifier.Sizes; var close = specifier.CloseBracketToken; if (isFixed && !sawNonOmittedSize) { close = this.AddError(close, ErrorCode.ERR_ValueExpected); } var args = _pool.AllocateSeparated<ArgumentSyntax>(); try { var withSeps = sizes.GetWithSeparators(); foreach (var item in withSeps) { var expression = item as ExpressionSyntax; if (expression != null) { bool isOmitted = expression.Kind == SyntaxKind.OmittedArraySizeExpression; if (!isFixed && !isOmitted) { expression = this.AddError(expression, ErrorCode.ERR_ArraySizeInDeclaration); } args.Add(_syntaxFactory.Argument(null, refKindKeyword: null, expression)); } else { args.AddSeparator((SyntaxToken)item); } } argumentList = _syntaxFactory.BracketedArgumentList(open, args, close); if (!isFixed) { argumentList = this.AddError(argumentList, ErrorCode.ERR_CStyleArray); // If we have "int x[] = new int[10];" then parse the initializer. if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { goto case SyntaxKind.EqualsToken; } } } finally { _pool.Free(args); } break; default: if (isConst) { name = this.AddError(name, ErrorCode.ERR_ConstValueRequired); // Error here for missing constant initializers } else if (isFixed) { if (parentType.Kind == SyntaxKind.ArrayType) { // They accidentally put the array before the identifier name = this.AddError(name, ErrorCode.ERR_FixedDimsRequired); } else { goto case SyntaxKind.OpenBracketToken; } } break; } localFunction = null; return _syntaxFactory.VariableDeclarator(name, argumentList, initializer); } // Is there a local function after an eaten identifier? private bool IsLocalFunctionAfterIdentifier() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.OpenParenToken || this.CurrentToken.Kind == SyntaxKind.LessThanToken); var resetPoint = this.GetResetPoint(); try { var typeParameterListOpt = this.ParseTypeParameterList(); var paramList = ParseParenthesizedParameterList(); if (!paramList.IsMissing && (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken || this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword)) { return true; } return false; } finally { Reset(ref resetPoint); Release(ref resetPoint); } } private bool IsPossibleEndOfVariableDeclaration() { switch (this.CurrentToken.Kind) { case SyntaxKind.CommaToken: case SyntaxKind.SemicolonToken: return true; default: return false; } } private ExpressionSyntax ParseVariableInitializer() { switch (this.CurrentToken.Kind) { case SyntaxKind.OpenBraceToken: return this.ParseArrayInitializer(); default: return this.ParseExpressionCore(); } } private bool IsPossibleVariableInitializer() { return this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.IsPossibleExpression(); } private FieldDeclarationSyntax ParseConstantFieldDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers, SyntaxKind parentKind) { var constToken = this.EatToken(SyntaxKind.ConstKeyword); modifiers.Add(constToken); var type = this.ParseType(); var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseVariableDeclarators(type, VariableFlags.Const, variables, parentKind); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.FieldDeclaration( attributes, modifiers.ToList(), _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _pool.Free(variables); } } private DelegateDeclarationSyntax ParseDelegateDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.DelegateKeyword); var delegateToken = this.EatToken(SyntaxKind.DelegateKeyword); var type = this.ParseReturnType(); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfMethodSignature; var name = this.ParseIdentifierToken(); var typeParameters = this.ParseTypeParameterList(); var parameterList = this.ParseParenthesizedParameterList(); var constraints = default(SyntaxListBuilder<TypeParameterConstraintClauseSyntax>); try { if (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { constraints = _pool.Allocate<TypeParameterConstraintClauseSyntax>(); this.ParseTypeParameterConstraintClauses(constraints); } _termState = saveTerm; var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.DelegateDeclaration(attributes, modifiers.ToList(), delegateToken, type, name, typeParameters, parameterList, constraints, semicolon); } finally { if (!constraints.IsNull) { _pool.Free(constraints); } } } private EnumDeclarationSyntax ParseEnumDeclaration(SyntaxList<AttributeListSyntax> attributes, SyntaxListBuilder modifiers) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.EnumKeyword); var enumToken = this.EatToken(SyntaxKind.EnumKeyword); var name = this.ParseIdentifierToken(); // check to see if the user tried to create a generic enum. var typeParameters = this.ParseTypeParameterList(); if (typeParameters != null) { name = AddTrailingSkippedSyntax(name, typeParameters); name = this.AddError(name, ErrorCode.ERR_UnexpectedGenericName); } BaseListSyntax baseList = null; if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { var colon = this.EatToken(SyntaxKind.ColonToken); var type = this.ParseType(); var tmpList = _pool.AllocateSeparated<BaseTypeSyntax>(); tmpList.Add(_syntaxFactory.SimpleBaseType(type)); baseList = _syntaxFactory.BaseList(colon, tmpList); _pool.Free(tmpList); } var members = default(SeparatedSyntaxList<EnumMemberDeclarationSyntax>); var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); if (!openBrace.IsMissing) { var builder = _pool.AllocateSeparated<EnumMemberDeclarationSyntax>(); try { this.ParseEnumMemberDeclarations(ref openBrace, builder); members = builder.ToList(); } finally { _pool.Free(builder); } } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); var semicolon = TryEatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.EnumDeclaration( attributes, modifiers.ToList(), enumToken, name, baseList, openBrace, members, closeBrace, semicolon); } private void ParseEnumMemberDeclarations( ref SyntaxToken openBrace, SeparatedSyntaxListBuilder<EnumMemberDeclarationSyntax> members) { if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsPossibleEnumMemberDeclaration() || this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { // first member members.Add(this.ParseEnumMemberDeclaration()); // additional members while (true) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.IsPossibleEnumMemberDeclaration()) { if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { // semicolon instead of comma.. consume it with error and act as if it were a comma. members.AddSeparator(this.EatTokenWithPrejudice(SyntaxKind.CommaToken)); } else { members.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); } // check for exit case after legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (!this.IsPossibleEnumMemberDeclaration()) { goto tryAgain; } members.Add(this.ParseEnumMemberDeclaration()); continue; } else if (this.SkipBadEnumMemberListTokens(ref openBrace, members, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadEnumMemberListTokens(ref openBrace, members, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } } private PostSkipAction SkipBadEnumMemberListTokens(ref SyntaxToken openBrace, SeparatedSyntaxListBuilder<EnumMemberDeclarationSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openBrace, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && p.CurrentToken.Kind != SyntaxKind.SemicolonToken && !p.IsPossibleEnumMemberDeclaration(), p => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken || p.IsTerminator(), expected); } private EnumMemberDeclarationSyntax ParseEnumMemberDeclaration() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.EnumMemberDeclaration) { return (EnumMemberDeclarationSyntax)this.EatNode(); } var memberAttrs = this.ParseAttributeDeclarations(); var memberName = this.ParseIdentifierToken(); EqualsValueClauseSyntax equalsValue = null; if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { var equals = this.EatToken(SyntaxKind.EqualsToken); ExpressionSyntax value; if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { //an identifier is a valid expression value = this.ParseIdentifierName(ErrorCode.ERR_ConstantExpected); } else { value = this.ParseExpressionCore(); } equalsValue = _syntaxFactory.EqualsValueClause(equals, value: value); } return _syntaxFactory.EnumMemberDeclaration(memberAttrs, modifiers: default, memberName, equalsValue); } private bool IsPossibleEnumMemberDeclaration() { return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken || this.IsTrueIdentifier(); } private bool IsDotOrColonColon() { return this.CurrentToken.Kind == SyntaxKind.DotToken || this.CurrentToken.Kind == SyntaxKind.ColonColonToken; } // This is public and parses open types. You probably don't want to use it. public NameSyntax ParseName() { return this.ParseQualifiedName(); } private IdentifierNameSyntax CreateMissingIdentifierName() { return _syntaxFactory.IdentifierName(CreateMissingIdentifierToken()); } private static SyntaxToken CreateMissingIdentifierToken() { return SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken); } [Flags] private enum NameOptions { None = 0, InExpression = 1 << 0, // Used to influence parser ambiguity around "<" and generics vs. expressions. Used in ParseSimpleName. InTypeList = 1 << 1, // Allows attributes to appear within the generic type argument list. Used during ParseInstantiation. PossiblePattern = 1 << 2, // Used to influence parser ambiguity around "<" and generics vs. expressions on the right of 'is' AfterIs = 1 << 3, DefinitePattern = 1 << 4, AfterOut = 1 << 5, AfterTupleComma = 1 << 6, FirstElementOfPossibleTupleLiteral = 1 << 7, } /// <summary> /// True if current identifier token is not really some contextual keyword /// </summary> /// <returns></returns> private bool IsTrueIdentifier() { if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken) { if (!IsCurrentTokenPartialKeywordOfPartialMethodOrType() && !IsCurrentTokenQueryKeywordInQuery() && !IsCurrentTokenWhereOfConstraintClause()) { return true; } } return false; } /// <summary> /// True if the given token is not really some contextual keyword. /// This method is for use in executable code, as it treats <c>partial</c> as an identifier. /// </summary> private bool IsTrueIdentifier(SyntaxToken token) { return token.Kind == SyntaxKind.IdentifierToken && !(this.IsInQuery && IsTokenQueryContextualKeyword(token)); } private IdentifierNameSyntax ParseIdentifierName(ErrorCode code = ErrorCode.ERR_IdentifierExpected) { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.IdentifierName) { if (!SyntaxFacts.IsContextualKeyword(((CSharp.Syntax.IdentifierNameSyntax)this.CurrentNode).Identifier.Kind())) { return (IdentifierNameSyntax)this.EatNode(); } } var tk = ParseIdentifierToken(code); return SyntaxFactory.IdentifierName(tk); } private SyntaxToken ParseIdentifierToken(ErrorCode code = ErrorCode.ERR_IdentifierExpected) { var ctk = this.CurrentToken.Kind; if (ctk == SyntaxKind.IdentifierToken) { // Error tolerance for IntelliSense. Consider the following case: [EditorBrowsable( partial class Goo { // } Because we're parsing an attribute argument we'll end up consuming the "partial" identifier and // we'll eventually end up in a pretty confused state. Because of that it becomes very difficult to // show the correct parameter help in this case. So, when we see "partial" we check if it's being used // as an identifier or as a contextual keyword. If it's the latter then we bail out. See // Bug: vswhidbey/542125 if (IsCurrentTokenPartialKeywordOfPartialMethodOrType() || IsCurrentTokenQueryKeywordInQuery()) { var result = CreateMissingIdentifierToken(); result = this.AddError(result, ErrorCode.ERR_InvalidExprTerm, this.CurrentToken.Text); return result; } SyntaxToken identifierToken = this.EatToken(); if (this.IsInAsync && identifierToken.ContextualKind == SyntaxKind.AwaitKeyword) { identifierToken = this.AddError(identifierToken, ErrorCode.ERR_BadAwaitAsIdentifier); } return identifierToken; } else { var name = CreateMissingIdentifierToken(); name = this.AddError(name, code); return name; } } private bool IsCurrentTokenQueryKeywordInQuery() { return this.IsInQuery && this.IsCurrentTokenQueryContextualKeyword; } private bool IsCurrentTokenPartialKeywordOfPartialMethodOrType() { if (this.CurrentToken.ContextualKind == SyntaxKind.PartialKeyword) { if (this.IsPartialType() || this.IsPartialMember()) { return true; } } return false; } private TypeParameterListSyntax ParseTypeParameterList() { if (this.CurrentToken.Kind != SyntaxKind.LessThanToken) { return null; } var saveTerm = _termState; _termState |= TerminatorState.IsEndOfTypeParameterList; try { var parameters = _pool.AllocateSeparated<TypeParameterSyntax>(); var open = this.EatToken(SyntaxKind.LessThanToken); open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics); // first parameter parameters.Add(this.ParseTypeParameter()); // remaining parameter & commas while (true) { if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken || this.IsCurrentTokenWhereOfConstraintClause()) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { parameters.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); parameters.Add(this.ParseTypeParameter()); } else if (this.SkipBadTypeParameterListTokens(parameters, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } var close = this.EatToken(SyntaxKind.GreaterThanToken); return _syntaxFactory.TypeParameterList(open, parameters, close); } finally { _termState = saveTerm; } } private PostSkipAction SkipBadTypeParameterListTokens(SeparatedSyntaxListBuilder<TypeParameterSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken, p => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken || p.IsTerminator(), expected); } private TypeParameterSyntax ParseTypeParameter() { if (this.IsCurrentTokenWhereOfConstraintClause()) { return _syntaxFactory.TypeParameter( default(SyntaxList<AttributeListSyntax>), varianceKeyword: null, this.AddError(CreateMissingIdentifierToken(), ErrorCode.ERR_IdentifierExpected)); } var attrs = default(SyntaxList<AttributeListSyntax>); if (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken && this.PeekToken(1).Kind != SyntaxKind.CloseBracketToken) { var saveTerm = _termState; _termState = TerminatorState.IsEndOfTypeArgumentList; attrs = this.ParseAttributeDeclarations(); _termState = saveTerm; } SyntaxToken varianceToken = null; if (this.CurrentToken.Kind == SyntaxKind.InKeyword || this.CurrentToken.Kind == SyntaxKind.OutKeyword) { varianceToken = CheckFeatureAvailability(this.EatToken(), MessageID.IDS_FeatureTypeVariance); } return _syntaxFactory.TypeParameter(attrs, varianceToken, this.ParseIdentifierToken()); } // Parses the parts of the names between Dots and ColonColons. private SimpleNameSyntax ParseSimpleName(NameOptions options = NameOptions.None) { var id = this.ParseIdentifierName(); if (id.Identifier.IsMissing) { return id; } // You can pass ignore generics if you don't even want the parser to consider generics at all. // The name parsing will then stop at the first "<". It doesn't make sense to pass both Generic and IgnoreGeneric. SimpleNameSyntax name = id; if (this.CurrentToken.Kind == SyntaxKind.LessThanToken) { var pt = this.GetResetPoint(); var kind = this.ScanTypeArgumentList(options); this.Reset(ref pt); this.Release(ref pt); if (kind == ScanTypeArgumentListKind.DefiniteTypeArgumentList || (kind == ScanTypeArgumentListKind.PossibleTypeArgumentList && (options & NameOptions.InTypeList) != 0)) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.LessThanToken); SyntaxToken open; var types = _pool.AllocateSeparated<TypeSyntax>(); SyntaxToken close; this.ParseTypeArgumentList(out open, types, out close); name = _syntaxFactory.GenericName(id.Identifier, _syntaxFactory.TypeArgumentList(open, types, close)); _pool.Free(types); } } return name; } private enum ScanTypeArgumentListKind { NotTypeArgumentList, PossibleTypeArgumentList, DefiniteTypeArgumentList } private ScanTypeArgumentListKind ScanTypeArgumentList(NameOptions options) { if (this.CurrentToken.Kind != SyntaxKind.LessThanToken) { return ScanTypeArgumentListKind.NotTypeArgumentList; } if ((options & NameOptions.InExpression) == 0) { return ScanTypeArgumentListKind.DefiniteTypeArgumentList; } // We're in an expression context, and we have a < token. This could be a // type argument list, or it could just be a relational expression. // // Scan just the type argument list portion (i.e. the part from < to > ) to // see what we think it could be. This will give us one of three possibilities: // // result == ScanTypeFlags.NotType. // // This is absolutely not a type-argument-list. Just return that result immediately. // // result != ScanTypeFlags.NotType && isDefinitelyTypeArgumentList. // // This is absolutely a type-argument-list. Just return that result immediately // // result != ScanTypeFlags.NotType && !isDefinitelyTypeArgumentList. // // This could be a type-argument list, or it could be an expression. Need to see // what came after the last '>' to find out which it is. // Scan for a type argument list. If we think it's a type argument list // then assume it is unless we see specific tokens following it. SyntaxToken lastTokenOfList = null; ScanTypeFlags possibleTypeArgumentFlags = ScanPossibleTypeArgumentList( ref lastTokenOfList, out bool isDefinitelyTypeArgumentList); if (possibleTypeArgumentFlags == ScanTypeFlags.NotType) { return ScanTypeArgumentListKind.NotTypeArgumentList; } if (isDefinitelyTypeArgumentList) { return ScanTypeArgumentListKind.DefiniteTypeArgumentList; } // If we did not definitively determine from immediate syntax that it was or // was not a type argument list, we must have scanned the entire thing up through // the closing greater-than token. In that case we will disambiguate based on the // token that follows it. Debug.Assert(lastTokenOfList.Kind == SyntaxKind.GreaterThanToken); switch (this.CurrentToken.Kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.CloseParenToken: case SyntaxKind.CloseBracketToken: case SyntaxKind.CloseBraceToken: case SyntaxKind.ColonToken: case SyntaxKind.SemicolonToken: case SyntaxKind.CommaToken: case SyntaxKind.DotToken: case SyntaxKind.QuestionToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.BarToken: case SyntaxKind.CaretToken: // These tokens are from 7.5.4.2 Grammar Ambiguities return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.AmpersandAmpersandToken: // e.g. `e is A<B> && e` case SyntaxKind.BarBarToken: // e.g. `e is A<B> || e` case SyntaxKind.AmpersandToken: // e.g. `e is A<B> & e` case SyntaxKind.OpenBracketToken: // e.g. `e is A<B>[]` case SyntaxKind.LessThanToken: // e.g. `e is A<B> < C` case SyntaxKind.LessThanEqualsToken: // e.g. `e is A<B> <= C` case SyntaxKind.GreaterThanEqualsToken: // e.g. `e is A<B> >= C` case SyntaxKind.IsKeyword: // e.g. `e is A<B> is bool` case SyntaxKind.AsKeyword: // e.g. `e is A<B> as bool` // These tokens were added to 7.5.4.2 Grammar Ambiguities in C# 7.0 return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.OpenBraceToken: // e.g. `e is A<B> {}` // This token was added to 7.5.4.2 Grammar Ambiguities in C# 8.0 return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.GreaterThanToken when ((options & NameOptions.AfterIs) != 0) && this.PeekToken(1).Kind != SyntaxKind.GreaterThanToken: // This token is added to 7.5.4.2 Grammar Ambiguities in C#7 for the special case in which // the possible generic is following an `is` keyword, e.g. `e is A<B> > C`. // We test one further token ahead because a right-shift operator `>>` looks like a pair of greater-than // tokens at this stage, but we don't intend to be handling the right-shift operator. // The upshot is that we retain compatibility with the two previous behaviors: // `(x is A<B>>C)` is parsed as `(x is A<B>) > C` // `A<B>>C` elsewhere is parsed as `A < (B >> C)` return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.IdentifierToken: // C#7: In certain contexts, we treat *identifier* as a disambiguating token. Those // contexts are where the sequence of tokens being disambiguated is immediately preceded by one // of the keywords is, case, or out, or arises while parsing the first element of a tuple literal // (in which case the tokens are preceded by `(` and the identifier is followed by a `,`) or a // subsequent element of a tuple literal (in which case the tokens are preceded by `,` and the // identifier is followed by a `,` or `)`). // In C#8 (or whenever recursive patterns are introduced) we also treat an identifier as a // disambiguating token if we're parsing the type of a pattern. // Note that we treat query contextual keywords (which appear here as identifiers) as disambiguating tokens as well. if ((options & (NameOptions.AfterIs | NameOptions.DefinitePattern | NameOptions.AfterOut)) != 0 || (options & NameOptions.AfterTupleComma) != 0 && (this.PeekToken(1).Kind == SyntaxKind.CommaToken || this.PeekToken(1).Kind == SyntaxKind.CloseParenToken) || (options & NameOptions.FirstElementOfPossibleTupleLiteral) != 0 && this.PeekToken(1).Kind == SyntaxKind.CommaToken ) { // we allow 'G<T,U> x' as a pattern-matching operation and a declaration expression in a tuple. return ScanTypeArgumentListKind.DefiniteTypeArgumentList; } return ScanTypeArgumentListKind.PossibleTypeArgumentList; case SyntaxKind.EndOfFileToken: // e.g. `e is A<B>` // This is useful for parsing expressions in isolation return ScanTypeArgumentListKind.DefiniteTypeArgumentList; case SyntaxKind.EqualsGreaterThanToken: // e.g. `e switch { A<B> => 1 }` // This token was added to 7.5.4.2 Grammar Ambiguities in C# 9.0 return ScanTypeArgumentListKind.DefiniteTypeArgumentList; default: return ScanTypeArgumentListKind.PossibleTypeArgumentList; } } private ScanTypeFlags ScanPossibleTypeArgumentList( ref SyntaxToken lastTokenOfList, out bool isDefinitelyTypeArgumentList) { isDefinitelyTypeArgumentList = false; if (this.CurrentToken.Kind == SyntaxKind.LessThanToken) { ScanTypeFlags result = ScanTypeFlags.GenericTypeOrExpression; do { lastTokenOfList = this.EatToken(); // Type arguments cannot contain attributes, so if this is an open square, we early out and assume it is not a type argument if (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken) { lastTokenOfList = null; return ScanTypeFlags.NotType; } if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken) { lastTokenOfList = EatToken(); return result; } switch (this.ScanType(out lastTokenOfList)) { case ScanTypeFlags.NotType: lastTokenOfList = null; return ScanTypeFlags.NotType; case ScanTypeFlags.MustBeType: // We're currently scanning a possible type-argument list. But we're // not sure if this is actually a type argument list, or is maybe some // complex relational expression with <'s and >'s. One thing we can // tell though is that if we have a predefined type (like 'int' or 'string') // before a comma or > then this is definitely a type argument list. i.e. // if you have: // // var v = ImmutableDictionary<int, // // then there's no legal interpretation of this as an expression (since a // standalone predefined type is not a valid simple term. Contrast that // with : // // var v = ImmutableDictionary<Int32, // // Here this might actually be a relational expression and the comma is meant // to separate out the variable declarator 'v' from the next variable. // // Note: we check if we got 'MustBeType' which triggers for predefined types, // (int, string, etc.), or array types (Goo[], A<T>[][] etc.), or pointer types // of things that must be types (int*, void**, etc.). isDefinitelyTypeArgumentList = DetermineIfDefinitelyTypeArgumentList(isDefinitelyTypeArgumentList); result = ScanTypeFlags.GenericTypeOrMethod; break; // case ScanTypeFlags.TupleType: // It would be nice if we saw a tuple to state that we definitely had a // type argument list. However, there are cases where this would not be // true. For example: // // public class C // { // public static void Main() // { // XX X = default; // int a = 1, b = 2; // bool z = X < (a, b), w = false; // } // } // // struct XX // { // public static bool operator <(XX x, (int a, int b) arg) => true; // public static bool operator >(XX x, (int a, int b) arg) => false; // } case ScanTypeFlags.NullableType: // See above. If we have X<Y?, or X<Y?>, then this is definitely a type argument list. isDefinitelyTypeArgumentList = DetermineIfDefinitelyTypeArgumentList(isDefinitelyTypeArgumentList); if (isDefinitelyTypeArgumentList) { result = ScanTypeFlags.GenericTypeOrMethod; } // Note: we intentionally fall out without setting 'result'. // Seeing a nullable type (not followed by a , or > ) is not enough // information for us to determine what this is yet. i.e. the user may have: // // X < Y ? Z : W // // We'd see a nullable type here, but this is definitely not a type arg list. break; case ScanTypeFlags.GenericTypeOrExpression: // See above. If we have X<Y<Z>, then this would definitely be a type argument list. // However, if we have X<Y<Z>> then this might not be type argument list. This could just // be some sort of expression where we're comparing, and then shifting values. if (!isDefinitelyTypeArgumentList) { isDefinitelyTypeArgumentList = this.CurrentToken.Kind == SyntaxKind.CommaToken; result = ScanTypeFlags.GenericTypeOrMethod; } break; case ScanTypeFlags.GenericTypeOrMethod: result = ScanTypeFlags.GenericTypeOrMethod; break; } } while (this.CurrentToken.Kind == SyntaxKind.CommaToken); if (this.CurrentToken.Kind != SyntaxKind.GreaterThanToken) { lastTokenOfList = null; return ScanTypeFlags.NotType; } lastTokenOfList = this.EatToken(); return result; } return ScanTypeFlags.NonGenericTypeOrExpression; } private bool DetermineIfDefinitelyTypeArgumentList(bool isDefinitelyTypeArgumentList) { if (!isDefinitelyTypeArgumentList) { isDefinitelyTypeArgumentList = this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.GreaterThanToken; } return isDefinitelyTypeArgumentList; } // ParseInstantiation: Parses the generic argument/parameter parts of the name. private void ParseTypeArgumentList(out SyntaxToken open, SeparatedSyntaxListBuilder<TypeSyntax> types, out SyntaxToken close) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.LessThanToken); open = this.EatToken(SyntaxKind.LessThanToken); open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics); if (this.IsOpenName()) { // NOTE: trivia will be attached to comma, not omitted type argument var omittedTypeArgumentInstance = _syntaxFactory.OmittedTypeArgument(SyntaxFactory.Token(SyntaxKind.OmittedTypeArgumentToken)); types.Add(omittedTypeArgumentInstance); while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { types.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); types.Add(omittedTypeArgumentInstance); } close = this.EatToken(SyntaxKind.GreaterThanToken); return; } // first type types.Add(this.ParseTypeArgument()); // remaining types & commas while (true) { if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleType()) { types.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); types.Add(this.ParseTypeArgument()); } else if (this.SkipBadTypeArgumentListTokens(types, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } close = this.EatToken(SyntaxKind.GreaterThanToken); } private PostSkipAction SkipBadTypeArgumentListTokens(SeparatedSyntaxListBuilder<TypeSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleType(), p => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken || p.IsTerminator(), expected); } // Parses the individual generic parameter/arguments in a name. private TypeSyntax ParseTypeArgument() { var attrs = default(SyntaxList<AttributeListSyntax>); if (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken && this.PeekToken(1).Kind != SyntaxKind.CloseBracketToken) { // Here, if we see a "[" that looks like it has something in it, we parse // it as an attribute and then later put an error on the whole type if // it turns out that attributes are not allowed. // TODO: should there be another flag that controls this behavior? we have // "allowAttrs" but should there also be a "recognizeAttrs" that we can // set to false in an expression context? var saveTerm = _termState; _termState = TerminatorState.IsEndOfTypeArgumentList; attrs = this.ParseAttributeDeclarations(); _termState = saveTerm; } SyntaxToken varianceToken = null; if (this.CurrentToken.Kind == SyntaxKind.InKeyword || this.CurrentToken.Kind == SyntaxKind.OutKeyword) { // Recognize the variance syntax, but give an error as it's // only appropriate in a type parameter list. varianceToken = this.EatToken(); varianceToken = CheckFeatureAvailability(varianceToken, MessageID.IDS_FeatureTypeVariance); varianceToken = this.AddError(varianceToken, ErrorCode.ERR_IllegalVarianceSyntax); } var result = this.ParseType(); // Consider the case where someone supplies an invalid type argument // Such as Action<0> or Action<static>. In this case we generate a missing // identifier in ParseType, but if we continue as is we'll immediately start to // interpret 0 as the start of a new expression when we can tell it's most likely // meant to be part of the type list. // // To solve this we check if the current token is not comma or greater than and // the next token is a comma or greater than. If so we assume that the found // token is part of this expression and we attempt to recover. This does open // the door for cases where we have an incomplete line to be interpretted as // a single expression. For example: // // Action< // Incomplete line // a>b; // // However, this only happens when the following expression is of the form a>... // or a,... which means this case should happen less frequently than what we're // trying to solve here so we err on the side of better error messages // for the majority of cases. SyntaxKind nextTokenKind = SyntaxKind.None; if (result.IsMissing && (this.CurrentToken.Kind != SyntaxKind.CommaToken && this.CurrentToken.Kind != SyntaxKind.GreaterThanToken) && ((nextTokenKind = this.PeekToken(1).Kind) == SyntaxKind.CommaToken || nextTokenKind == SyntaxKind.GreaterThanToken)) { // Eat the current token and add it as skipped so we recover result = AddTrailingSkippedSyntax(result, this.EatToken()); } if (varianceToken != null) { result = AddLeadingSkippedSyntax(result, varianceToken); } if (attrs.Count > 0) { result = AddLeadingSkippedSyntax(result, attrs.Node); result = this.AddError(result, ErrorCode.ERR_TypeExpected); } return result; } private bool IsEndOfTypeArgumentList() => this.CurrentToken.Kind == SyntaxKind.GreaterThanToken; private bool IsOpenName() { bool isOpen = true; int n = 0; while (this.PeekToken(n).Kind == SyntaxKind.CommaToken) { n++; } if (this.PeekToken(n).Kind != SyntaxKind.GreaterThanToken) { isOpen = false; } return isOpen; } private void ParseMemberName( out ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, out SyntaxToken identifierOrThisOpt, out TypeParameterListSyntax typeParameterListOpt, bool isEvent) { identifierOrThisOpt = null; explicitInterfaceOpt = null; typeParameterListOpt = null; if (!IsPossibleMemberName()) { // No clue what this is. Just bail. Our caller will have to // move forward and try again. return; } NameSyntax explicitInterfaceName = null; SyntaxToken separator = null; ResetPoint beforeIdentifierPoint = default(ResetPoint); bool beforeIdentifierPointSet = false; try { while (true) { // Check if we got 'this'. If so, then we have an indexer. // Note: we parse out type parameters here as well so that // we can give a useful error about illegal generic indexers. if (this.CurrentToken.Kind == SyntaxKind.ThisKeyword) { beforeIdentifierPoint = GetResetPoint(); beforeIdentifierPointSet = true; identifierOrThisOpt = this.EatToken(); typeParameterListOpt = this.ParseTypeParameterList(); break; } // now, scan past the next name. if it's followed by a dot then // it's part of the explicit name we're building up. Otherwise, // it's the name of the member. var point = GetResetPoint(); bool isMemberName; try { ScanNamedTypePart(); isMemberName = !IsDotOrColonColonOrDotDot(); } finally { this.Reset(ref point); this.Release(ref point); } if (isMemberName) { // We're past any explicit interface portion and We've // gotten to the member name. beforeIdentifierPoint = GetResetPoint(); beforeIdentifierPointSet = true; if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) { separator = this.AddError(separator, ErrorCode.ERR_AliasQualAsExpression); separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } identifierOrThisOpt = this.ParseIdentifierToken(); typeParameterListOpt = this.ParseTypeParameterList(); break; } else { // If we saw a . or :: then we must have something explicit. AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator); } } if (explicitInterfaceName != null) { if (separator.Kind != SyntaxKind.DotToken) { separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, separator.GetLeadingTriviaWidth(), separator.Width)); separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } if (isEvent && this.CurrentToken.Kind != SyntaxKind.OpenBraceToken && this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { // CS0071: If you're explicitly implementing an event field, you have to use the accessor form // // Good: // event EventDelegate Parent.E // { // add { ... } // remove { ... } // } // // Bad: // event EventDelegate Parent. // E( //(or anything that is not the semicolon // // To recover: rollback to before the name of the field was parsed (just the part after the last // dot), insert a missing identifier for the field name, insert missing accessors, and then treat // the event name that's actually there as the beginning of a new member. e.g. // // event EventDelegate Parent./*Missing nodes here*/ // // E( // // Rationale: The identifier could be the name of a type at the beginning of an existing member // declaration (above which someone has started to type an explicit event implementation). // // In case the dot doesn't follow with an end line or E ends with a semicolon, the error recovery // is skipped. In that case the rationale above does not fit very well. explicitInterfaceOpt = _syntaxFactory.ExplicitInterfaceSpecifier( explicitInterfaceName, AddError(separator, ErrorCode.ERR_ExplicitEventFieldImpl)); if (separator.TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia)) { Debug.Assert(beforeIdentifierPointSet); Reset(ref beforeIdentifierPoint); //clear fields that were populated after the reset point identifierOrThisOpt = null; typeParameterListOpt = null; } } else { explicitInterfaceOpt = _syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator); } } } finally { if (beforeIdentifierPointSet) { Release(ref beforeIdentifierPoint); } } } private void AccumulateExplicitInterfaceName(ref NameSyntax explicitInterfaceName, ref SyntaxToken separator) { // first parse the upcoming name portion. var saveTerm = _termState; _termState |= TerminatorState.IsEndOfNameInExplicitInterface; if (explicitInterfaceName == null) { // If this is the first time, then just get the next simple // name and store it as the explicit interface name. explicitInterfaceName = this.ParseSimpleName(NameOptions.InTypeList); // Now, get the next separator. if (this.CurrentToken.Kind == SyntaxKind.DotDotToken) { // Error recovery as in ParseQualifiedNameRight. If we have `X..Y` break that into `X.<missing-id>.Y` separator = this.EatToken(); explicitInterfaceName = RecoverFromDotDot(explicitInterfaceName, ref separator); } else { separator = this.CurrentToken.Kind == SyntaxKind.ColonColonToken ? this.EatToken() // fine after the first identifier : this.EatToken(SyntaxKind.DotToken); } } else { // Parse out the next part and combine it with the // current explicit name to form the new explicit name. var tmp = this.ParseQualifiedNameRight(NameOptions.InTypeList, explicitInterfaceName, separator); Debug.Assert(!ReferenceEquals(tmp, explicitInterfaceName), "We should have consumed something and updated explicitInterfaceName"); explicitInterfaceName = tmp; // Now, get the next separator. if (this.CurrentToken.Kind == SyntaxKind.ColonColonToken) { separator = this.EatToken(); separator = this.AddError(separator, ErrorCode.ERR_UnexpectedAliasedName); separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } else if (this.CurrentToken.Kind == SyntaxKind.DotDotToken) { // Error recovery as in ParseQualifiedNameRight. If we have `X..Y` break that into `X.<missing-id>.Y` separator = this.EatToken(); explicitInterfaceName = RecoverFromDotDot(explicitInterfaceName, ref separator); } else { separator = this.EatToken(SyntaxKind.DotToken); } } _termState = saveTerm; } /// <summary> /// This is an adjusted version of <see cref="ParseMemberName"/>. /// When it returns true, it stops at operator keyword (<see cref="IsOperatorKeyword"/>). /// When it returns false, it does not advance in the token stream. /// </summary> private bool IsOperatorStart(out ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt, bool advanceParser = true) { explicitInterfaceOpt = null; if (IsOperatorKeyword()) { return true; } if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return false; } NameSyntax explicitInterfaceName = null; SyntaxToken separator = null; ResetPoint beforeIdentifierPoint = GetResetPoint(); try { while (true) { // now, scan past the next name. if it's followed by a dot then // it's part of the explicit name we're building up. Otherwise, // it should be an operator token var point = GetResetPoint(); bool isPartOfInterfaceName; try { if (IsOperatorKeyword()) { isPartOfInterfaceName = false; } else { ScanNamedTypePart(); // If we have part of the interface name, but no dot before the operator token, then // for the purpose of error recovery, treat this as an operator start with a // missing dot token. isPartOfInterfaceName = IsDotOrColonColonOrDotDot() || IsOperatorKeyword(); } } finally { this.Reset(ref point); this.Release(ref point); } if (!isPartOfInterfaceName) { // We're past any explicit interface portion if (separator != null && separator.Kind == SyntaxKind.ColonColonToken) { separator = this.AddError(separator, ErrorCode.ERR_AliasQualAsExpression); separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } break; } else { // If we saw a . or :: then we must have something explicit. AccumulateExplicitInterfaceName(ref explicitInterfaceName, ref separator); } } if (!IsOperatorKeyword() || explicitInterfaceName is null) { Reset(ref beforeIdentifierPoint); return false; } if (!advanceParser) { Reset(ref beforeIdentifierPoint); return true; } if (separator.Kind != SyntaxKind.DotToken) { separator = WithAdditionalDiagnostics(separator, GetExpectedTokenError(SyntaxKind.DotToken, separator.Kind, separator.GetLeadingTriviaWidth(), separator.Width)); separator = ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); } explicitInterfaceOpt = CheckFeatureAvailability(_syntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceName, separator), MessageID.IDS_FeatureStaticAbstractMembersInInterfaces); return true; } finally { Release(ref beforeIdentifierPoint); } } private NameSyntax ParseAliasQualifiedName(NameOptions allowedParts = NameOptions.None) { NameSyntax name = this.ParseSimpleName(allowedParts); if (this.CurrentToken.Kind == SyntaxKind.ColonColonToken) { var token = this.EatToken(); name = ParseQualifiedNameRight(allowedParts, name, token); } return name; } private NameSyntax ParseQualifiedName(NameOptions options = NameOptions.None) { NameSyntax name = this.ParseAliasQualifiedName(options); // Handle .. tokens for error recovery purposes. while (IsDotOrColonColonOrDotDot()) { if (this.PeekToken(1).Kind == SyntaxKind.ThisKeyword) { break; } var separator = this.EatToken(); name = ParseQualifiedNameRight(options, name, separator); } return name; } private bool IsDotOrColonColonOrDotDot() { return this.IsDotOrColonColon() || this.CurrentToken.Kind == SyntaxKind.DotDotToken; } private NameSyntax ParseQualifiedNameRight( NameOptions options, NameSyntax left, SyntaxToken separator) { Debug.Assert( separator.Kind == SyntaxKind.DotToken || separator.Kind == SyntaxKind.DotDotToken || separator.Kind == SyntaxKind.ColonColonToken); var right = this.ParseSimpleName(options); switch (separator.Kind) { case SyntaxKind.DotToken: return _syntaxFactory.QualifiedName(left, separator, right); case SyntaxKind.DotDotToken: // Error recovery. If we have `X..Y` break that into `X.<missing-id>.Y` return _syntaxFactory.QualifiedName(RecoverFromDotDot(left, ref separator), separator, right); case SyntaxKind.ColonColonToken: if (left.Kind != SyntaxKind.IdentifierName) { separator = this.AddError(separator, ErrorCode.ERR_UnexpectedAliasedName, separator.ToString()); } // If the left hand side is not an identifier name then the user has done // something like Goo.Bar::Blah. We've already made an error node for the // ::, so just pretend that they typed Goo.Bar.Blah and continue on. var identifierLeft = left as IdentifierNameSyntax; if (identifierLeft == null) { separator = this.ConvertToMissingWithTrailingTrivia(separator, SyntaxKind.DotToken); return _syntaxFactory.QualifiedName(left, separator, right); } else { if (identifierLeft.Identifier.ContextualKind == SyntaxKind.GlobalKeyword) { identifierLeft = _syntaxFactory.IdentifierName(ConvertToKeyword(identifierLeft.Identifier)); } identifierLeft = CheckFeatureAvailability(identifierLeft, MessageID.IDS_FeatureGlobalNamespace); // If the name on the right had errors or warnings then we need to preserve // them in the tree. return WithAdditionalDiagnostics(_syntaxFactory.AliasQualifiedName(identifierLeft, separator, right), left.GetDiagnostics()); } default: throw ExceptionUtilities.Unreachable; } } private NameSyntax RecoverFromDotDot(NameSyntax left, ref SyntaxToken separator) { Debug.Assert(separator.Kind == SyntaxKind.DotDotToken); var leftDot = SyntaxFactory.Token(separator.LeadingTrivia.Node, SyntaxKind.DotToken, null); var missingName = this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected); separator = SyntaxFactory.Token(null, SyntaxKind.DotToken, separator.TrailingTrivia.Node); return _syntaxFactory.QualifiedName(left, leftDot, missingName); } private SyntaxToken ConvertToMissingWithTrailingTrivia(SyntaxToken token, SyntaxKind expectedKind) { var newToken = SyntaxFactory.MissingToken(expectedKind); newToken = AddTrailingSkippedSyntax(newToken, token); return newToken; } private enum ScanTypeFlags { /// <summary> /// Definitely not a type name. /// </summary> NotType, /// <summary> /// Definitely a type name: either a predefined type (int, string, etc.) or an array /// type (ending with a [] brackets), or a pointer type (ending with *s), or a function /// pointer type (ending with > in valid cases, or a *, ), or calling convention /// identifier, in invalid cases). /// </summary> MustBeType, /// <summary> /// Might be a generic (qualified) type name or a method name. /// </summary> GenericTypeOrMethod, /// <summary> /// Might be a generic (qualified) type name or an expression or a method name. /// </summary> GenericTypeOrExpression, /// <summary> /// Might be a non-generic (qualified) type name or an expression. /// </summary> NonGenericTypeOrExpression, /// <summary> /// A type name with alias prefix (Alias::Name). Note that Alias::Name.X would not fall under this. This /// only is returned for exactly Alias::Name. /// </summary> AliasQualifiedName, /// <summary> /// Nullable type (ending with ?). /// </summary> NullableType, /// <summary> /// Might be a pointer type or a multiplication. /// </summary> PointerOrMultiplication, /// <summary> /// Might be a tuple type. /// </summary> TupleType, } private bool IsPossibleType() { var tk = this.CurrentToken.Kind; return IsPredefinedType(tk) || this.IsTrueIdentifier(); } private ScanTypeFlags ScanType(bool forPattern = false) { return ScanType(out _, forPattern); } private ScanTypeFlags ScanType(out SyntaxToken lastTokenOfType, bool forPattern = false) { return ScanType(forPattern ? ParseTypeMode.DefinitePattern : ParseTypeMode.Normal, out lastTokenOfType); } private void ScanNamedTypePart() { SyntaxToken lastTokenOfType; ScanNamedTypePart(out lastTokenOfType); } private ScanTypeFlags ScanNamedTypePart(out SyntaxToken lastTokenOfType) { if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken || !this.IsTrueIdentifier()) { lastTokenOfType = null; return ScanTypeFlags.NotType; } lastTokenOfType = this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.LessThanToken) { return this.ScanPossibleTypeArgumentList(ref lastTokenOfType, out _); } else { return ScanTypeFlags.NonGenericTypeOrExpression; } } private ScanTypeFlags ScanType(ParseTypeMode mode, out SyntaxToken lastTokenOfType) { Debug.Assert(mode != ParseTypeMode.NewExpression); ScanTypeFlags result; bool isFunctionPointer = false; if (this.CurrentToken.Kind == SyntaxKind.RefKeyword) { // in a ref local or ref return, we treat "ref" and "ref readonly" as part of the type this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword) { this.EatToken(); } } // Handle :: as well for error case of an alias used without a preceding identifier. if (this.CurrentToken.Kind is SyntaxKind.IdentifierToken or SyntaxKind.ColonColonToken) { bool isAlias; if (this.CurrentToken.Kind is SyntaxKind.ColonColonToken) { result = ScanTypeFlags.NonGenericTypeOrExpression; // Definitely seems like an alias if we're starting with a :: isAlias = true; // We set this to null to appease the flow checker. It will always be the case that this will be // set to an appropriate value inside the `for` loop below. We'll consume the :: there and then // call ScanNamedTypePart which will always set this to a valid value. lastTokenOfType = null; } else { Debug.Assert(this.CurrentToken.Kind is SyntaxKind.IdentifierToken); // We're an alias if we start with an: id:: isAlias = this.PeekToken(1).Kind == SyntaxKind.ColonColonToken; result = this.ScanNamedTypePart(out lastTokenOfType); if (result == ScanTypeFlags.NotType) { return ScanTypeFlags.NotType; } Debug.Assert(result is ScanTypeFlags.GenericTypeOrExpression or ScanTypeFlags.GenericTypeOrMethod or ScanTypeFlags.NonGenericTypeOrExpression); } // Scan a name for (bool firstLoop = true; IsDotOrColonColon(); firstLoop = false) { // If we consume any more dots or colons, don't consider us an alias anymore. For dots, we now have // x::y.z (which is now back to a normal expr/type, not an alias), and for colons that means we have // x::y::z or x.y::z both of which are effectively gibberish. if (!firstLoop) { isAlias = false; } this.EatToken(); result = this.ScanNamedTypePart(out lastTokenOfType); if (result == ScanTypeFlags.NotType) { return ScanTypeFlags.NotType; } Debug.Assert(result is ScanTypeFlags.GenericTypeOrExpression or ScanTypeFlags.GenericTypeOrMethod or ScanTypeFlags.NonGenericTypeOrExpression); } if (isAlias) { result = ScanTypeFlags.AliasQualifiedName; } } else if (IsPredefinedType(this.CurrentToken.Kind)) { // Simple type... lastTokenOfType = this.EatToken(); result = ScanTypeFlags.MustBeType; } else if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { lastTokenOfType = this.EatToken(); result = this.ScanTupleType(out lastTokenOfType); if (result == ScanTypeFlags.NotType || mode == ParseTypeMode.DefinitePattern && this.CurrentToken.Kind != SyntaxKind.OpenBracketToken) { // A tuple type can appear in a pattern only if it is the element type of an array type. return ScanTypeFlags.NotType; } } else if (IsFunctionPointerStart()) { isFunctionPointer = true; result = ScanFunctionPointerType(out lastTokenOfType); } else { // Can't be a type! lastTokenOfType = null; return ScanTypeFlags.NotType; } int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { switch (this.CurrentToken.Kind) { case SyntaxKind.QuestionToken when lastTokenOfType.Kind != SyntaxKind.QuestionToken && // don't allow `Type??` lastTokenOfType.Kind != SyntaxKind.AsteriskToken && // don't allow `Type*?` !isFunctionPointer: // don't allow `delegate*<...>?` lastTokenOfType = this.EatToken(); result = ScanTypeFlags.NullableType; break; case SyntaxKind.AsteriskToken when lastTokenOfType.Kind != SyntaxKind.CloseBracketToken: // don't allow `Type[]*` // Check for pointer type(s) switch (mode) { case ParseTypeMode.FirstElementOfPossibleTupleLiteral: case ParseTypeMode.AfterTupleComma: // We are parsing the type for a declaration expression in a tuple, which does // not permit pointer types except as an element type of an array type. // In that context a `*` is parsed as a multiplication. if (PointerTypeModsFollowedByRankAndDimensionSpecifier()) { goto default; } goto done; case ParseTypeMode.DefinitePattern: // pointer type syntax is not supported in patterns. goto done; default: lastTokenOfType = this.EatToken(); isFunctionPointer = false; if (result == ScanTypeFlags.GenericTypeOrExpression || result == ScanTypeFlags.NonGenericTypeOrExpression) { result = ScanTypeFlags.PointerOrMultiplication; } else if (result == ScanTypeFlags.GenericTypeOrMethod) { result = ScanTypeFlags.MustBeType; } break; } break; case SyntaxKind.OpenBracketToken: // Check for array types. this.EatToken(); while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { this.EatToken(); } if (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { lastTokenOfType = null; return ScanTypeFlags.NotType; } lastTokenOfType = this.EatToken(); isFunctionPointer = false; result = ScanTypeFlags.MustBeType; break; default: goto done; } } done: return result; } /// <summary> /// Returns TupleType when a possible tuple type is found. /// Note that this is not MustBeType, so that the caller can consider deconstruction syntaxes. /// The caller is expected to have consumed the opening paren. /// </summary> private ScanTypeFlags ScanTupleType(out SyntaxToken lastTokenOfType) { var tupleElementType = ScanType(out lastTokenOfType); if (tupleElementType != ScanTypeFlags.NotType) { if (IsTrueIdentifier()) { lastTokenOfType = this.EatToken(); } if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { do { lastTokenOfType = this.EatToken(); tupleElementType = ScanType(out lastTokenOfType); if (tupleElementType == ScanTypeFlags.NotType) { lastTokenOfType = this.EatToken(); return ScanTypeFlags.NotType; } if (IsTrueIdentifier()) { lastTokenOfType = this.EatToken(); } } while (this.CurrentToken.Kind == SyntaxKind.CommaToken); if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken) { lastTokenOfType = this.EatToken(); return ScanTypeFlags.TupleType; } } } // Can't be a type! lastTokenOfType = null; return ScanTypeFlags.NotType; } #nullable enable private ScanTypeFlags ScanFunctionPointerType(out SyntaxToken lastTokenOfType) { Debug.Assert(IsFunctionPointerStart()); _ = EatToken(SyntaxKind.DelegateKeyword); lastTokenOfType = EatToken(SyntaxKind.AsteriskToken); TerminatorState saveTerm; if (CurrentToken.Kind == SyntaxKind.IdentifierToken) { var peek1 = PeekToken(1); switch (CurrentToken) { case { ContextualKind: SyntaxKind.ManagedKeyword }: case { ContextualKind: SyntaxKind.UnmanagedKeyword }: case var _ when IsPossibleFunctionPointerParameterListStart(peek1): case var _ when peek1.Kind == SyntaxKind.OpenBracketToken: lastTokenOfType = EatToken(); break; default: // Whatever is next, it's probably not part of the type. We know that delegate* must be // a function pointer start, however, so say the asterisk is the last element and bail return ScanTypeFlags.MustBeType; } if (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { lastTokenOfType = EatToken(SyntaxKind.OpenBracketToken); saveTerm = _termState; _termState |= TerminatorState.IsEndOfFunctionPointerCallingConvention; try { while (true) { lastTokenOfType = TryEatToken(SyntaxKind.IdentifierToken) ?? lastTokenOfType; if (skipBadFunctionPointerTokens() == PostSkipAction.Abort) { break; } Debug.Assert(CurrentToken.Kind == SyntaxKind.CommaToken); lastTokenOfType = EatToken(); } lastTokenOfType = TryEatToken(SyntaxKind.CloseBracketToken) ?? lastTokenOfType; } finally { _termState = saveTerm; } } } if (!IsPossibleFunctionPointerParameterListStart(CurrentToken)) { // Even though this function pointer type is incomplete, we know that it // must be the start of a type, as there is no other possible interpretation // of delegate*. By always treating it as a type, we ensure that any disambiguation // done in later parsing treats this as a type, which will produce better // errors at later stages. return ScanTypeFlags.MustBeType; } var validStartingToken = EatToken().Kind == SyntaxKind.LessThanToken; saveTerm = _termState; _termState |= validStartingToken ? TerminatorState.IsEndOfFunctionPointerParameterList : TerminatorState.IsEndOfFunctionPointerParameterListErrored; var ignoredModifiers = _pool.Allocate<SyntaxToken>(); try { do { ParseParameterModifiers(ignoredModifiers, isFunctionPointerParameter: true); ignoredModifiers.Clear(); _ = ScanType(out _); if (skipBadFunctionPointerTokens() == PostSkipAction.Abort) { break; } _ = EatToken(SyntaxKind.CommaToken); } while (true); } finally { _termState = saveTerm; _pool.Free(ignoredModifiers); } if (!validStartingToken && CurrentToken.Kind == SyntaxKind.CloseParenToken) { lastTokenOfType = EatTokenAsKind(SyntaxKind.GreaterThanToken); } else { lastTokenOfType = EatToken(SyntaxKind.GreaterThanToken); } return ScanTypeFlags.MustBeType; PostSkipAction skipBadFunctionPointerTokens() { return SkipBadTokensWithExpectedKind(isNotExpectedFunction: p => p.CurrentToken.Kind != SyntaxKind.CommaToken, abortFunction: p => p.IsTerminator(), expected: SyntaxKind.CommaToken, trailingTrivia: out _); } } #nullable disable private static bool IsPredefinedType(SyntaxKind keyword) { return SyntaxFacts.IsPredefinedType(keyword); } public TypeSyntax ParseTypeName() { return ParseType(); } private TypeSyntax ParseTypeOrVoid() { if (this.CurrentToken.Kind == SyntaxKind.VoidKeyword && this.PeekToken(1).Kind != SyntaxKind.AsteriskToken) { // Must be 'void' type, so create such a type node and return it. return _syntaxFactory.PredefinedType(this.EatToken()); } return this.ParseType(); } private enum ParseTypeMode { Normal, Parameter, AfterIs, DefinitePattern, AfterOut, AfterRef, AfterTupleComma, AsExpression, NewExpression, FirstElementOfPossibleTupleLiteral, } private TypeSyntax ParseType(ParseTypeMode mode = ParseTypeMode.Normal) { if (this.CurrentToken.Kind == SyntaxKind.RefKeyword) { var refKeyword = this.EatToken(); refKeyword = this.CheckFeatureAvailability(refKeyword, MessageID.IDS_FeatureRefLocalsReturns); SyntaxToken readonlyKeyword = null; if (this.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword) { readonlyKeyword = this.EatToken(); readonlyKeyword = this.CheckFeatureAvailability(readonlyKeyword, MessageID.IDS_FeatureReadOnlyReferences); } var type = ParseTypeCore(ParseTypeMode.AfterRef); return _syntaxFactory.RefType(refKeyword, readonlyKeyword, type); } return ParseTypeCore(mode); } private TypeSyntax ParseTypeCore(ParseTypeMode mode) { NameOptions nameOptions; switch (mode) { case ParseTypeMode.AfterIs: nameOptions = NameOptions.InExpression | NameOptions.AfterIs | NameOptions.PossiblePattern; break; case ParseTypeMode.DefinitePattern: nameOptions = NameOptions.InExpression | NameOptions.DefinitePattern | NameOptions.PossiblePattern; break; case ParseTypeMode.AfterOut: nameOptions = NameOptions.InExpression | NameOptions.AfterOut; break; case ParseTypeMode.AfterTupleComma: nameOptions = NameOptions.InExpression | NameOptions.AfterTupleComma; break; case ParseTypeMode.FirstElementOfPossibleTupleLiteral: nameOptions = NameOptions.InExpression | NameOptions.FirstElementOfPossibleTupleLiteral; break; case ParseTypeMode.NewExpression: case ParseTypeMode.AsExpression: case ParseTypeMode.Normal: case ParseTypeMode.Parameter: case ParseTypeMode.AfterRef: nameOptions = NameOptions.None; break; default: throw ExceptionUtilities.UnexpectedValue(mode); } var type = this.ParseUnderlyingType(mode, options: nameOptions); Debug.Assert(type != null); int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { switch (this.CurrentToken.Kind) { case SyntaxKind.QuestionToken when canBeNullableType(): { var question = EatNullableQualifierIfApplicable(mode); if (question != null) { type = _syntaxFactory.NullableType(type, question); continue; } goto done; // token not consumed } bool canBeNullableType() { // These are the fast tests for (in)applicability. // More expensive tests are in `EatNullableQualifierIfApplicable` if (type.Kind == SyntaxKind.NullableType || type.Kind == SyntaxKind.PointerType || type.Kind == SyntaxKind.FunctionPointerType) return false; if (this.PeekToken(1).Kind == SyntaxKind.OpenBracketToken) return true; if (mode == ParseTypeMode.DefinitePattern) return true; // Permit nullable type parsing and report while binding for a better error message if (mode == ParseTypeMode.NewExpression && type.Kind == SyntaxKind.TupleType && this.PeekToken(1).Kind != SyntaxKind.OpenParenToken && this.PeekToken(1).Kind != SyntaxKind.OpenBraceToken) return false; // Permit `new (int, int)?(t)` (creation) and `new (int, int) ? x : y` (conditional) return true; } case SyntaxKind.AsteriskToken when type.Kind != SyntaxKind.ArrayType: switch (mode) { case ParseTypeMode.AfterIs: case ParseTypeMode.DefinitePattern: case ParseTypeMode.AfterTupleComma: case ParseTypeMode.FirstElementOfPossibleTupleLiteral: // these contexts do not permit a pointer type except as an element type of an array. if (PointerTypeModsFollowedByRankAndDimensionSpecifier()) { type = this.ParsePointerTypeMods(type); continue; } break; case ParseTypeMode.Normal: case ParseTypeMode.Parameter: case ParseTypeMode.AfterOut: case ParseTypeMode.AfterRef: case ParseTypeMode.AsExpression: case ParseTypeMode.NewExpression: type = this.ParsePointerTypeMods(type); continue; } goto done; // token not consumed case SyntaxKind.OpenBracketToken: // Now check for arrays. { var ranks = _pool.Allocate<ArrayRankSpecifierSyntax>(); try { while (this.CurrentToken.Kind == SyntaxKind.OpenBracketToken) { var rank = this.ParseArrayRankSpecifier(out _); ranks.Add(rank); } type = _syntaxFactory.ArrayType(type, ranks); } finally { _pool.Free(ranks); } continue; } default: goto done; // token not consumed } } done:; Debug.Assert(type != null); return type; } private SyntaxToken EatNullableQualifierIfApplicable(ParseTypeMode mode) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.QuestionToken); var resetPoint = this.GetResetPoint(); try { var questionToken = this.EatToken(); if (!canFollowNullableType()) { // Restore current token index this.Reset(ref resetPoint); return null; } return CheckFeatureAvailability(questionToken, MessageID.IDS_FeatureNullable); bool canFollowNullableType() { switch (mode) { case ParseTypeMode.AfterIs: case ParseTypeMode.DefinitePattern: case ParseTypeMode.AsExpression: // These contexts might be a type that is at the end of an expression. // In these contexts we only permit the nullable qualifier if it is followed // by a token that could not start an expression, because for backward // compatibility we want to consider a `?` token as part of the `?:` // operator if possible. return !CanStartExpression(); case ParseTypeMode.NewExpression: // A nullable qualifier is permitted as part of the type in a `new` expression. // e.g. `new int?()` is allowed. It creates a null value of type `Nullable<int>`. // Similarly `new int? {}` is allowed. return this.CurrentToken.Kind == SyntaxKind.OpenParenToken || // ctor parameters this.CurrentToken.Kind == SyntaxKind.OpenBracketToken || // array type this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; // object initializer default: return true; } } } finally { this.Release(ref resetPoint); } } private bool PointerTypeModsFollowedByRankAndDimensionSpecifier() { // Are pointer specifiers (if any) followed by an array specifier? for (int i = 0; ; i++) { switch (this.PeekToken(i).Kind) { case SyntaxKind.AsteriskToken: continue; case SyntaxKind.OpenBracketToken: return true; default: return false; } } } private ArrayRankSpecifierSyntax ParseArrayRankSpecifier(out bool sawNonOmittedSize) { sawNonOmittedSize = false; bool sawOmittedSize = false; var open = this.EatToken(SyntaxKind.OpenBracketToken); var list = _pool.AllocateSeparated<ExpressionSyntax>(); try { var omittedArraySizeExpressionInstance = _syntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition) && this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { // NOTE: trivia will be attached to comma, not omitted array size sawOmittedSize = true; list.Add(omittedArraySizeExpressionInstance); list.AddSeparator(this.EatToken()); } else if (this.IsPossibleExpression()) { var size = this.ParseExpressionCore(); sawNonOmittedSize = true; list.Add(size); if (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); } } else if (this.SkipBadArrayRankSpecifierTokens(ref open, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } // Don't end on a comma. // If the omitted size would be the only element, then skip it unless sizes were expected. if (((list.Count & 1) == 0)) { sawOmittedSize = true; list.Add(omittedArraySizeExpressionInstance); } // Never mix omitted and non-omitted array sizes. If there were non-omitted array sizes, // then convert all of the omitted array sizes to missing identifiers. if (sawOmittedSize && sawNonOmittedSize) { for (int i = 0; i < list.Count; i++) { if (list[i].RawKind == (int)SyntaxKind.OmittedArraySizeExpression) { int width = list[i].Width; int offset = list[i].GetLeadingTriviaWidth(); list[i] = this.AddError(this.CreateMissingIdentifierName(), offset, width, ErrorCode.ERR_ValueExpected); } } } // Eat the close brace and we're done. var close = this.EatToken(SyntaxKind.CloseBracketToken); return _syntaxFactory.ArrayRankSpecifier(open, list, close); } finally { _pool.Free(list); } } private TupleTypeSyntax ParseTupleType() { var open = this.EatToken(SyntaxKind.OpenParenToken); var list = _pool.AllocateSeparated<TupleElementSyntax>(); try { if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { var element = ParseTupleElement(); list.Add(element); while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { var comma = this.EatToken(SyntaxKind.CommaToken); list.AddSeparator(comma); element = ParseTupleElement(); list.Add(element); } } if (list.Count < 2) { if (list.Count < 1) { list.Add(_syntaxFactory.TupleElement(this.CreateMissingIdentifierName(), identifier: null)); } list.AddSeparator(SyntaxFactory.MissingToken(SyntaxKind.CommaToken)); var missing = this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_TupleTooFewElements); list.Add(_syntaxFactory.TupleElement(missing, identifier: null)); } var close = this.EatToken(SyntaxKind.CloseParenToken); var result = _syntaxFactory.TupleType(open, list, close); result = CheckFeatureAvailability(result, MessageID.IDS_FeatureTuples); return result; } finally { _pool.Free(list); } } private TupleElementSyntax ParseTupleElement() { var type = ParseType(); SyntaxToken name = null; if (IsTrueIdentifier()) { name = this.ParseIdentifierToken(); } return _syntaxFactory.TupleElement(type, name); } private PostSkipAction SkipBadArrayRankSpecifierTokens(ref SyntaxToken openBracket, SeparatedSyntaxListBuilder<ExpressionSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openBracket, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), p => p.CurrentToken.Kind == SyntaxKind.CloseBracketToken || p.IsTerminator(), expected); } private TypeSyntax ParseUnderlyingType(ParseTypeMode mode, NameOptions options = NameOptions.None) { if (IsPredefinedType(this.CurrentToken.Kind)) { // This is a predefined type var token = this.EatToken(); if (token.Kind == SyntaxKind.VoidKeyword && this.CurrentToken.Kind != SyntaxKind.AsteriskToken) { token = this.AddError(token, mode == ParseTypeMode.Parameter ? ErrorCode.ERR_NoVoidParameter : ErrorCode.ERR_NoVoidHere); } return _syntaxFactory.PredefinedType(token); } // The :: case is for error recovery. if (IsTrueIdentifier() || this.CurrentToken.Kind == SyntaxKind.ColonColonToken) { return this.ParseQualifiedName(options); } if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { return this.ParseTupleType(); } else if (IsFunctionPointerStart()) { return ParseFunctionPointerTypeSyntax(); } return this.AddError( this.CreateMissingIdentifierName(), mode == ParseTypeMode.NewExpression ? ErrorCode.ERR_BadNewExpr : ErrorCode.ERR_TypeExpected); } #nullable enable private FunctionPointerTypeSyntax ParseFunctionPointerTypeSyntax() { Debug.Assert(IsFunctionPointerStart()); var @delegate = EatToken(SyntaxKind.DelegateKeyword); var asterisk = EatToken(SyntaxKind.AsteriskToken); FunctionPointerCallingConventionSyntax? callingConvention = parseCallingConvention(); if (!IsPossibleFunctionPointerParameterListStart(CurrentToken)) { var lessThanTokenError = WithAdditionalDiagnostics(SyntaxFactory.MissingToken(SyntaxKind.LessThanToken), GetExpectedTokenError(SyntaxKind.LessThanToken, SyntaxKind.None)); var missingTypes = _pool.AllocateSeparated<FunctionPointerParameterSyntax>(); var missingTypeName = CreateMissingIdentifierName(); var missingType = SyntaxFactory.FunctionPointerParameter(attributeLists: default, modifiers: default, missingTypeName); missingTypes.Add(missingType); // Handle the simple case of delegate*>. We don't try to deal with any variation of delegate*invalid>, as // we don't know for sure that the expression isn't a relational with something else. var greaterThanTokenError = TryEatToken(SyntaxKind.GreaterThanToken) ?? SyntaxFactory.MissingToken(SyntaxKind.GreaterThanToken); var paramList = SyntaxFactory.FunctionPointerParameterList(lessThanTokenError, missingTypes, greaterThanTokenError); var funcPtr = SyntaxFactory.FunctionPointerType(@delegate, asterisk, callingConvention, paramList); _pool.Free(missingTypes); return funcPtr; } var lessThanToken = EatTokenAsKind(SyntaxKind.LessThanToken); var saveTerm = _termState; _termState |= (lessThanToken.IsMissing ? TerminatorState.IsEndOfFunctionPointerParameterListErrored : TerminatorState.IsEndOfFunctionPointerParameterList); var types = _pool.AllocateSeparated<FunctionPointerParameterSyntax>(); try { while (true) { var modifiers = _pool.Allocate<SyntaxToken>(); try { ParseParameterModifiers(modifiers, isFunctionPointerParameter: true); var parameterType = ParseTypeOrVoid(); types.Add(SyntaxFactory.FunctionPointerParameter(attributeLists: default, modifiers, parameterType)); if (skipBadFunctionPointerTokens(types) == PostSkipAction.Abort) { break; } Debug.Assert(CurrentToken.Kind == SyntaxKind.CommaToken); types.AddSeparator(EatToken(SyntaxKind.CommaToken)); } finally { _pool.Free(modifiers); } } SyntaxToken greaterThanToken; if (lessThanToken.IsMissing && CurrentToken.Kind == SyntaxKind.CloseParenToken) { greaterThanToken = EatTokenAsKind(SyntaxKind.GreaterThanToken); } else { greaterThanToken = EatToken(SyntaxKind.GreaterThanToken); } var funcPointer = SyntaxFactory.FunctionPointerType(@delegate, asterisk, callingConvention, SyntaxFactory.FunctionPointerParameterList(lessThanToken, types, greaterThanToken)); funcPointer = CheckFeatureAvailability(funcPointer, MessageID.IDS_FeatureFunctionPointers); return funcPointer; } finally { _termState = saveTerm; _pool.Free(types); } PostSkipAction skipBadFunctionPointerTokens<T>(SeparatedSyntaxListBuilder<T> list) where T : CSharpSyntaxNode { CSharpSyntaxNode? tmp = null; Debug.Assert(list.Count > 0); return SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, isNotExpectedFunction: p => p.CurrentToken.Kind != SyntaxKind.CommaToken, abortFunction: p => p.IsTerminator(), expected: SyntaxKind.CommaToken); } FunctionPointerCallingConventionSyntax? parseCallingConvention() { if (CurrentToken.Kind == SyntaxKind.IdentifierToken) { SyntaxToken managedSpecifier; SyntaxToken peek1 = PeekToken(1); switch (CurrentToken) { case { ContextualKind: SyntaxKind.ManagedKeyword }: case { ContextualKind: SyntaxKind.UnmanagedKeyword }: managedSpecifier = EatContextualToken(CurrentToken.ContextualKind); break; case var _ when IsPossibleFunctionPointerParameterListStart(peek1): // If there's a possible parameter list next, treat this as a bad identifier that should have been managed or unmanaged managedSpecifier = EatTokenAsKind(SyntaxKind.ManagedKeyword); break; case var _ when peek1.Kind == SyntaxKind.OpenBracketToken: // If there's an open brace next, treat this as a bad identifier that should have been unmanaged managedSpecifier = EatTokenAsKind(SyntaxKind.UnmanagedKeyword); break; default: // Whatever is next, it's probably not a calling convention or a function pointer type. // Bail out return null; } FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventions = null; if (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { var openBracket = EatToken(SyntaxKind.OpenBracketToken); var callingConventionModifiers = _pool.AllocateSeparated<FunctionPointerUnmanagedCallingConventionSyntax>(); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFunctionPointerCallingConvention; try { while (true) { callingConventionModifiers.Add(SyntaxFactory.FunctionPointerUnmanagedCallingConvention(EatToken(SyntaxKind.IdentifierToken))); if (skipBadFunctionPointerTokens(callingConventionModifiers) == PostSkipAction.Abort) { break; } Debug.Assert(CurrentToken.Kind == SyntaxKind.CommaToken); callingConventionModifiers.AddSeparator(EatToken(SyntaxKind.CommaToken)); } var closeBracket = EatToken(SyntaxKind.CloseBracketToken); unmanagedCallingConventions = SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(openBracket, callingConventionModifiers, closeBracket); } finally { _termState = saveTerm; _pool.Free(callingConventionModifiers); } } if (managedSpecifier.Kind == SyntaxKind.ManagedKeyword && unmanagedCallingConventions != null) { // 'managed' calling convention cannot be combined with unmanaged calling convention specifiers. unmanagedCallingConventions = AddError(unmanagedCallingConventions, ErrorCode.ERR_CannotSpecifyManagedWithUnmanagedSpecifiers); } return SyntaxFactory.FunctionPointerCallingConvention(managedSpecifier, unmanagedCallingConventions); } return null; } } private bool IsFunctionPointerStart() => CurrentToken.Kind == SyntaxKind.DelegateKeyword && PeekToken(1).Kind == SyntaxKind.AsteriskToken; private static bool IsPossibleFunctionPointerParameterListStart(SyntaxToken token) // We consider both ( and < to be possible starts, in order to make error recovery more graceful // in the scenario where a user accidentally surrounds their function pointer type list with parens. => token.Kind == SyntaxKind.LessThanToken || token.Kind == SyntaxKind.OpenParenToken; #nullable disable private TypeSyntax ParsePointerTypeMods(TypeSyntax type) { // Check for pointer types while (this.CurrentToken.Kind == SyntaxKind.AsteriskToken) { type = _syntaxFactory.PointerType(type, this.EatToken()); } return type; } public StatementSyntax ParseStatement() { return ParseWithStackGuard( () => ParsePossiblyAttributedStatement() ?? ParseExpressionStatement(attributes: default), () => SyntaxFactory.EmptyStatement(attributeLists: default, SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken))); } private StatementSyntax ParsePossiblyAttributedStatement() => ParseStatementCore(ParseAttributeDeclarations(), isGlobal: false); /// <param name="isGlobal">If we're being called while parsing a C# top-level statements (Script or Simple Program). /// At the top level in Script, we allow most statements *except* for local-decls/local-funcs. /// Those will instead be parsed out as script-fields/methods.</param> private StatementSyntax ParseStatementCore(SyntaxList<AttributeListSyntax> attributes, bool isGlobal) { if (canReuseStatement(attributes, isGlobal)) { return (StatementSyntax)this.EatNode(); } ResetPoint resetPointBeforeStatement = this.GetResetPoint(); try { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); StatementSyntax result; // Main switch to handle processing almost any statement. switch (this.CurrentToken.Kind) { case SyntaxKind.FixedKeyword: return this.ParseFixedStatement(attributes); case SyntaxKind.BreakKeyword: return this.ParseBreakStatement(attributes); case SyntaxKind.ContinueKeyword: return this.ParseContinueStatement(attributes); case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: return this.ParseTryStatement(attributes); case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: return this.ParseCheckedStatement(attributes); case SyntaxKind.DoKeyword: return this.ParseDoStatement(attributes); case SyntaxKind.ForKeyword: return this.ParseForOrForEachStatement(attributes); case SyntaxKind.ForEachKeyword: return this.ParseForEachStatement(attributes, awaitTokenOpt: null); case SyntaxKind.GotoKeyword: return this.ParseGotoStatement(attributes); case SyntaxKind.IfKeyword: return this.ParseIfStatement(attributes); case SyntaxKind.ElseKeyword: // Including 'else' keyword to handle 'else without if' error cases return this.ParseMisplacedElse(attributes); case SyntaxKind.LockKeyword: return this.ParseLockStatement(attributes); case SyntaxKind.ReturnKeyword: return this.ParseReturnStatement(attributes); case SyntaxKind.SwitchKeyword: return this.ParseSwitchStatement(attributes); case SyntaxKind.ThrowKeyword: return this.ParseThrowStatement(attributes); case SyntaxKind.UnsafeKeyword: result = TryParseStatementStartingWithUnsafe(attributes); if (result != null) return result; break; case SyntaxKind.UsingKeyword: return ParseStatementStartingWithUsing(attributes); case SyntaxKind.WhileKeyword: return this.ParseWhileStatement(attributes); case SyntaxKind.OpenBraceToken: return this.ParseBlock(attributes); case SyntaxKind.SemicolonToken: return _syntaxFactory.EmptyStatement(attributes, this.EatToken()); case SyntaxKind.IdentifierToken: result = TryParseStatementStartingWithIdentifier(attributes, isGlobal); if (result != null) return result; break; } return ParseStatementCoreRest(attributes, isGlobal, ref resetPointBeforeStatement); } finally { _recursionDepth--; this.Release(ref resetPointBeforeStatement); } bool canReuseStatement(SyntaxList<AttributeListSyntax> attributes, bool isGlobal) { return this.IsIncrementalAndFactoryContextMatches && this.CurrentNode is Syntax.StatementSyntax && !isGlobal && // Top-level statements are reused by ParseMemberDeclarationOrStatementCore when possible. attributes.Count == 0; } } private StatementSyntax ParseStatementCoreRest(SyntaxList<AttributeListSyntax> attributes, bool isGlobal, ref ResetPoint resetPointBeforeStatement) { isGlobal = isGlobal && IsScript; if (!this.IsPossibleLocalDeclarationStatement(isGlobal)) { return this.ParseExpressionStatement(attributes); } if (isGlobal) { // if we're at the global script level, then we don't support local-decls or // local-funcs. The caller instead will look for those and parse them as // fields/methods in the global script scope. return null; } bool beginsWithAwait = this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword; var result = ParseLocalDeclarationStatement(attributes); // didn't get any sort of statement. This was something else entirely // (like just a `}`). No need to retry anything here. Just reset back // to where we started from and bail entirely from parsing a statement. if (result == null) { this.Reset(ref resetPointBeforeStatement); return null; } if (result.ContainsDiagnostics && beginsWithAwait && !IsInAsync) { // Local decl had issues. We were also starting with 'await' in a non-async // context. Retry parsing this as if we were in an 'async' context as it's much // more likely that this was a misplace await-expr' than a local decl. // // The user will still get a later binding error about an await-expr in a non-async // context. this.Reset(ref resetPointBeforeStatement); IsInAsync = true; result = ParseExpressionStatement(attributes); IsInAsync = false; } // Didn't want to retry as an `await expr`. Just return what we actually // produced. return result; } private StatementSyntax TryParseStatementStartingWithIdentifier(SyntaxList<AttributeListSyntax> attributes, bool isGlobal) { if (this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword && this.PeekToken(1).Kind == SyntaxKind.ForEachKeyword) { return this.ParseForEachStatement(attributes, ParseAwaitKeyword(MessageID.IDS_FeatureAsyncStreams)); } else if (IsPossibleAwaitUsing()) { if (PeekToken(2).Kind == SyntaxKind.OpenParenToken) { // `await using Type ...` is handled below in ParseLocalDeclarationStatement return this.ParseUsingStatement(attributes, ParseAwaitKeyword(MessageID.IDS_FeatureAsyncUsing)); } } else if (this.IsPossibleLabeledStatement()) { return this.ParseLabeledStatement(attributes); } else if (this.IsPossibleYieldStatement()) { return this.ParseYieldStatement(attributes); } else if (this.IsPossibleAwaitExpressionStatement()) { return this.ParseExpressionStatement(attributes); } else if (this.IsQueryExpression(mayBeVariableDeclaration: true, mayBeMemberDeclaration: isGlobal && IsScript)) { return this.ParseExpressionStatement(attributes, this.ParseQueryExpression(0)); } return null; } private StatementSyntax ParseStatementStartingWithUsing(SyntaxList<AttributeListSyntax> attributes) => PeekToken(1).Kind == SyntaxKind.OpenParenToken ? ParseUsingStatement(attributes) : ParseLocalDeclarationStatement(attributes); // Checking for brace to disambiguate between unsafe statement and unsafe local function private StatementSyntax TryParseStatementStartingWithUnsafe(SyntaxList<AttributeListSyntax> attributes) => IsPossibleUnsafeStatement() ? ParseUnsafeStatement(attributes) : null; private SyntaxToken ParseAwaitKeyword(MessageID feature) { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword); SyntaxToken awaitToken = this.EatContextualToken(SyntaxKind.AwaitKeyword); return feature != MessageID.None ? CheckFeatureAvailability(awaitToken, feature) : awaitToken; } private bool IsPossibleAwaitUsing() => CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword && PeekToken(1).Kind == SyntaxKind.UsingKeyword; private bool IsPossibleLabeledStatement() { return this.PeekToken(1).Kind == SyntaxKind.ColonToken && this.IsTrueIdentifier(); } private bool IsPossibleUnsafeStatement() { return this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken; } private bool IsPossibleYieldStatement() { return this.CurrentToken.ContextualKind == SyntaxKind.YieldKeyword && (this.PeekToken(1).Kind == SyntaxKind.ReturnKeyword || this.PeekToken(1).Kind == SyntaxKind.BreakKeyword); } private bool IsPossibleLocalDeclarationStatement(bool isGlobalScriptLevel) { // This method decides whether to parse a statement as a // declaration or as an expression statement. In the old // compiler it would simply call IsLocalDeclaration. var tk = this.CurrentToken.Kind; if (tk == SyntaxKind.RefKeyword || IsDeclarationModifier(tk) || // treat `static int x = 2;` as a local variable declaration (SyntaxFacts.IsPredefinedType(tk) && this.PeekToken(1).Kind != SyntaxKind.DotToken && // e.g. `int.Parse()` is an expression this.PeekToken(1).Kind != SyntaxKind.OpenParenToken)) // e.g. `int (x, y)` is an error decl expression { return true; } // note: `using (` and `await using (` are already handled in ParseStatementCore. if (tk == SyntaxKind.UsingKeyword) { Debug.Assert(PeekToken(1).Kind != SyntaxKind.OpenParenToken); return true; } if (IsPossibleAwaitUsing()) { Debug.Assert(PeekToken(2).Kind != SyntaxKind.OpenParenToken); return true; } tk = this.CurrentToken.ContextualKind; var isPossibleAttributeOrModifier = (IsAdditionalLocalFunctionModifier(tk) || tk == SyntaxKind.OpenBracketToken) && (tk != SyntaxKind.AsyncKeyword || ShouldAsyncBeTreatedAsModifier(parsingStatementNotDeclaration: true)); if (isPossibleAttributeOrModifier) { return true; } return IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(isGlobalScriptLevel); } private bool IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(bool isGlobalScriptLevel) { bool? typedIdentifier = IsPossibleTypedIdentifierStart(this.CurrentToken, this.PeekToken(1), allowThisKeyword: false); if (typedIdentifier != null) { return typedIdentifier.Value; } // It's common to have code like the following: // // Task. // await Task.Delay() // // In this case we don't want to parse this as a local declaration like: // // Task.await Task // // This does not represent user intent, and it causes all sorts of problems to higher // layers. This is because both the parse tree is strange, and the symbol tables have // entries that throw things off (like a bogus 'Task' local). // // Note that we explicitly do this check when we see that the code spreads over multiple // lines. We don't want this if the user has actually written "X.Y z" var tk = this.CurrentToken.ContextualKind; if (tk == SyntaxKind.IdentifierToken) { var token1 = PeekToken(1); if (token1.Kind == SyntaxKind.DotToken && token1.TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia)) { if (PeekToken(2).Kind == SyntaxKind.IdentifierToken && PeekToken(3).Kind == SyntaxKind.IdentifierToken) { // We have something like: // // X. // Y z // // This is only a local declaration if we have: // // X.Y z; // X.Y z = ... // X.Y z, ... // X.Y z( ... (local function) // X.Y z<W... (local function) // var token4Kind = PeekToken(4).Kind; if (token4Kind != SyntaxKind.SemicolonToken && token4Kind != SyntaxKind.EqualsToken && token4Kind != SyntaxKind.CommaToken && token4Kind != SyntaxKind.OpenParenToken && token4Kind != SyntaxKind.LessThanToken) { return false; } } } } var resetPoint = this.GetResetPoint(); try { ScanTypeFlags st = this.ScanType(); // We could always return true for st == AliasQualName in addition to MustBeType on the first line, however, we want it to return false in the case where // CurrentToken.Kind != SyntaxKind.Identifier so that error cases, like: A::N(), are not parsed as variable declarations and instead are parsed as A.N() where we can give // a better error message saying "did you meant to use a '.'?" if (st == ScanTypeFlags.MustBeType && this.CurrentToken.Kind != SyntaxKind.DotToken && this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { return true; } if (st == ScanTypeFlags.NotType || this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return false; } // T? and T* might start an expression, we need to parse further to disambiguate: if (isGlobalScriptLevel) { if (st == ScanTypeFlags.PointerOrMultiplication) { return false; } else if (st == ScanTypeFlags.NullableType) { return IsPossibleDeclarationStatementFollowingNullableType(); } } return true; } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } private bool IsPossibleTopLevelUsingLocalDeclarationStatement() { if (this.CurrentToken.Kind != SyntaxKind.UsingKeyword) { return false; } var tk = PeekToken(1).Kind; if (tk == SyntaxKind.RefKeyword) { return true; } if (IsDeclarationModifier(tk)) // treat `const int x = 2;` as a local variable declaration { if (tk != SyntaxKind.StaticKeyword) // For `static` we still need to make sure we have a typed identifier after it, because `using static type;` is a valid using directive. { return true; } } else if (SyntaxFacts.IsPredefinedType(tk)) { return true; } var resetPoint = this.GetResetPoint(); try { // Skip 'using' keyword EatToken(); if (tk == SyntaxKind.StaticKeyword) { // Skip 'static' keyword EatToken(); } return IsPossibleFirstTypedIdentifierInLocaDeclarationStatement(isGlobalScriptLevel: false); } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } // Looks ahead for a declaration of a field, property or method declaration following a nullable type T?. private bool IsPossibleDeclarationStatementFollowingNullableType() { if (IsFieldDeclaration(isEvent: false)) { return IsPossibleFieldDeclarationFollowingNullableType(); } ExplicitInterfaceSpecifierSyntax explicitInterfaceOpt; SyntaxToken identifierOrThisOpt; TypeParameterListSyntax typeParameterListOpt; this.ParseMemberName(out explicitInterfaceOpt, out identifierOrThisOpt, out typeParameterListOpt, isEvent: false); if (explicitInterfaceOpt == null && identifierOrThisOpt == null && typeParameterListOpt == null) { return false; } // looks like a property: if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { return true; } // don't accept indexers: if (identifierOrThisOpt.Kind == SyntaxKind.ThisKeyword) { return false; } return IsPossibleMethodDeclarationFollowingNullableType(); } // At least one variable declaration terminated by a semicolon or a comma. // idf; // idf, // idf = <expr>; // idf = <expr>, private bool IsPossibleFieldDeclarationFollowingNullableType() { if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { return false; } this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.EqualsToken) { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFieldDeclaration; this.EatToken(); this.ParseVariableInitializer(); _termState = saveTerm; } return this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken; } private bool IsPossibleMethodDeclarationFollowingNullableType() { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfMethodSignature; var paramList = this.ParseParenthesizedParameterList(); _termState = saveTerm; var separatedParameters = paramList.Parameters.GetWithSeparators(); // parsed full signature: if (!paramList.CloseParenToken.IsMissing) { // (...) { // (...) where if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { return true; } // disambiguates conditional expressions // (...) : if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { return false; } } // no parameters, just an open paren followed by a token that doesn't belong to a parameter definition: if (separatedParameters.Count == 0) { return false; } var parameter = (ParameterSyntax)separatedParameters[0]; // has an attribute: // ([Attr] if (parameter.AttributeLists.Count > 0) { return true; } // has params modifier: // (params for (int i = 0; i < parameter.Modifiers.Count; i++) { if (parameter.Modifiers[i].Kind == SyntaxKind.ParamsKeyword) { return true; } } if (parameter.Type == null) { // has arglist: // (__arglist if (parameter.Identifier.Kind == SyntaxKind.ArgListKeyword) { return true; } } else if (parameter.Type.Kind == SyntaxKind.NullableType) { // nullable type with modifiers // (ref T? // (out T? if (parameter.Modifiers.Count > 0) { return true; } // nullable type, identifier, and separator or closing parent // (T ? idf, // (T ? idf) if (!parameter.Identifier.IsMissing && (separatedParameters.Count >= 2 && !separatedParameters[1].IsMissing || separatedParameters.Count == 1 && !paramList.CloseParenToken.IsMissing)) { return true; } } else if (parameter.Type.Kind == SyntaxKind.IdentifierName && ((IdentifierNameSyntax)parameter.Type).Identifier.ContextualKind == SyntaxKind.FromKeyword) { // assume that "from" is meant to be a query start ("from" bound to a type is rare): // (from return false; } else { // has a name and a non-nullable type: // (T idf // (ref T idf // (out T idf if (!parameter.Identifier.IsMissing) { return true; } } return false; } private bool IsPossibleNewExpression() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NewKeyword); // skip new SyntaxToken nextToken = PeekToken(1); // new { } // new [ ] switch (nextToken.Kind) { case SyntaxKind.OpenBraceToken: case SyntaxKind.OpenBracketToken: return true; } // // Declaration with new modifier vs. new expression // Parse it as an expression if the type is not followed by an identifier or this keyword. // // Member declarations: // new T Idf ... // new T this ... // new partial Idf ("partial" as a type name) // new partial this ("partial" as a type name) // new partial T Idf // new partial T this // new <modifier> // new <class|interface|struct|enum> // new partial <class|interface|struct|enum> // // New expressions: // new T [] // new T { } // new <non-type> // if (SyntaxFacts.GetBaseTypeDeclarationKind(nextToken.Kind) != SyntaxKind.None) { return false; } DeclarationModifiers modifier = GetModifier(nextToken); if (modifier == DeclarationModifiers.Partial) { if (SyntaxFacts.IsPredefinedType(PeekToken(2).Kind)) { return false; } // class, struct, enum, interface keywords, but also other modifiers that are not allowed after // partial keyword but start class declaration, so we can assume the user just swapped them. if (IsPossibleStartOfTypeDeclaration(PeekToken(2).Kind)) { return false; } } else if (modifier != DeclarationModifiers.None) { return false; } bool? typedIdentifier = IsPossibleTypedIdentifierStart(nextToken, PeekToken(2), allowThisKeyword: true); if (typedIdentifier != null) { // new Idf Idf // new Idf . // new partial T // new partial . return !typedIdentifier.Value; } var resetPoint = this.GetResetPoint(); try { // skips new keyword EatToken(); ScanTypeFlags st = this.ScanType(); return !IsPossibleMemberName() || st == ScanTypeFlags.NotType; } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } /// <returns> /// true if the current token can be the first token of a typed identifier (a type name followed by an identifier), /// false if it definitely can't be, /// null if we need to scan further to find out. /// </returns> private bool? IsPossibleTypedIdentifierStart(SyntaxToken current, SyntaxToken next, bool allowThisKeyword) { if (IsTrueIdentifier(current)) { switch (next.Kind) { // tokens that can be in type names... case SyntaxKind.DotToken: case SyntaxKind.AsteriskToken: case SyntaxKind.QuestionToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.LessThanToken: case SyntaxKind.ColonColonToken: return null; case SyntaxKind.OpenParenToken: if (current.IsIdentifierVar()) { // potentially either a tuple type in a local declaration (true), or // a tuple lvalue in a deconstruction assignment (false). return null; } else { return false; } case SyntaxKind.IdentifierToken: return IsTrueIdentifier(next); case SyntaxKind.ThisKeyword: return allowThisKeyword; default: return false; } } return null; } private BlockSyntax ParsePossiblyAttributedBlock() => ParseBlock(this.ParseAttributeDeclarations()); /// <summary> /// Used to parse the block-body for a method or accessor. For blocks that appear *inside* /// method bodies, call <see cref="ParseBlock"/>. /// </summary> /// <param name="isAccessorBody">If is true, then we produce a special diagnostic if the /// open brace is missing.</param> private BlockSyntax ParseMethodOrAccessorBodyBlock(SyntaxList<AttributeListSyntax> attributes, bool isAccessorBody) { // Check again for incremental re-use. This way if a method signature is edited we can // still quickly re-sync on the body. if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.Block && attributes.Count == 0) return (BlockSyntax)this.EatNode(); // There's a special error code for a missing token after an accessor keyword CSharpSyntaxNode openBrace = isAccessorBody && this.CurrentToken.Kind != SyntaxKind.OpenBraceToken ? this.AddError( SyntaxFactory.MissingToken(SyntaxKind.OpenBraceToken), IsFeatureEnabled(MessageID.IDS_FeatureExpressionBodiedAccessor) ? ErrorCode.ERR_SemiOrLBraceOrArrowExpected : ErrorCode.ERR_SemiOrLBraceExpected) : this.EatToken(SyntaxKind.OpenBraceToken); var statements = _pool.Allocate<StatementSyntax>(); this.ParseStatements(ref openBrace, statements, stopOnSwitchSections: false); var block = _syntaxFactory.Block( attributes, (SyntaxToken)openBrace, // Force creation a many-children list, even if only 1, 2, or 3 elements in the statement list. IsLargeEnoughNonEmptyStatementList(statements) ? new SyntaxList<StatementSyntax>(SyntaxList.List(((SyntaxListBuilder)statements).ToArray())) : statements, this.EatToken(SyntaxKind.CloseBraceToken)); _pool.Free(statements); return block; } /// <summary> /// Used to parse normal blocks that appear inside method bodies. For the top level block /// of a method/accessor use <see cref="ParseMethodOrAccessorBodyBlock"/>. /// </summary> private BlockSyntax ParseBlock(SyntaxList<AttributeListSyntax> attributes) { // Check again for incremental re-use, since ParseBlock is called from a bunch of places // other than ParseStatementCore() if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.Block) return (BlockSyntax)this.EatNode(); CSharpSyntaxNode openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var statements = _pool.Allocate<StatementSyntax>(); this.ParseStatements(ref openBrace, statements, stopOnSwitchSections: false); var block = _syntaxFactory.Block( attributes, (SyntaxToken)openBrace, statements, this.EatToken(SyntaxKind.CloseBraceToken)); _pool.Free(statements); return block; } // Is this statement list non-empty, and large enough to make using weak children beneficial? private static bool IsLargeEnoughNonEmptyStatementList(SyntaxListBuilder<StatementSyntax> statements) { if (statements.Count == 0) { return false; } else if (statements.Count == 1) { // If we have a single statement, it might be small, like "return null", or large, // like a loop or if or switch with many statements inside. Use the width as a proxy for // how big it is. If it's small, its better to forgo a many children list anyway, since the // weak reference would consume as much memory as is saved. return statements[0].Width > 60; } else { // For 2 or more statements, go ahead and create a many-children lists. return true; } } private void ParseStatements(ref CSharpSyntaxNode previousNode, SyntaxListBuilder<StatementSyntax> statements, bool stopOnSwitchSections) { var saveTerm = _termState; _termState |= TerminatorState.IsPossibleStatementStartOrStop; // partial statements can abort if a new statement starts if (stopOnSwitchSections) { _termState |= TerminatorState.IsSwitchSectionStart; } int lastTokenPosition = -1; while (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken && this.CurrentToken.Kind != SyntaxKind.EndOfFileToken && !(stopOnSwitchSections && this.IsPossibleSwitchSection()) && IsMakingProgress(ref lastTokenPosition)) { if (this.IsPossibleStatement(acceptAccessibilityMods: true)) { var statement = this.ParsePossiblyAttributedStatement(); if (statement != null) { statements.Add(statement); continue; } } GreenNode trailingTrivia; var action = this.SkipBadStatementListTokens(statements, SyntaxKind.CloseBraceToken, out trailingTrivia); if (trailingTrivia != null) { previousNode = AddTrailingSkippedSyntax(previousNode, trailingTrivia); } if (action == PostSkipAction.Abort) { break; } } _termState = saveTerm; } private bool IsPossibleStatementStartOrStop() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.IsPossibleStatement(acceptAccessibilityMods: true); } private PostSkipAction SkipBadStatementListTokens(SyntaxListBuilder<StatementSyntax> statements, SyntaxKind expected, out GreenNode trailingTrivia) { return this.SkipBadListTokensWithExpectedKindHelper( statements, // We know we have a bad statement, so it can't be a local // function, meaning we shouldn't consider accessibility // modifiers to be the start of a statement p => !p.IsPossibleStatement(acceptAccessibilityMods: false), p => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken || p.IsTerminator(), expected, out trailingTrivia ); } private bool IsPossibleStatement(bool acceptAccessibilityMods) { var tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.FixedKeyword: case SyntaxKind.BreakKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.LockKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.ThrowKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.UsingKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.OpenBraceToken: case SyntaxKind.SemicolonToken: case SyntaxKind.StaticKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: case SyntaxKind.RefKeyword: case SyntaxKind.ExternKeyword: case SyntaxKind.OpenBracketToken: return true; case SyntaxKind.IdentifierToken: return IsTrueIdentifier(); case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: return !_isInTry; // Accessibility modifiers are not legal in a statement, // but a common mistake for local functions. Parse to give a // better error message. case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: return acceptAccessibilityMods; default: return IsPredefinedType(tk) || IsPossibleExpression(); } } private FixedStatementSyntax ParseFixedStatement(SyntaxList<AttributeListSyntax> attributes) { var @fixed = this.EatToken(SyntaxKind.FixedKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfFixedStatement; var decl = ParseVariableDeclaration(); _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); StatementSyntax statement = this.ParseEmbeddedStatement(); return _syntaxFactory.FixedStatement(attributes, @fixed, openParen, decl, closeParen, statement); } private bool IsEndOfFixedStatement() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken; } private StatementSyntax ParseEmbeddedStatement() { // ParseEmbeddedStatement is called through many recursive statement parsing cases. We // keep the body exceptionally simple, and we optimize for the common case, to ensure it // is inlined into the callers. Otherwise the overhead of this single method can have a // deep impact on the number of recursive calls we can make (more than a hundred during // empirical testing). return parseEmbeddedStatementRest(this.ParsePossiblyAttributedStatement()); StatementSyntax parseEmbeddedStatementRest(StatementSyntax statement) { if (statement == null) { // The consumers of embedded statements are expecting to receive a non-null statement // yet there are several error conditions that can lead ParseStatementCore to return // null. When that occurs create an error empty Statement and return it to the caller. return SyntaxFactory.EmptyStatement(attributeLists: default, EatToken(SyntaxKind.SemicolonToken)); } // In scripts, stand-alone expression statements may not be followed by semicolons. // ParseExpressionStatement hides the error. // However, embedded expression statements are required to be followed by semicolon. if (statement.Kind == SyntaxKind.ExpressionStatement && IsScript) { var expressionStatementSyntax = (ExpressionStatementSyntax)statement; var semicolonToken = expressionStatementSyntax.SemicolonToken; // Do not add a new error if the same error was already added. if (semicolonToken.IsMissing && !semicolonToken.GetDiagnostics().Contains(diagnosticInfo => (ErrorCode)diagnosticInfo.Code == ErrorCode.ERR_SemicolonExpected)) { semicolonToken = this.AddError(semicolonToken, ErrorCode.ERR_SemicolonExpected); return expressionStatementSyntax.Update(expressionStatementSyntax.AttributeLists, expressionStatementSyntax.Expression, semicolonToken); } } return statement; } } private BreakStatementSyntax ParseBreakStatement(SyntaxList<AttributeListSyntax> attributes) { var breakKeyword = this.EatToken(SyntaxKind.BreakKeyword); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.BreakStatement(attributes, breakKeyword, semicolon); } private ContinueStatementSyntax ParseContinueStatement(SyntaxList<AttributeListSyntax> attributes) { var continueKeyword = this.EatToken(SyntaxKind.ContinueKeyword); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.ContinueStatement(attributes, continueKeyword, semicolon); } private TryStatementSyntax ParseTryStatement(SyntaxList<AttributeListSyntax> attributes) { var isInTry = _isInTry; _isInTry = true; var @try = this.EatToken(SyntaxKind.TryKeyword); BlockSyntax block; if (@try.IsMissing) { block = _syntaxFactory.Block( attributeLists: default, this.EatToken(SyntaxKind.OpenBraceToken), default(SyntaxList<StatementSyntax>), this.EatToken(SyntaxKind.CloseBraceToken)); } else { var saveTerm = _termState; _termState |= TerminatorState.IsEndOfTryBlock; block = this.ParsePossiblyAttributedBlock(); _termState = saveTerm; } var catches = default(SyntaxListBuilder<CatchClauseSyntax>); FinallyClauseSyntax @finally = null; try { bool hasEnd = false; if (this.CurrentToken.Kind == SyntaxKind.CatchKeyword) { hasEnd = true; catches = _pool.Allocate<CatchClauseSyntax>(); while (this.CurrentToken.Kind == SyntaxKind.CatchKeyword) { catches.Add(this.ParseCatchClause()); } } if (this.CurrentToken.Kind == SyntaxKind.FinallyKeyword) { hasEnd = true; var fin = this.EatToken(); var finBlock = this.ParsePossiblyAttributedBlock(); @finally = _syntaxFactory.FinallyClause(fin, finBlock); } if (!hasEnd) { block = this.AddErrorToLastToken(block, ErrorCode.ERR_ExpectedEndTry); // synthesize missing tokens for "finally { }": @finally = _syntaxFactory.FinallyClause( SyntaxToken.CreateMissing(SyntaxKind.FinallyKeyword, null, null), _syntaxFactory.Block( attributeLists: default, SyntaxToken.CreateMissing(SyntaxKind.OpenBraceToken, null, null), default(SyntaxList<StatementSyntax>), SyntaxToken.CreateMissing(SyntaxKind.CloseBraceToken, null, null))); } _isInTry = isInTry; return _syntaxFactory.TryStatement(attributes, @try, block, catches, @finally); } finally { if (!catches.IsNull) { _pool.Free(catches); } } } private bool IsEndOfTryBlock() { return this.CurrentToken.Kind == SyntaxKind.CloseBraceToken || this.CurrentToken.Kind == SyntaxKind.CatchKeyword || this.CurrentToken.Kind == SyntaxKind.FinallyKeyword; } private CatchClauseSyntax ParseCatchClause() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.CatchKeyword); var @catch = this.EatToken(); CatchDeclarationSyntax decl = null; var saveTerm = _termState; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var openParen = this.EatToken(); _termState |= TerminatorState.IsEndOfCatchClause; var type = this.ParseType(); SyntaxToken name = null; if (this.IsTrueIdentifier()) { name = this.ParseIdentifierToken(); } _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); decl = _syntaxFactory.CatchDeclaration(openParen, type, name, closeParen); } CatchFilterClauseSyntax filter = null; var keywordKind = this.CurrentToken.ContextualKind; if (keywordKind == SyntaxKind.WhenKeyword || keywordKind == SyntaxKind.IfKeyword) { var whenKeyword = this.EatContextualToken(SyntaxKind.WhenKeyword); if (keywordKind == SyntaxKind.IfKeyword) { // The initial design of C# exception filters called for the use of the // "if" keyword in this position. We've since changed to "when", but // the error recovery experience for early adopters (and for old source // stored in the symbol server) will be better if we consume "if" as // though it were "when". whenKeyword = AddTrailingSkippedSyntax(whenKeyword, EatToken()); } whenKeyword = CheckFeatureAvailability(whenKeyword, MessageID.IDS_FeatureExceptionFilter); _termState |= TerminatorState.IsEndOfFilterClause; var openParen = this.EatToken(SyntaxKind.OpenParenToken); var filterExpression = this.ParseExpressionCore(); _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); filter = _syntaxFactory.CatchFilterClause(whenKeyword, openParen, filterExpression, closeParen); } _termState |= TerminatorState.IsEndOfCatchBlock; var block = this.ParsePossiblyAttributedBlock(); _termState = saveTerm; return _syntaxFactory.CatchClause(@catch, decl, filter, block); } private bool IsEndOfCatchClause() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.Kind == SyntaxKind.CloseBraceToken || this.CurrentToken.Kind == SyntaxKind.CatchKeyword || this.CurrentToken.Kind == SyntaxKind.FinallyKeyword; } private bool IsEndOfFilterClause() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken || this.CurrentToken.Kind == SyntaxKind.CloseBraceToken || this.CurrentToken.Kind == SyntaxKind.CatchKeyword || this.CurrentToken.Kind == SyntaxKind.FinallyKeyword; } private bool IsEndOfCatchBlock() { return this.CurrentToken.Kind == SyntaxKind.CloseBraceToken || this.CurrentToken.Kind == SyntaxKind.CatchKeyword || this.CurrentToken.Kind == SyntaxKind.FinallyKeyword; } private StatementSyntax ParseCheckedStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.CheckedKeyword || this.CurrentToken.Kind == SyntaxKind.UncheckedKeyword); if (this.PeekToken(1).Kind == SyntaxKind.OpenParenToken) { return this.ParseExpressionStatement(attributes); } var spec = this.EatToken(); var block = this.ParsePossiblyAttributedBlock(); return _syntaxFactory.CheckedStatement(SyntaxFacts.GetCheckStatement(spec.Kind), attributes, spec, block); } private DoStatementSyntax ParseDoStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.DoKeyword); var @do = this.EatToken(SyntaxKind.DoKeyword); var statement = this.ParseEmbeddedStatement(); var @while = this.EatToken(SyntaxKind.WhileKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfDoWhileExpression; var expression = this.ParseExpressionCore(); _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.DoStatement(attributes, @do, statement, @while, openParen, expression, closeParen, semicolon); } private bool IsEndOfDoWhileExpression() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken; } private StatementSyntax ParseForOrForEachStatement(SyntaxList<AttributeListSyntax> attributes) { // Check if the user wrote the following accidentally: // // for (SomeType t in // // instead of // // foreach (SomeType t in // // In that case, parse it as a foreach, but given the appropriate message that a // 'foreach' keyword was expected. var resetPoint = this.GetResetPoint(); try { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ForKeyword); this.EatToken(); if (this.EatToken().Kind == SyntaxKind.OpenParenToken && this.ScanType() != ScanTypeFlags.NotType && this.EatToken().Kind == SyntaxKind.IdentifierToken && this.EatToken().Kind == SyntaxKind.InKeyword) { // Looks like a foreach statement. Parse it that way instead this.Reset(ref resetPoint); return this.ParseForEachStatement(attributes, awaitTokenOpt: null); } else { // Normal for statement. this.Reset(ref resetPoint); return this.ParseForStatement(attributes); } } finally { this.Release(ref resetPoint); } } private ForStatementSyntax ParseForStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ForKeyword); var forToken = this.EatToken(SyntaxKind.ForKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfForStatementArgument; var resetPoint = this.GetResetPoint(); var initializers = _pool.AllocateSeparated<ExpressionSyntax>(); var incrementors = _pool.AllocateSeparated<ExpressionSyntax>(); try { // Here can be either a declaration or an expression statement list. Scan // for a declaration first. VariableDeclarationSyntax decl = null; bool isDeclaration = false; if (this.CurrentToken.Kind == SyntaxKind.RefKeyword) { isDeclaration = true; } else { isDeclaration = !this.IsQueryExpression(mayBeVariableDeclaration: true, mayBeMemberDeclaration: false) && this.ScanType() != ScanTypeFlags.NotType && this.IsTrueIdentifier(); this.Reset(ref resetPoint); } if (isDeclaration) { decl = ParseVariableDeclaration(); if (decl.Type.Kind == SyntaxKind.RefType) { decl = decl.Update( CheckFeatureAvailability(decl.Type, MessageID.IDS_FeatureRefFor), decl.Variables); } } else if (this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { // Not a type followed by an identifier, so it must be an expression list. this.ParseForStatementExpressionList(ref openParen, initializers); } var semi = this.EatToken(SyntaxKind.SemicolonToken); ExpressionSyntax condition = null; if (this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { condition = this.ParseExpressionCore(); } var semi2 = this.EatToken(SyntaxKind.SemicolonToken); if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { this.ParseForStatementExpressionList(ref semi2, incrementors); } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = ParseEmbeddedStatement(); return _syntaxFactory.ForStatement(attributes, forToken, openParen, decl, initializers, semi, condition, semi2, incrementors, closeParen, statement); } finally { _termState = saveTerm; this.Release(ref resetPoint); _pool.Free(incrementors); _pool.Free(initializers); } } private bool IsEndOfForStatementArgument() { return this.CurrentToken.Kind == SyntaxKind.SemicolonToken || this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; } private void ParseForStatementExpressionList(ref SyntaxToken startToken, SeparatedSyntaxListBuilder<ExpressionSyntax> list) { if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken && this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { tryAgain: if (this.IsPossibleExpression() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument list.Add(this.ParseExpressionCore()); // additional arguments int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleExpression()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); list.Add(this.ParseExpressionCore()); continue; } else if (this.SkipBadForStatementExpressionListTokens(ref startToken, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadForStatementExpressionListTokens(ref startToken, list, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } } private PostSkipAction SkipBadForStatementExpressionListTokens(ref SyntaxToken startToken, SeparatedSyntaxListBuilder<ExpressionSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), p => p.CurrentToken.Kind == SyntaxKind.CloseParenToken || p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsTerminator(), expected); } private CommonForEachStatementSyntax ParseForEachStatement( SyntaxList<AttributeListSyntax> attributes, SyntaxToken awaitTokenOpt) { // Can be a 'for' keyword if the user typed: 'for (SomeType t in' Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ForEachKeyword || this.CurrentToken.Kind == SyntaxKind.ForKeyword); // Syntax for foreach is either: // foreach [await] ( <type> <identifier> in <expr> ) <embedded-statement> // or // foreach [await] ( <deconstruction-declaration> in <expr> ) <embedded-statement> SyntaxToken @foreach; // If we're at a 'for', then consume it and attach // it as skipped text to the missing 'foreach' token. if (this.CurrentToken.Kind == SyntaxKind.ForKeyword) { var skippedForToken = this.EatToken(); skippedForToken = this.AddError(skippedForToken, ErrorCode.ERR_SyntaxError, SyntaxFacts.GetText(SyntaxKind.ForEachKeyword), SyntaxFacts.GetText(SyntaxKind.ForKeyword)); @foreach = ConvertToMissingWithTrailingTrivia(skippedForToken, SyntaxKind.ForEachKeyword); } else { @foreach = this.EatToken(SyntaxKind.ForEachKeyword); } var openParen = this.EatToken(SyntaxKind.OpenParenToken); var variable = ParseExpressionOrDeclaration(ParseTypeMode.Normal, feature: MessageID.IDS_FeatureTuples, permitTupleDesignation: true); var @in = this.EatToken(SyntaxKind.InKeyword, ErrorCode.ERR_InExpected); if (!IsValidForeachVariable(variable)) { @in = this.AddError(@in, ErrorCode.ERR_BadForeachDecl); } var expression = this.ParseExpressionCore(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = this.ParseEmbeddedStatement(); if (variable is DeclarationExpressionSyntax decl) { if (decl.Type.Kind == SyntaxKind.RefType) { decl = decl.Update( CheckFeatureAvailability(decl.Type, MessageID.IDS_FeatureRefForEach), decl.Designation); } if (decl.designation.Kind != SyntaxKind.ParenthesizedVariableDesignation) { // if we see a foreach declaration that isn't a deconstruction, we use the old form of foreach syntax node. SyntaxToken identifier; switch (decl.designation.Kind) { case SyntaxKind.SingleVariableDesignation: identifier = ((SingleVariableDesignationSyntax)decl.designation).identifier; break; case SyntaxKind.DiscardDesignation: // revert the identifier from its contextual underscore back to an identifier. var discard = ((DiscardDesignationSyntax)decl.designation).underscoreToken; Debug.Assert(discard.Kind == SyntaxKind.UnderscoreToken); identifier = SyntaxToken.WithValue(SyntaxKind.IdentifierToken, discard.LeadingTrivia.Node, discard.Text, discard.ValueText, discard.TrailingTrivia.Node); break; default: throw ExceptionUtilities.UnexpectedValue(decl.designation.Kind); } return _syntaxFactory.ForEachStatement(attributes, awaitTokenOpt, @foreach, openParen, decl.Type, identifier, @in, expression, closeParen, statement); } } return _syntaxFactory.ForEachVariableStatement(attributes, awaitTokenOpt, @foreach, openParen, variable, @in, expression, closeParen, statement); } // // Parse an expression where a declaration expression would be permitted. This is suitable for use after // the `out` keyword in an argument list, or in the elements of a tuple literal (because they may // be on the left-hand-side of a positional subpattern). The first element of a tuple is handled slightly // differently, as we check for the comma before concluding that the identifier should cause a // disambiguation. For example, for the input `(A < B , C > D)`, we treat this as a tuple with // two elements, because if we considered the `A<B,C>` to be a type, it wouldn't be a tuple at // all. Since we don't have such a thing as a one-element tuple (even for positional subpattern), the // absence of the comma after the `D` means we don't treat the `D` as contributing to the // disambiguation of the expression/type. More formally, ... // // If a sequence of tokens can be parsed(in context) as a* simple-name* (§7.6.3), *member-access* (§7.6.5), // or* pointer-member-access* (§18.5.2) ending with a* type-argument-list* (§4.4.1), the token immediately // following the closing `>` token is examined, to see if it is // - One of `( ) ] } : ; , . ? == != | ^ && || & [`; or // - One of the relational operators `< > <= >= is as`; or // - A contextual query keyword appearing inside a query expression; or // - In certain contexts, we treat *identifier* as a disambiguating token.Those contexts are where the // sequence of tokens being disambiguated is immediately preceded by one of the keywords `is`, `case` // or `out`, or arises while parsing the first element of a tuple literal(in which case the tokens are // preceded by `(` or `:` and the identifier is followed by a `,`) or a subsequent element of a tuple literal. // // If the following token is among this list, or an identifier in such a context, then the *type-argument-list* is // retained as part of the *simple-name*, *member-access* or *pointer-member-access* and any other possible parse // of the sequence of tokens is discarded.Otherwise, the *type-argument-list* is not considered to be part of the // *simple-name*, *member-access* or *pointer-member-access*, even if there is no other possible parse of the // sequence of tokens.Note that these rules are not applied when parsing a *type-argument-list* in a *namespace-or-type-name* (§3.8). // // See also ScanTypeArgumentList where these disambiguation rules are encoded. // private ExpressionSyntax ParseExpressionOrDeclaration(ParseTypeMode mode, MessageID feature, bool permitTupleDesignation) { return IsPossibleDeclarationExpression(mode, permitTupleDesignation) ? this.ParseDeclarationExpression(mode, feature) : this.ParseSubExpression(Precedence.Expression); } private bool IsPossibleDeclarationExpression(ParseTypeMode mode, bool permitTupleDesignation) { if (this.IsInAsync && this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword) { // can't be a declaration expression. return false; } var resetPoint = this.GetResetPoint(); try { bool typeIsVar = IsVarType(); SyntaxToken lastTokenOfType; if (ScanType(mode, out lastTokenOfType) == ScanTypeFlags.NotType) { return false; } // check for a designation if (!ScanDesignation(permitTupleDesignation && (typeIsVar || IsPredefinedType(lastTokenOfType.Kind)))) { return false; } switch (mode) { case ParseTypeMode.FirstElementOfPossibleTupleLiteral: return this.CurrentToken.Kind == SyntaxKind.CommaToken; case ParseTypeMode.AfterTupleComma: return this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.CloseParenToken; default: // The other case where we disambiguate between a declaration and expression is before the `in` of a foreach loop. // There we err on the side of accepting a declaration. return true; } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } /// <summary> /// Is the following set of tokens, interpreted as a type, the type <c>var</c>? /// </summary> private bool IsVarType() { if (!this.CurrentToken.IsIdentifierVar()) { return false; } switch (this.PeekToken(1).Kind) { case SyntaxKind.DotToken: case SyntaxKind.ColonColonToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.AsteriskToken: case SyntaxKind.QuestionToken: case SyntaxKind.LessThanToken: return false; default: return true; } } private static bool IsValidForeachVariable(ExpressionSyntax variable) { switch (variable.Kind) { case SyntaxKind.DeclarationExpression: // e.g. `foreach (var (x, y) in e)` return true; case SyntaxKind.TupleExpression: // e.g. `foreach ((var x, var y) in e)` return true; case SyntaxKind.IdentifierName: // e.g. `foreach (_ in e)` return ((IdentifierNameSyntax)variable).Identifier.ContextualKind == SyntaxKind.UnderscoreToken; default: return false; } } private GotoStatementSyntax ParseGotoStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.GotoKeyword); var @goto = this.EatToken(SyntaxKind.GotoKeyword); SyntaxToken caseOrDefault = null; ExpressionSyntax arg = null; SyntaxKind kind; if (this.CurrentToken.Kind == SyntaxKind.CaseKeyword || this.CurrentToken.Kind == SyntaxKind.DefaultKeyword) { caseOrDefault = this.EatToken(); if (caseOrDefault.Kind == SyntaxKind.CaseKeyword) { kind = SyntaxKind.GotoCaseStatement; arg = this.ParseExpressionCore(); } else { kind = SyntaxKind.GotoDefaultStatement; } } else { kind = SyntaxKind.GotoStatement; arg = this.ParseIdentifierName(); } var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.GotoStatement(kind, attributes, @goto, caseOrDefault, arg, semicolon); } private IfStatementSyntax ParseIfStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.IfKeyword); return _syntaxFactory.IfStatement( attributes, this.EatToken(SyntaxKind.IfKeyword), this.EatToken(SyntaxKind.OpenParenToken), this.ParseExpressionCore(), this.EatToken(SyntaxKind.CloseParenToken), this.ParseEmbeddedStatement(), this.ParseElseClauseOpt()); } private IfStatementSyntax ParseMisplacedElse(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ElseKeyword); return _syntaxFactory.IfStatement( attributes, this.EatToken(SyntaxKind.IfKeyword, ErrorCode.ERR_ElseCannotStartStatement), this.EatToken(SyntaxKind.OpenParenToken), this.ParseExpressionCore(), this.EatToken(SyntaxKind.CloseParenToken), this.ParseExpressionStatement(attributes: default), this.ParseElseClauseOpt()); } private ElseClauseSyntax ParseElseClauseOpt() { if (this.CurrentToken.Kind != SyntaxKind.ElseKeyword) { return null; } var elseToken = this.EatToken(SyntaxKind.ElseKeyword); var elseStatement = this.ParseEmbeddedStatement(); return _syntaxFactory.ElseClause(elseToken, elseStatement); } private LockStatementSyntax ParseLockStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.LockKeyword); var @lock = this.EatToken(SyntaxKind.LockKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expression = this.ParseExpressionCore(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = this.ParseEmbeddedStatement(); return _syntaxFactory.LockStatement(attributes, @lock, openParen, expression, closeParen, statement); } private ReturnStatementSyntax ParseReturnStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ReturnKeyword); var @return = this.EatToken(SyntaxKind.ReturnKeyword); ExpressionSyntax arg = null; if (this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { arg = this.ParsePossibleRefExpression(); } var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.ReturnStatement(attributes, @return, arg, semicolon); } private YieldStatementSyntax ParseYieldStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.YieldKeyword); var yieldToken = ConvertToKeyword(this.EatToken()); SyntaxToken returnOrBreak; ExpressionSyntax arg = null; SyntaxKind kind; yieldToken = CheckFeatureAvailability(yieldToken, MessageID.IDS_FeatureIterators); if (this.CurrentToken.Kind == SyntaxKind.BreakKeyword) { kind = SyntaxKind.YieldBreakStatement; returnOrBreak = this.EatToken(); } else { kind = SyntaxKind.YieldReturnStatement; returnOrBreak = this.EatToken(SyntaxKind.ReturnKeyword); if (this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { returnOrBreak = this.AddError(returnOrBreak, ErrorCode.ERR_EmptyYield); } else { arg = this.ParseExpressionCore(); } } var semi = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.YieldStatement(kind, attributes, yieldToken, returnOrBreak, arg, semi); } private SwitchStatementSyntax ParseSwitchStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.SwitchKeyword); var @switch = this.EatToken(SyntaxKind.SwitchKeyword); var expression = this.ParseExpressionCore(); SyntaxToken openParen; SyntaxToken closeParen; if (expression.Kind == SyntaxKind.ParenthesizedExpression) { var parenExpression = (ParenthesizedExpressionSyntax)expression; openParen = parenExpression.OpenParenToken; expression = parenExpression.Expression; closeParen = parenExpression.CloseParenToken; Debug.Assert(parenExpression.GetDiagnostics().Length == 0); } else if (expression.Kind == SyntaxKind.TupleExpression) { // As a special case, when a tuple literal is the governing expression of // a switch statement we permit the switch statement's own parentheses to be omitted. // LDM 2018-04-04. openParen = closeParen = null; } else { // Some other expression has appeared without parens. Give a syntax error. openParen = SyntaxFactory.MissingToken(SyntaxKind.OpenParenToken); expression = this.AddError(expression, ErrorCode.ERR_SwitchGoverningExpressionRequiresParens); closeParen = SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken); } var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var sections = _pool.Allocate<SwitchSectionSyntax>(); try { while (this.IsPossibleSwitchSection()) { var swcase = this.ParseSwitchSection(); sections.Add(swcase); } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); return _syntaxFactory.SwitchStatement(attributes, @switch, openParen, expression, closeParen, openBrace, sections, closeBrace); } finally { _pool.Free(sections); } } private bool IsPossibleSwitchSection() { return (this.CurrentToken.Kind == SyntaxKind.CaseKeyword) || (this.CurrentToken.Kind == SyntaxKind.DefaultKeyword && this.PeekToken(1).Kind != SyntaxKind.OpenParenToken); } private SwitchSectionSyntax ParseSwitchSection() { Debug.Assert(this.IsPossibleSwitchSection()); // First, parse case label(s) var labels = _pool.Allocate<SwitchLabelSyntax>(); var statements = _pool.Allocate<StatementSyntax>(); try { do { SyntaxToken specifier; SwitchLabelSyntax label; SyntaxToken colon; if (this.CurrentToken.Kind == SyntaxKind.CaseKeyword) { ExpressionSyntax expression; specifier = this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { expression = ParseIdentifierName(ErrorCode.ERR_ConstantExpected); colon = this.EatToken(SyntaxKind.ColonToken); label = _syntaxFactory.CaseSwitchLabel(specifier, expression, colon); } else { var node = ParseExpressionOrPatternForSwitchStatement(); // if there is a 'when' token, we treat a case expression as a constant pattern. if (this.CurrentToken.ContextualKind == SyntaxKind.WhenKeyword && node is ExpressionSyntax ex) node = _syntaxFactory.ConstantPattern(ex); if (node.Kind == SyntaxKind.DiscardPattern) node = this.AddError(node, ErrorCode.ERR_DiscardPatternInSwitchStatement); if (node is PatternSyntax pat) { var whenClause = ParseWhenClause(Precedence.Expression); colon = this.EatToken(SyntaxKind.ColonToken); label = _syntaxFactory.CasePatternSwitchLabel(specifier, pat, whenClause, colon); label = CheckFeatureAvailability(label, MessageID.IDS_FeaturePatternMatching); } else { colon = this.EatToken(SyntaxKind.ColonToken); label = _syntaxFactory.CaseSwitchLabel(specifier, (ExpressionSyntax)node, colon); } } } else { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.DefaultKeyword); specifier = this.EatToken(SyntaxKind.DefaultKeyword); colon = this.EatToken(SyntaxKind.ColonToken); label = _syntaxFactory.DefaultSwitchLabel(specifier, colon); } labels.Add(label); } while (IsPossibleSwitchSection()); // Next, parse statement list stopping for new sections CSharpSyntaxNode tmp = labels[labels.Count - 1]; this.ParseStatements(ref tmp, statements, true); labels[labels.Count - 1] = (SwitchLabelSyntax)tmp; return _syntaxFactory.SwitchSection(labels, statements); } finally { _pool.Free(statements); _pool.Free(labels); } } private ThrowStatementSyntax ParseThrowStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.ThrowKeyword); var @throw = this.EatToken(SyntaxKind.ThrowKeyword); ExpressionSyntax arg = null; if (this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { arg = this.ParseExpressionCore(); } var semi = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.ThrowStatement(attributes, @throw, arg, semi); } private UnsafeStatementSyntax ParseUnsafeStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.UnsafeKeyword); var @unsafe = this.EatToken(SyntaxKind.UnsafeKeyword); var block = this.ParsePossiblyAttributedBlock(); return _syntaxFactory.UnsafeStatement(attributes, @unsafe, block); } private UsingStatementSyntax ParseUsingStatement(SyntaxList<AttributeListSyntax> attributes, SyntaxToken awaitTokenOpt = null) { var @using = this.EatToken(SyntaxKind.UsingKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); VariableDeclarationSyntax declaration = null; ExpressionSyntax expression = null; var resetPoint = this.GetResetPoint(); ParseUsingExpression(ref declaration, ref expression, ref resetPoint); this.Release(ref resetPoint); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = this.ParseEmbeddedStatement(); return _syntaxFactory.UsingStatement(attributes, awaitTokenOpt, @using, openParen, declaration, expression, closeParen, statement); } private void ParseUsingExpression(ref VariableDeclarationSyntax declaration, ref ExpressionSyntax expression, ref ResetPoint resetPoint) { if (this.IsAwaitExpression()) { expression = this.ParseExpressionCore(); return; } // Now, this can be either an expression or a decl list ScanTypeFlags st; if (this.IsQueryExpression(mayBeVariableDeclaration: true, mayBeMemberDeclaration: false)) { st = ScanTypeFlags.NotType; } else { st = this.ScanType(); } if (st == ScanTypeFlags.NullableType) { // We need to handle: // * using (f ? x = a : x = b) // * using (f ? x = a) // * using (f ? x, y) if (this.CurrentToken.Kind != SyntaxKind.IdentifierToken) { this.Reset(ref resetPoint); expression = this.ParseExpressionCore(); } else { switch (this.PeekToken(1).Kind) { default: this.Reset(ref resetPoint); expression = this.ParseExpressionCore(); break; case SyntaxKind.CommaToken: case SyntaxKind.CloseParenToken: this.Reset(ref resetPoint); declaration = ParseVariableDeclaration(); break; case SyntaxKind.EqualsToken: // Parse it as a decl. If the next token is a : and only one variable was parsed, // convert the whole thing to ?: expression. this.Reset(ref resetPoint); declaration = ParseVariableDeclaration(); // We may have non-nullable types in error scenarios. if (this.CurrentToken.Kind == SyntaxKind.ColonToken && declaration.Type.Kind == SyntaxKind.NullableType && SyntaxFacts.IsName(((NullableTypeSyntax)declaration.Type).ElementType.Kind) && declaration.Variables.Count == 1) { // We have "name? id = expr :" so need to convert to a ?: expression. this.Reset(ref resetPoint); declaration = null; expression = this.ParseExpressionCore(); } break; } } } else if (IsUsingStatementVariableDeclaration(st)) { this.Reset(ref resetPoint); declaration = ParseVariableDeclaration(); } else { // Must be an expression statement this.Reset(ref resetPoint); expression = this.ParseExpressionCore(); } } private bool IsUsingStatementVariableDeclaration(ScanTypeFlags st) { Debug.Assert(st != ScanTypeFlags.NullableType); bool condition1 = st == ScanTypeFlags.MustBeType && this.CurrentToken.Kind != SyntaxKind.DotToken; bool condition2 = st != ScanTypeFlags.NotType && this.CurrentToken.Kind == SyntaxKind.IdentifierToken; bool condition3 = st == ScanTypeFlags.NonGenericTypeOrExpression || this.PeekToken(1).Kind == SyntaxKind.EqualsToken; return condition1 || (condition2 && condition3); } private WhileStatementSyntax ParseWhileStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.WhileKeyword); var @while = this.EatToken(SyntaxKind.WhileKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var condition = this.ParseExpressionCore(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var statement = this.ParseEmbeddedStatement(); return _syntaxFactory.WhileStatement(attributes, @while, openParen, condition, closeParen, statement); } private LabeledStatementSyntax ParseLabeledStatement(SyntaxList<AttributeListSyntax> attributes) { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.IdentifierToken); // We have an identifier followed by a colon. But if the identifier is a contextual keyword in a query context, // ParseIdentifier will result in a missing name and Eat(Colon) will fail. We won't make forward progress. Debug.Assert(this.IsTrueIdentifier()); var label = this.ParseIdentifierToken(); var colon = this.EatToken(SyntaxKind.ColonToken); Debug.Assert(!colon.IsMissing); var statement = this.ParsePossiblyAttributedStatement() ?? SyntaxFactory.EmptyStatement(attributeLists: default, EatToken(SyntaxKind.SemicolonToken)); return _syntaxFactory.LabeledStatement(attributes, label, colon, statement); } /// <summary> /// Parses any kind of local declaration statement: local variable or local function. /// </summary> private StatementSyntax ParseLocalDeclarationStatement(SyntaxList<AttributeListSyntax> attributes) { SyntaxToken awaitKeyword, usingKeyword; bool canParseAsLocalFunction = false; if (IsPossibleAwaitUsing()) { awaitKeyword = ParseAwaitKeyword(MessageID.None); usingKeyword = EatToken(); } else if (this.CurrentToken.Kind == SyntaxKind.UsingKeyword) { awaitKeyword = null; usingKeyword = EatToken(); } else { awaitKeyword = null; usingKeyword = null; canParseAsLocalFunction = true; } if (usingKeyword != null) { usingKeyword = CheckFeatureAvailability(usingKeyword, MessageID.IDS_FeatureUsingDeclarations); } var mods = _pool.Allocate(); this.ParseDeclarationModifiers(mods); var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); try { this.ParseLocalDeclaration(variables, allowLocalFunctions: canParseAsLocalFunction, attributes: attributes, mods: mods.ToList(), type: out var type, localFunction: out var localFunction); if (localFunction != null) { Debug.Assert(variables.Count == 0); return localFunction; } if (canParseAsLocalFunction) { // If we find an accessibility modifier but no local function it's likely // the user forgot a closing brace. Let's back out of statement parsing. // We check just for a leading accessibility modifier in the syntax because // SkipBadStatementListTokens will not skip attribute lists. if (attributes.Count == 0 && mods.Count > 0 && IsAccessibilityModifier(((SyntaxToken)mods[0]).ContextualKind)) { return null; } } for (int i = 0; i < mods.Count; i++) { var mod = (SyntaxToken)mods[i]; if (IsAdditionalLocalFunctionModifier(mod.ContextualKind)) { mods[i] = this.AddError(mod, ErrorCode.ERR_BadMemberFlag, mod.Text); } } var semicolon = this.EatToken(SyntaxKind.SemicolonToken); return _syntaxFactory.LocalDeclarationStatement( attributes, awaitKeyword, usingKeyword, mods.ToList(), _syntaxFactory.VariableDeclaration(type, variables), semicolon); } finally { _pool.Free(variables); _pool.Free(mods); } } private VariableDesignationSyntax ParseDesignation(bool forPattern) { // the two forms of designation are // (1) identifier // (2) ( designation ... ) // for pattern-matching, we permit the designation list to be empty VariableDesignationSyntax result; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var openParen = this.EatToken(SyntaxKind.OpenParenToken); var listOfDesignations = _pool.AllocateSeparated<VariableDesignationSyntax>(); bool done = false; if (forPattern) { done = (this.CurrentToken.Kind == SyntaxKind.CloseParenToken); } else { listOfDesignations.Add(ParseDesignation(forPattern)); listOfDesignations.AddSeparator(EatToken(SyntaxKind.CommaToken)); } if (!done) { while (true) { listOfDesignations.Add(ParseDesignation(forPattern)); if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { listOfDesignations.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); } else { break; } } } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); result = _syntaxFactory.ParenthesizedVariableDesignation(openParen, listOfDesignations, closeParen); _pool.Free(listOfDesignations); } else { result = ParseSimpleDesignation(); } return result; } /// <summary> /// Parse a single variable designation (e.g. <c>x</c>) or a wildcard designation (e.g. <c>_</c>) /// </summary> /// <returns></returns> private VariableDesignationSyntax ParseSimpleDesignation() { if (CurrentToken.ContextualKind == SyntaxKind.UnderscoreToken) { var underscore = this.EatContextualToken(SyntaxKind.UnderscoreToken); return _syntaxFactory.DiscardDesignation(underscore); } else { var identifier = this.EatToken(SyntaxKind.IdentifierToken); return _syntaxFactory.SingleVariableDesignation(identifier); } } private WhenClauseSyntax ParseWhenClause(Precedence precedence) { if (this.CurrentToken.ContextualKind != SyntaxKind.WhenKeyword) { return null; } var when = this.EatContextualToken(SyntaxKind.WhenKeyword); var condition = ParseSubExpression(precedence); return _syntaxFactory.WhenClause(when, condition); } /// <summary> /// Parse a local variable declaration. /// </summary> /// <returns></returns> private VariableDeclarationSyntax ParseVariableDeclaration() { var variables = _pool.AllocateSeparated<VariableDeclaratorSyntax>(); TypeSyntax type; LocalFunctionStatementSyntax localFunction; ParseLocalDeclaration(variables, false, attributes: default, mods: default, out type, out localFunction); Debug.Assert(localFunction == null); var result = _syntaxFactory.VariableDeclaration(type, variables); _pool.Free(variables); return result; } private void ParseLocalDeclaration( SeparatedSyntaxListBuilder<VariableDeclaratorSyntax> variables, bool allowLocalFunctions, SyntaxList<AttributeListSyntax> attributes, SyntaxList<SyntaxToken> mods, out TypeSyntax type, out LocalFunctionStatementSyntax localFunction) { type = allowLocalFunctions ? ParseReturnType() : this.ParseType(); VariableFlags flags = VariableFlags.Local; if (mods.Any((int)SyntaxKind.ConstKeyword)) { flags |= VariableFlags.Const; } var saveTerm = _termState; _termState |= TerminatorState.IsEndOfDeclarationClause; this.ParseVariableDeclarators( type, flags, variables, variableDeclarationsExpected: true, allowLocalFunctions: allowLocalFunctions, attributes: attributes, mods: mods, localFunction: out localFunction); _termState = saveTerm; if (allowLocalFunctions && localFunction == null && (type as PredefinedTypeSyntax)?.Keyword.Kind == SyntaxKind.VoidKeyword) { type = this.AddError(type, ErrorCode.ERR_NoVoidHere); } } private bool IsEndOfDeclarationClause() { switch (this.CurrentToken.Kind) { case SyntaxKind.SemicolonToken: case SyntaxKind.CloseParenToken: case SyntaxKind.ColonToken: return true; default: return false; } } private void ParseDeclarationModifiers(SyntaxListBuilder list) { SyntaxKind k; while (IsDeclarationModifier(k = this.CurrentToken.ContextualKind) || IsAdditionalLocalFunctionModifier(k)) { SyntaxToken mod; if (k == SyntaxKind.AsyncKeyword) { // check for things like "async async()" where async is the type and/or the function name { var resetPoint = this.GetResetPoint(); var invalid = !IsPossibleStartOfTypeDeclaration(this.EatToken().Kind) && !IsDeclarationModifier(this.CurrentToken.Kind) && !IsAdditionalLocalFunctionModifier(this.CurrentToken.Kind) && (ScanType() == ScanTypeFlags.NotType || this.CurrentToken.Kind != SyntaxKind.IdentifierToken); this.Reset(ref resetPoint); this.Release(ref resetPoint); if (invalid) { break; } } mod = this.EatContextualToken(k); if (k == SyntaxKind.AsyncKeyword) { mod = CheckFeatureAvailability(mod, MessageID.IDS_FeatureAsync); } } else { mod = this.EatToken(); } if (k == SyntaxKind.ReadOnlyKeyword || k == SyntaxKind.VolatileKeyword) { mod = this.AddError(mod, ErrorCode.ERR_BadMemberFlag, mod.Text); } else if (list.Any(mod.RawKind)) { // check for duplicates, can only be const mod = this.AddError(mod, ErrorCode.ERR_TypeExpected, mod.Text); } list.Add(mod); } } private static bool IsDeclarationModifier(SyntaxKind kind) { switch (kind) { case SyntaxKind.ConstKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: return true; default: return false; } } private static bool IsAdditionalLocalFunctionModifier(SyntaxKind kind) { switch (kind) { case SyntaxKind.StaticKeyword: case SyntaxKind.AsyncKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.ExternKeyword: // Not a valid modifier, but we should parse to give a good // error message case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: return true; default: return false; } } private static bool IsAccessibilityModifier(SyntaxKind kind) { switch (kind) { // Accessibility modifiers aren't legal in a local function, // but a common mistake. Parse to give a better error message. case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: return true; default: return false; } } private LocalFunctionStatementSyntax TryParseLocalFunctionStatementBody( SyntaxList<AttributeListSyntax> attributes, SyntaxList<SyntaxToken> modifiers, TypeSyntax type, SyntaxToken identifier) { // This may potentially be an ambiguous parse until very far into the token stream, so we may have to backtrack. // For example, "await x()" is ambiguous at the current point of parsing (right now we're right after the x). // The point at which it becomes unambiguous is after the argument list. A "=>" or "{" means its a local function // (with return type @await), a ";" or other expression-y token means its an await of a function call. // Note that we could just check if we're in an async context, but that breaks some analyzers, because // "await f();" would be parsed as a local function statement when really we want a parse error so we can say // "did you mean to make this method be an async method?" (it's invalid either way, so the spec doesn't care) var resetPoint = this.GetResetPoint(); // Indicates this must be parsed as a local function, even if there's no body bool forceLocalFunc = true; if (type.Kind == SyntaxKind.IdentifierName) { var id = ((IdentifierNameSyntax)type).Identifier; forceLocalFunc = id.ContextualKind != SyntaxKind.AwaitKeyword; } bool parentScopeIsInAsync = IsInAsync; IsInAsync = false; SyntaxListBuilder badBuilder = null; for (int i = 0; i < modifiers.Count; i++) { var modifier = modifiers[i]; switch (modifier.ContextualKind) { case SyntaxKind.AsyncKeyword: IsInAsync = true; forceLocalFunc = true; continue; case SyntaxKind.UnsafeKeyword: forceLocalFunc = true; continue; case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: continue; // already reported earlier, no need to report again case SyntaxKind.StaticKeyword: modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureStaticLocalFunctions); if ((object)modifier == modifiers[i]) { continue; } break; case SyntaxKind.ExternKeyword: modifier = CheckFeatureAvailability(modifier, MessageID.IDS_FeatureExternLocalFunctions); if ((object)modifier == modifiers[i]) { continue; } break; default: modifier = this.AddError(modifier, ErrorCode.ERR_BadMemberFlag, modifier.Text); break; } if (badBuilder == null) { badBuilder = _pool.Allocate(); badBuilder.AddRange(modifiers); } badBuilder[i] = modifier; } if (badBuilder != null) { modifiers = badBuilder.ToList(); _pool.Free(badBuilder); } TypeParameterListSyntax typeParameterListOpt = this.ParseTypeParameterList(); // "await f<T>()" still makes sense, so don't force accept a local function if there's a type parameter list. ParameterListSyntax paramList = this.ParseParenthesizedParameterList(); // "await x()" is ambiguous (see note at start of this method), but we assume "await x(await y)" is meant to be a function if it's in a non-async context. if (!forceLocalFunc) { var paramListSyntax = paramList.Parameters; for (int i = 0; i < paramListSyntax.Count; i++) { // "await x(y)" still parses as a parameter list, so check to see if it's a valid parameter (like "x(t y)") forceLocalFunc |= !paramListSyntax[i].ContainsDiagnostics; if (forceLocalFunc) break; } } var constraints = default(SyntaxListBuilder<TypeParameterConstraintClauseSyntax>); if (this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword) { constraints = _pool.Allocate<TypeParameterConstraintClauseSyntax>(); this.ParseTypeParameterConstraintClauses(constraints); forceLocalFunc = true; } BlockSyntax blockBody; ArrowExpressionClauseSyntax expressionBody; SyntaxToken semicolon; this.ParseBlockAndExpressionBodiesWithSemicolon(out blockBody, out expressionBody, out semicolon, parseSemicolonAfterBlock: false); IsInAsync = parentScopeIsInAsync; if (!forceLocalFunc && blockBody == null && expressionBody == null) { this.Reset(ref resetPoint); this.Release(ref resetPoint); return null; } this.Release(ref resetPoint); identifier = CheckFeatureAvailability(identifier, MessageID.IDS_FeatureLocalFunctions); return _syntaxFactory.LocalFunctionStatement( attributes, modifiers, type, identifier, typeParameterListOpt, paramList, constraints, blockBody, expressionBody, semicolon); } private ExpressionStatementSyntax ParseExpressionStatement(SyntaxList<AttributeListSyntax> attributes) { return ParseExpressionStatement(attributes, this.ParseExpressionCore()); } private ExpressionStatementSyntax ParseExpressionStatement(SyntaxList<AttributeListSyntax> attributes, ExpressionSyntax expression) { SyntaxToken semicolon; if (IsScript && this.CurrentToken.Kind == SyntaxKind.EndOfFileToken) { semicolon = SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken); } else { // Do not report an error if the expression is not a statement expression. // The error is reported in semantic analysis. semicolon = this.EatToken(SyntaxKind.SemicolonToken); } return _syntaxFactory.ExpressionStatement(attributes, expression, semicolon); } public ExpressionSyntax ParseExpression() { return ParseWithStackGuard( this.ParseExpressionCore, this.CreateMissingIdentifierName); } private ExpressionSyntax ParseExpressionCore() { return this.ParseSubExpression(Precedence.Expression); } /// <summary> /// Is the current token one that could start an expression? /// </summary> private bool CanStartExpression() { return IsPossibleExpression(allowBinaryExpressions: false, allowAssignmentExpressions: false, allowAttributes: false); } /// <summary> /// Is the current token one that could be in an expression? /// </summary> private bool IsPossibleExpression() { return IsPossibleExpression(allowBinaryExpressions: true, allowAssignmentExpressions: true, allowAttributes: true); } private bool IsPossibleExpression(bool allowBinaryExpressions, bool allowAssignmentExpressions, bool allowAttributes) { SyntaxKind tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.TypeOfKeyword: case SyntaxKind.DefaultKeyword: case SyntaxKind.SizeOfKeyword: case SyntaxKind.MakeRefKeyword: case SyntaxKind.RefTypeKeyword: case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: case SyntaxKind.RefValueKeyword: case SyntaxKind.ArgListKeyword: case SyntaxKind.BaseKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.ThisKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.NullKeyword: case SyntaxKind.OpenParenToken: case SyntaxKind.NumericLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.NewKeyword: case SyntaxKind.DelegateKeyword: case SyntaxKind.ColonColonToken: // bad aliased name case SyntaxKind.ThrowKeyword: case SyntaxKind.StackAllocKeyword: case SyntaxKind.DotDotToken: case SyntaxKind.RefKeyword: return true; case SyntaxKind.StaticKeyword: return IsPossibleAnonymousMethodExpression() || IsPossibleLambdaExpression(Precedence.Expression); case SyntaxKind.OpenBracketToken: return allowAttributes && IsPossibleLambdaExpression(Precedence.Expression); case SyntaxKind.IdentifierToken: // Specifically allow the from contextual keyword, because it can always be the start of an // expression (whether it is used as an identifier or a keyword). return this.IsTrueIdentifier() || (this.CurrentToken.ContextualKind == SyntaxKind.FromKeyword); default: return IsPredefinedType(tk) || SyntaxFacts.IsAnyUnaryExpression(tk) || (allowBinaryExpressions && SyntaxFacts.IsBinaryExpression(tk)) || (allowAssignmentExpressions && SyntaxFacts.IsAssignmentExpressionOperatorToken(tk)); } } private static bool IsInvalidSubExpression(SyntaxKind kind) { switch (kind) { case SyntaxKind.BreakKeyword: case SyntaxKind.CaseKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.FinallyKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.LockKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.UsingKeyword: case SyntaxKind.WhileKeyword: return true; default: return false; } } internal static bool IsRightAssociative(SyntaxKind op) { switch (op) { case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: case SyntaxKind.CoalesceExpression: return true; default: return false; } } private enum Precedence : uint { Expression = 0, // Loosest possible precedence, used to accept all expressions Assignment = Expression, Lambda = Assignment, // "The => operator has the same precedence as assignment (=) and is right-associative." Conditional, Coalescing, ConditionalOr, ConditionalAnd, LogicalOr, LogicalXor, LogicalAnd, Equality, Relational, Shift, Additive, Multiplicative, Switch, Range, Unary, Cast, PointerIndirection, AddressOf, Primary, } private static Precedence GetPrecedence(SyntaxKind op) { switch (op) { case SyntaxKind.QueryExpression: return Precedence.Expression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return Precedence.Lambda; case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: case SyntaxKind.CoalesceAssignmentExpression: return Precedence.Assignment; case SyntaxKind.CoalesceExpression: case SyntaxKind.ThrowExpression: return Precedence.Coalescing; case SyntaxKind.LogicalOrExpression: return Precedence.ConditionalOr; case SyntaxKind.LogicalAndExpression: return Precedence.ConditionalAnd; case SyntaxKind.BitwiseOrExpression: return Precedence.LogicalOr; case SyntaxKind.ExclusiveOrExpression: return Precedence.LogicalXor; case SyntaxKind.BitwiseAndExpression: return Precedence.LogicalAnd; case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: return Precedence.Equality; case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.IsPatternExpression: return Precedence.Relational; case SyntaxKind.SwitchExpression: case SyntaxKind.WithExpression: return Precedence.Switch; case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: return Precedence.Shift; case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: return Precedence.Additive; case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: return Precedence.Multiplicative; case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.BitwiseNotExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.SizeOfExpression: case SyntaxKind.CheckedExpression: case SyntaxKind.UncheckedExpression: case SyntaxKind.MakeRefExpression: case SyntaxKind.RefValueExpression: case SyntaxKind.RefTypeExpression: case SyntaxKind.AwaitExpression: case SyntaxKind.IndexExpression: return Precedence.Unary; case SyntaxKind.CastExpression: return Precedence.Cast; case SyntaxKind.PointerIndirectionExpression: return Precedence.PointerIndirection; case SyntaxKind.AddressOfExpression: return Precedence.AddressOf; case SyntaxKind.RangeExpression: return Precedence.Range; case SyntaxKind.ConditionalExpression: return Precedence.Expression; case SyntaxKind.AliasQualifiedName: case SyntaxKind.AnonymousObjectCreationExpression: case SyntaxKind.ArgListExpression: case SyntaxKind.ArrayCreationExpression: case SyntaxKind.BaseExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.ConditionalAccessExpression: case SyntaxKind.DeclarationExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.DefaultLiteralExpression: case SyntaxKind.ElementAccessExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.GenericName: case SyntaxKind.IdentifierName: case SyntaxKind.ImplicitArrayCreationExpression: case SyntaxKind.ImplicitStackAllocArrayCreationExpression: case SyntaxKind.ImplicitObjectCreationExpression: case SyntaxKind.InterpolatedStringExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.PointerMemberAccessExpression: case SyntaxKind.PostDecrementExpression: case SyntaxKind.PostIncrementExpression: case SyntaxKind.PredefinedType: case SyntaxKind.RefExpression: case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.SuppressNullableWarningExpression: case SyntaxKind.ThisExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.TupleExpression: return Precedence.Primary; default: throw ExceptionUtilities.UnexpectedValue(op); } } private static bool IsExpectedPrefixUnaryOperator(SyntaxKind kind) { return SyntaxFacts.IsPrefixUnaryExpression(kind) && kind != SyntaxKind.RefKeyword && kind != SyntaxKind.OutKeyword; } private static bool IsExpectedBinaryOperator(SyntaxKind kind) { return SyntaxFacts.IsBinaryExpression(kind); } private static bool IsExpectedAssignmentOperator(SyntaxKind kind) { return SyntaxFacts.IsAssignmentExpressionOperatorToken(kind); } private bool IsPossibleAwaitExpressionStatement() { return (this.IsScript || this.IsInAsync) && this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword; } private bool IsAwaitExpression() { if (this.CurrentToken.ContextualKind == SyntaxKind.AwaitKeyword) { if (this.IsInAsync) { // If we see an await in an async function, parse it as an unop. return true; } // If we see an await followed by a token that cannot follow an identifier, parse await as a unop. // BindAwait() catches the cases where await successfully parses as a unop but is not in an async // function, and reports an appropriate ERR_BadAwaitWithoutAsync* error. var next = PeekToken(1); switch (next.Kind) { case SyntaxKind.IdentifierToken: return next.ContextualKind != SyntaxKind.WithKeyword; // Keywords case SyntaxKind.NewKeyword: case SyntaxKind.ThisKeyword: case SyntaxKind.BaseKeyword: case SyntaxKind.DelegateKeyword: case SyntaxKind.TypeOfKeyword: case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: case SyntaxKind.DefaultKeyword: // Literals case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.StringLiteralToken: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringToken: case SyntaxKind.NumericLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.CharacterLiteralToken: return true; } } return false; } /// <summary> /// Parse a subexpression of the enclosing operator of the given precedence. /// </summary> private ExpressionSyntax ParseSubExpression(Precedence precedence) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); var result = ParseSubExpressionCore(precedence); #if DEBUG // Ensure every expression kind is handled in GetPrecedence _ = GetPrecedence(result.Kind); #endif _recursionDepth--; return result; } private ExpressionSyntax ParseSubExpressionCore(Precedence precedence) { ExpressionSyntax leftOperand; Precedence newPrecedence = 0; // all of these are tokens that start statements and are invalid // to start a expression with. if we see one, then we must have // something like: // // return // if (... // parse out a missing name node for the expression, and keep on going var tk = this.CurrentToken.Kind; if (IsInvalidSubExpression(tk)) { return this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); } // Parse a left operand -- possibly preceded by a unary operator. if (IsExpectedPrefixUnaryOperator(tk)) { var opKind = SyntaxFacts.GetPrefixUnaryExpression(tk); newPrecedence = GetPrecedence(opKind); var opToken = this.EatToken(); var operand = this.ParseSubExpression(newPrecedence); leftOperand = _syntaxFactory.PrefixUnaryExpression(opKind, opToken, operand); } else if (tk == SyntaxKind.DotDotToken) { // Operator ".." here can either be a prefix unary operator or a stand alone empty range: var opToken = this.EatToken(); newPrecedence = GetPrecedence(SyntaxKind.RangeExpression); ExpressionSyntax rightOperand; if (CanStartExpression()) { rightOperand = this.ParseSubExpression(newPrecedence); } else { rightOperand = null; } leftOperand = _syntaxFactory.RangeExpression(leftOperand: null, opToken, rightOperand); } else if (IsAwaitExpression()) { newPrecedence = GetPrecedence(SyntaxKind.AwaitExpression); var awaitToken = this.EatContextualToken(SyntaxKind.AwaitKeyword); awaitToken = CheckFeatureAvailability(awaitToken, MessageID.IDS_FeatureAsync); var operand = this.ParseSubExpression(newPrecedence); leftOperand = _syntaxFactory.AwaitExpression(awaitToken, operand); } else if (this.IsQueryExpression(mayBeVariableDeclaration: false, mayBeMemberDeclaration: false)) { leftOperand = this.ParseQueryExpression(precedence); } else if (this.CurrentToken.ContextualKind == SyntaxKind.FromKeyword && IsInQuery) { // If this "from" token wasn't the start of a query then it's not really an expression. // Consume it so that we don't try to parse it again as the next argument in an // argument list. SyntaxToken skipped = this.EatToken(); // consume but skip "from" skipped = this.AddError(skipped, ErrorCode.ERR_InvalidExprTerm, this.CurrentToken.Text); leftOperand = AddTrailingSkippedSyntax(this.CreateMissingIdentifierName(), skipped); } else if (tk == SyntaxKind.ThrowKeyword) { var result = ParseThrowExpression(); // we parse a throw expression even at the wrong precedence for better recovery return (precedence <= Precedence.Coalescing) ? result : this.AddError(result, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); } else if (this.IsPossibleDeconstructionLeft(precedence)) { leftOperand = ParseDeclarationExpression(ParseTypeMode.Normal, MessageID.IDS_FeatureTuples); } else { // Not a unary operator - get a primary expression. leftOperand = this.ParseTerm(precedence); } return ParseExpressionContinued(leftOperand, precedence); } private ExpressionSyntax ParseExpressionContinued(ExpressionSyntax leftOperand, Precedence precedence) { while (true) { // We either have a binary or assignment operator here, or we're finished. var tk = this.CurrentToken.ContextualKind; bool isAssignmentOperator = false; SyntaxKind opKind; if (IsExpectedBinaryOperator(tk)) { opKind = SyntaxFacts.GetBinaryExpression(tk); } else if (IsExpectedAssignmentOperator(tk)) { opKind = SyntaxFacts.GetAssignmentExpression(tk); isAssignmentOperator = true; } else if (tk == SyntaxKind.DotDotToken) { opKind = SyntaxKind.RangeExpression; } else if (tk == SyntaxKind.SwitchKeyword && this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken) { opKind = SyntaxKind.SwitchExpression; } else if (tk == SyntaxKind.WithKeyword && this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken) { opKind = SyntaxKind.WithExpression; } else { break; } var newPrecedence = GetPrecedence(opKind); // check for >> or >>= bool doubleOp = false; if (tk == SyntaxKind.GreaterThanToken && (this.PeekToken(1).Kind == SyntaxKind.GreaterThanToken || this.PeekToken(1).Kind == SyntaxKind.GreaterThanEqualsToken)) { // check to see if they really are adjacent if (this.CurrentToken.GetTrailingTriviaWidth() == 0 && this.PeekToken(1).GetLeadingTriviaWidth() == 0) { if (this.PeekToken(1).Kind == SyntaxKind.GreaterThanToken) { opKind = SyntaxFacts.GetBinaryExpression(SyntaxKind.GreaterThanGreaterThanToken); } else { opKind = SyntaxFacts.GetAssignmentExpression(SyntaxKind.GreaterThanGreaterThanEqualsToken); isAssignmentOperator = true; } newPrecedence = GetPrecedence(opKind); doubleOp = true; } } // Check the precedence to see if we should "take" this operator if (newPrecedence < precedence) { break; } // Same precedence, but not right-associative -- deal with this "later" if ((newPrecedence == precedence) && !IsRightAssociative(opKind)) { break; } // We'll "take" this operator, as precedence is tentatively OK. var opToken = this.EatContextualToken(tk); var leftPrecedence = GetPrecedence(leftOperand.Kind); if (newPrecedence > leftPrecedence) { // Normally, a left operand with a looser precedence will consume all right operands that // have a tighter precedence. For example, in the expression `a + b * c`, the `* c` part // will be consumed as part of the right operand of the addition. However, there are a // few circumstances in which a tighter precedence is not consumed: that occurs when the // left hand operator does not have an expression as its right operand. This occurs for // the is-type operator and the is-pattern operator. Source text such as // `a is {} + b` should produce a syntax error, as parsing the `+` with an `is` // expression as its left operand would be a precedence inversion. Similarly, it occurs // with an anonymous method expression or a lambda expression with a block body. No // further parsing will find a way to fix things up, so we accept the operator but issue // a diagnostic. ErrorCode errorCode = leftOperand.Kind == SyntaxKind.IsPatternExpression ? ErrorCode.ERR_UnexpectedToken : ErrorCode.WRN_PrecedenceInversion; opToken = this.AddError(opToken, errorCode, opToken.Text); } if (doubleOp) { // combine tokens into a single token var opToken2 = this.EatToken(); var kind = opToken2.Kind == SyntaxKind.GreaterThanToken ? SyntaxKind.GreaterThanGreaterThanToken : SyntaxKind.GreaterThanGreaterThanEqualsToken; opToken = SyntaxFactory.Token(opToken.GetLeadingTrivia(), kind, opToken2.GetTrailingTrivia()); } if (opKind == SyntaxKind.AsExpression) { var type = this.ParseType(ParseTypeMode.AsExpression); leftOperand = _syntaxFactory.BinaryExpression(opKind, leftOperand, opToken, type); } else if (opKind == SyntaxKind.IsExpression) { leftOperand = ParseIsExpression(leftOperand, opToken); } else if (isAssignmentOperator) { ExpressionSyntax rhs = opKind == SyntaxKind.SimpleAssignmentExpression && CurrentToken.Kind == SyntaxKind.RefKeyword ? rhs = CheckFeatureAvailability(ParsePossibleRefExpression(), MessageID.IDS_FeatureRefReassignment) : rhs = this.ParseSubExpression(newPrecedence); if (opKind == SyntaxKind.CoalesceAssignmentExpression) { opToken = CheckFeatureAvailability(opToken, MessageID.IDS_FeatureCoalesceAssignmentExpression); } leftOperand = _syntaxFactory.AssignmentExpression(opKind, leftOperand, opToken, rhs); } else if (opKind == SyntaxKind.SwitchExpression) { leftOperand = ParseSwitchExpression(leftOperand, opToken); } else if (opKind == SyntaxKind.WithExpression) { leftOperand = ParseWithExpression(leftOperand, opToken); } else if (tk == SyntaxKind.DotDotToken) { // Operator ".." here can either be a binary or a postfix unary operator: Debug.Assert(opKind == SyntaxKind.RangeExpression); ExpressionSyntax rightOperand; if (CanStartExpression()) { newPrecedence = GetPrecedence(opKind); rightOperand = this.ParseSubExpression(newPrecedence); } else { rightOperand = null; } leftOperand = _syntaxFactory.RangeExpression(leftOperand, opToken, rightOperand); } else { Debug.Assert(IsExpectedBinaryOperator(tk)); leftOperand = _syntaxFactory.BinaryExpression(opKind, leftOperand, opToken, this.ParseSubExpression(newPrecedence)); } } // From the language spec: // // conditional-expression: // null-coalescing-expression // null-coalescing-expression ? expression : expression // // Only take the conditional if we're at or below its precedence. if (CurrentToken.Kind == SyntaxKind.QuestionToken && precedence <= Precedence.Conditional) { var questionToken = this.EatToken(); var colonLeft = this.ParsePossibleRefExpression(); if (this.CurrentToken.Kind == SyntaxKind.EndOfFileToken && this.lexer.InterpolationFollowedByColon) { // We have an interpolated string with an interpolation that contains a conditional expression. // Unfortunately, the precedence demands that the colon is considered to signal the start of the // format string. Without this code, the compiler would complain about a missing colon, and point // to the colon that is present, which would be confusing. We aim to give a better error message. var colon = SyntaxFactory.MissingToken(SyntaxKind.ColonToken); var colonRight = _syntaxFactory.IdentifierName(SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); leftOperand = _syntaxFactory.ConditionalExpression(leftOperand, questionToken, colonLeft, colon, colonRight); leftOperand = this.AddError(leftOperand, ErrorCode.ERR_ConditionalInInterpolation); } else { var colon = this.EatToken(SyntaxKind.ColonToken); var colonRight = this.ParsePossibleRefExpression(); leftOperand = _syntaxFactory.ConditionalExpression(leftOperand, questionToken, colonLeft, colon, colonRight); } } return leftOperand; } private ExpressionSyntax ParseDeclarationExpression(ParseTypeMode mode, MessageID feature) { TypeSyntax type = this.ParseType(mode); var designation = ParseDesignation(forPattern: false); if (feature != MessageID.None) { designation = CheckFeatureAvailability(designation, feature); } return _syntaxFactory.DeclarationExpression(type, designation); } private ExpressionSyntax ParseThrowExpression() { var throwToken = this.EatToken(SyntaxKind.ThrowKeyword); var thrown = this.ParseSubExpression(Precedence.Coalescing); var result = _syntaxFactory.ThrowExpression(throwToken, thrown); return CheckFeatureAvailability(result, MessageID.IDS_FeatureThrowExpression); } private ExpressionSyntax ParseIsExpression(ExpressionSyntax leftOperand, SyntaxToken opToken) { var node = this.ParseTypeOrPatternForIsOperator(); switch (node) { case PatternSyntax pattern: var result = _syntaxFactory.IsPatternExpression(leftOperand, opToken, pattern); return CheckFeatureAvailability(result, MessageID.IDS_FeaturePatternMatching); case TypeSyntax type: return _syntaxFactory.BinaryExpression(SyntaxKind.IsExpression, leftOperand, opToken, type); default: throw ExceptionUtilities.UnexpectedValue(node); } } private ExpressionSyntax ParseTerm(Precedence precedence) => this.ParsePostFixExpression(ParseTermWithoutPostfix(precedence)); private ExpressionSyntax ParseTermWithoutPostfix(Precedence precedence) { var tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.TypeOfKeyword: return this.ParseTypeOfExpression(); case SyntaxKind.DefaultKeyword: return this.ParseDefaultExpression(); case SyntaxKind.SizeOfKeyword: return this.ParseSizeOfExpression(); case SyntaxKind.MakeRefKeyword: return this.ParseMakeRefExpression(); case SyntaxKind.RefTypeKeyword: return this.ParseRefTypeExpression(); case SyntaxKind.CheckedKeyword: case SyntaxKind.UncheckedKeyword: return this.ParseCheckedOrUncheckedExpression(); case SyntaxKind.RefValueKeyword: return this.ParseRefValueExpression(); case SyntaxKind.ColonColonToken: // misplaced :: // Calling ParseAliasQualifiedName will cause us to create a missing identifier node that then // properly consumes the :: and the reset of the alias name afterwards. return this.ParseAliasQualifiedName(NameOptions.InExpression); case SyntaxKind.EqualsGreaterThanToken: return this.ParseLambdaExpression(); case SyntaxKind.StaticKeyword: if (this.IsPossibleAnonymousMethodExpression()) { return this.ParseAnonymousMethodExpression(); } else if (this.IsPossibleLambdaExpression(precedence)) { return this.ParseLambdaExpression(); } else { return this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, this.CurrentToken.Text); } case SyntaxKind.IdentifierToken: if (this.IsTrueIdentifier()) { if (this.IsPossibleAnonymousMethodExpression()) { return this.ParseAnonymousMethodExpression(); } else if (this.IsPossibleLambdaExpression(precedence) && this.TryParseLambdaExpression() is { } lambda) { return lambda; } else if (this.IsPossibleDeconstructionLeft(precedence)) { return ParseDeclarationExpression(ParseTypeMode.Normal, MessageID.IDS_FeatureTuples); } else { return this.ParseAliasQualifiedName(NameOptions.InExpression); } } else { return this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_InvalidExprTerm, this.CurrentToken.Text); } case SyntaxKind.OpenBracketToken: if (!this.IsPossibleLambdaExpression(precedence)) { goto default; } return this.ParseLambdaExpression(); case SyntaxKind.ThisKeyword: return _syntaxFactory.ThisExpression(this.EatToken()); case SyntaxKind.BaseKeyword: return ParseBaseExpression(); case SyntaxKind.ArgListKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.NullKeyword: case SyntaxKind.NumericLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.CharacterLiteralToken: return _syntaxFactory.LiteralExpression(SyntaxFacts.GetLiteralExpression(tk), this.EatToken()); case SyntaxKind.InterpolatedStringStartToken: throw new NotImplementedException(); // this should not occur because these tokens are produced and parsed immediately case SyntaxKind.InterpolatedStringToken: return this.ParseInterpolatedStringToken(); case SyntaxKind.OpenParenToken: if (IsPossibleLambdaExpression(precedence)) { if (this.TryParseLambdaExpression() is { } lambda) { return lambda; } } return this.ParseCastOrParenExpressionOrTuple(); case SyntaxKind.NewKeyword: return this.ParseNewExpression(); case SyntaxKind.StackAllocKeyword: return this.ParseStackAllocExpression(); case SyntaxKind.DelegateKeyword: // check for lambda expression with explicit function pointer return type if (this.IsPossibleLambdaExpression(precedence)) { return this.ParseLambdaExpression(); } return this.ParseAnonymousMethodExpression(); case SyntaxKind.RefKeyword: // check for lambda expression with explicit ref return type: `ref int () => { ... }` if (this.IsPossibleLambdaExpression(precedence)) { return this.ParseLambdaExpression(); } // ref is not expected to appear in this position. return this.AddError(ParsePossibleRefExpression(), ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); default: if (IsPredefinedType(tk)) { if (this.IsPossibleLambdaExpression(precedence)) { return this.ParseLambdaExpression(); } // check for intrinsic type followed by '.' var expr = _syntaxFactory.PredefinedType(this.EatToken()); if (this.CurrentToken.Kind != SyntaxKind.DotToken || tk == SyntaxKind.VoidKeyword) { expr = this.AddError(expr, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); } return expr; } else { var expr = this.CreateMissingIdentifierName(); if (tk == SyntaxKind.EndOfFileToken) { expr = this.AddError(expr, ErrorCode.ERR_ExpressionExpected); } else { expr = this.AddError(expr, ErrorCode.ERR_InvalidExprTerm, SyntaxFacts.GetText(tk)); } return expr; } } } private ExpressionSyntax ParseBaseExpression() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.BaseKeyword); return _syntaxFactory.BaseExpression(this.EatToken()); } /// <summary> /// Returns true if... /// 1. The precedence is less than or equal to Assignment, and /// 2. The current token is the identifier var or a predefined type, and /// 3. it is followed by (, and /// 4. that ( begins a valid parenthesized designation, and /// 5. the token following that designation is = /// </summary> private bool IsPossibleDeconstructionLeft(Precedence precedence) { if (precedence > Precedence.Assignment || !(this.CurrentToken.IsIdentifierVar() || IsPredefinedType(this.CurrentToken.Kind))) { return false; } var resetPoint = this.GetResetPoint(); try { this.EatToken(); // `var` return this.CurrentToken.Kind == SyntaxKind.OpenParenToken && ScanDesignator() && this.CurrentToken.Kind == SyntaxKind.EqualsToken; } finally { // Restore current token index this.Reset(ref resetPoint); this.Release(ref resetPoint); } } private bool ScanDesignator() { switch (this.CurrentToken.Kind) { case SyntaxKind.IdentifierToken: if (!IsTrueIdentifier()) { goto default; } this.EatToken(); // eat the identifier return true; case SyntaxKind.OpenParenToken: while (true) { this.EatToken(); // eat the open paren or comma if (!ScanDesignator()) { return false; } switch (this.CurrentToken.Kind) { case SyntaxKind.CommaToken: continue; case SyntaxKind.CloseParenToken: this.EatToken(); // eat the close paren return true; default: return false; } } default: return false; } } private bool IsPossibleAnonymousMethodExpression() { // Skip past any static/async keywords. var tokenIndex = 0; while (this.PeekToken(tokenIndex).Kind == SyntaxKind.StaticKeyword || this.PeekToken(tokenIndex).ContextualKind == SyntaxKind.AsyncKeyword) { tokenIndex++; } return this.PeekToken(tokenIndex).Kind == SyntaxKind.DelegateKeyword && this.PeekToken(tokenIndex + 1).Kind != SyntaxKind.AsteriskToken; } private ExpressionSyntax ParsePostFixExpression(ExpressionSyntax expr) { Debug.Assert(expr != null); while (true) { SyntaxKind tk = this.CurrentToken.Kind; switch (tk) { case SyntaxKind.OpenParenToken: expr = _syntaxFactory.InvocationExpression(expr, this.ParseParenthesizedArgumentList()); break; case SyntaxKind.OpenBracketToken: expr = _syntaxFactory.ElementAccessExpression(expr, this.ParseBracketedArgumentList()); break; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: expr = _syntaxFactory.PostfixUnaryExpression(SyntaxFacts.GetPostfixUnaryExpression(tk), expr, this.EatToken()); break; case SyntaxKind.ColonColonToken: if (this.PeekToken(1).Kind == SyntaxKind.IdentifierToken) { // replace :: with missing dot and annotate with skipped text "::" and error var ccToken = this.EatToken(); ccToken = this.AddError(ccToken, ErrorCode.ERR_UnexpectedAliasedName); var dotToken = this.ConvertToMissingWithTrailingTrivia(ccToken, SyntaxKind.DotToken); expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, dotToken, this.ParseSimpleName(NameOptions.InExpression)); } else { // just some random trailing :: ? expr = AddTrailingSkippedSyntax(expr, this.EatTokenWithPrejudice(SyntaxKind.DotToken)); } break; case SyntaxKind.MinusGreaterThanToken: expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.PointerMemberAccessExpression, expr, this.EatToken(), this.ParseSimpleName(NameOptions.InExpression)); break; case SyntaxKind.DotToken: // if we have the error situation: // // expr. // X Y // // Then we don't want to parse this out as "Expr.X" // // It's far more likely the member access expression is simply incomplete and // there is a new declaration on the next line. if (this.CurrentToken.TrailingTrivia.Any((int)SyntaxKind.EndOfLineTrivia) && this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && this.PeekToken(2).ContextualKind == SyntaxKind.IdentifierToken) { expr = _syntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, expr, this.EatToken(), this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_IdentifierExpected)); return expr; } expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, this.EatToken(), this.ParseSimpleName(NameOptions.InExpression)); break; case SyntaxKind.QuestionToken: if (CanStartConsequenceExpression(this.PeekToken(1).Kind)) { var qToken = this.EatToken(); var consequence = ParseConsequenceSyntax(); expr = _syntaxFactory.ConditionalAccessExpression(expr, qToken, consequence); expr = CheckFeatureAvailability(expr, MessageID.IDS_FeatureNullPropagatingOperator); break; } goto default; case SyntaxKind.ExclamationToken: expr = _syntaxFactory.PostfixUnaryExpression(SyntaxFacts.GetPostfixUnaryExpression(tk), expr, this.EatToken()); expr = CheckFeatureAvailability(expr, MessageID.IDS_FeatureNullableReferenceTypes); break; default: return expr; } } } private static bool CanStartConsequenceExpression(SyntaxKind kind) { return kind == SyntaxKind.DotToken || kind == SyntaxKind.OpenBracketToken; } internal ExpressionSyntax ParseConsequenceSyntax() { SyntaxKind tk = this.CurrentToken.Kind; ExpressionSyntax expr = null; switch (tk) { case SyntaxKind.DotToken: expr = _syntaxFactory.MemberBindingExpression(this.EatToken(), this.ParseSimpleName(NameOptions.InExpression)); break; case SyntaxKind.OpenBracketToken: expr = _syntaxFactory.ElementBindingExpression(this.ParseBracketedArgumentList()); break; } Debug.Assert(expr != null); while (true) { tk = this.CurrentToken.Kind; // Nullable suppression operators should only be consumed by a conditional access // if there are further conditional operations performed after the suppression if (isOptionalExclamationsFollowedByConditionalOperation()) { while (tk == SyntaxKind.ExclamationToken) { expr = _syntaxFactory.PostfixUnaryExpression(SyntaxKind.SuppressNullableWarningExpression, expr, EatToken()); expr = CheckFeatureAvailability(expr, MessageID.IDS_FeatureNullableReferenceTypes); tk = this.CurrentToken.Kind; } } switch (tk) { case SyntaxKind.OpenParenToken: expr = _syntaxFactory.InvocationExpression(expr, this.ParseParenthesizedArgumentList()); break; case SyntaxKind.OpenBracketToken: expr = _syntaxFactory.ElementAccessExpression(expr, this.ParseBracketedArgumentList()); break; case SyntaxKind.DotToken: expr = _syntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, expr, this.EatToken(), this.ParseSimpleName(NameOptions.InExpression)); break; case SyntaxKind.QuestionToken: if (CanStartConsequenceExpression(this.PeekToken(1).Kind)) { var qToken = this.EatToken(); var consequence = ParseConsequenceSyntax(); expr = _syntaxFactory.ConditionalAccessExpression(expr, qToken, consequence); } return expr; default: return expr; } } bool isOptionalExclamationsFollowedByConditionalOperation() { var tk = this.CurrentToken.Kind; for (int i = 1; tk == SyntaxKind.ExclamationToken; i++) { tk = this.PeekToken(i).Kind; } return tk is SyntaxKind.OpenParenToken or SyntaxKind.OpenBracketToken or SyntaxKind.DotToken or SyntaxKind.QuestionToken; } } internal ArgumentListSyntax ParseParenthesizedArgumentList() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.ArgumentList) { return (ArgumentListSyntax)this.EatNode(); } ParseArgumentList( openToken: out SyntaxToken openToken, arguments: out SeparatedSyntaxList<ArgumentSyntax> arguments, closeToken: out SyntaxToken closeToken, openKind: SyntaxKind.OpenParenToken, closeKind: SyntaxKind.CloseParenToken); return _syntaxFactory.ArgumentList(openToken, arguments, closeToken); } internal BracketedArgumentListSyntax ParseBracketedArgumentList() { if (this.IsIncrementalAndFactoryContextMatches && this.CurrentNodeKind == SyntaxKind.BracketedArgumentList) { return (BracketedArgumentListSyntax)this.EatNode(); } ParseArgumentList( openToken: out SyntaxToken openToken, arguments: out SeparatedSyntaxList<ArgumentSyntax> arguments, closeToken: out SyntaxToken closeToken, openKind: SyntaxKind.OpenBracketToken, closeKind: SyntaxKind.CloseBracketToken); return _syntaxFactory.BracketedArgumentList(openToken, arguments, closeToken); } private void ParseArgumentList( out SyntaxToken openToken, out SeparatedSyntaxList<ArgumentSyntax> arguments, out SyntaxToken closeToken, SyntaxKind openKind, SyntaxKind closeKind) { Debug.Assert(openKind == SyntaxKind.OpenParenToken || openKind == SyntaxKind.OpenBracketToken); Debug.Assert(closeKind == SyntaxKind.CloseParenToken || closeKind == SyntaxKind.CloseBracketToken); Debug.Assert((openKind == SyntaxKind.OpenParenToken) == (closeKind == SyntaxKind.CloseParenToken)); bool isIndexer = openKind == SyntaxKind.OpenBracketToken; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken || this.CurrentToken.Kind == SyntaxKind.OpenBracketToken) { // convert `[` into `(` or vice versa for error recovery openToken = this.EatTokenAsKind(openKind); } else { openToken = this.EatToken(openKind); } var saveTerm = _termState; _termState |= TerminatorState.IsEndOfArgumentList; SeparatedSyntaxListBuilder<ArgumentSyntax> list = default(SeparatedSyntaxListBuilder<ArgumentSyntax>); try { if (this.CurrentToken.Kind != closeKind && this.CurrentToken.Kind != SyntaxKind.SemicolonToken) { tryAgain: if (list.IsNull) { list = _pool.AllocateSeparated<ArgumentSyntax>(); } if (this.IsPossibleArgumentExpression() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument list.Add(this.ParseArgumentExpression(isIndexer)); // additional arguments var lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.CloseBracketToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleArgumentExpression()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); list.Add(this.ParseArgumentExpression(isIndexer)); continue; } else if (this.SkipBadArgumentListTokens(ref openToken, list, SyntaxKind.CommaToken, closeKind) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadArgumentListTokens(ref openToken, list, SyntaxKind.IdentifierToken, closeKind) == PostSkipAction.Continue) { goto tryAgain; } } else if (isIndexer && this.CurrentToken.Kind == closeKind) { // An indexer always expects at least one value. And so we need to give an error // for the case where we see only "[]". ParseArgumentExpression gives it. if (list.IsNull) { list = _pool.AllocateSeparated<ArgumentSyntax>(); } list.Add(this.ParseArgumentExpression(isIndexer)); } _termState = saveTerm; if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.CloseBracketToken) { // convert `]` into `)` or vice versa for error recovery closeToken = this.EatTokenAsKind(closeKind); } else { closeToken = this.EatToken(closeKind); } arguments = list.ToList(); } finally { if (!list.IsNull) { _pool.Free(list); } } } private PostSkipAction SkipBadArgumentListTokens(ref SyntaxToken open, SeparatedSyntaxListBuilder<ArgumentSyntax> list, SyntaxKind expected, SyntaxKind closeKind) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref open, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleArgumentExpression(), p => p.CurrentToken.Kind == closeKind || p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsTerminator(), expected); } private bool IsEndOfArgumentList() { return this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.CloseBracketToken; } private bool IsPossibleArgumentExpression() { return IsValidArgumentRefKindKeyword(this.CurrentToken.Kind) || this.IsPossibleExpression(); } private static bool IsValidArgumentRefKindKeyword(SyntaxKind kind) { switch (kind) { case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: return true; default: return false; } } private ArgumentSyntax ParseArgumentExpression(bool isIndexer) { NameColonSyntax nameColon = null; if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.ColonToken) { var name = this.ParseIdentifierName(); var colon = this.EatToken(SyntaxKind.ColonToken); nameColon = _syntaxFactory.NameColon(name, colon); nameColon = CheckFeatureAvailability(nameColon, MessageID.IDS_FeatureNamedArgument); } SyntaxToken refKindKeyword = null; if (IsValidArgumentRefKindKeyword(this.CurrentToken.Kind)) { refKindKeyword = this.EatToken(); } ExpressionSyntax expression; if (isIndexer && (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.CurrentToken.Kind == SyntaxKind.CloseBracketToken)) { expression = this.ParseIdentifierName(ErrorCode.ERR_ValueExpected); } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { expression = this.ParseIdentifierName(ErrorCode.ERR_MissingArgument); } else { if (refKindKeyword?.Kind == SyntaxKind.InKeyword) { refKindKeyword = this.CheckFeatureAvailability(refKindKeyword, MessageID.IDS_FeatureReadOnlyReferences); } // According to Language Specification, section 7.6.7 Element access // The argument-list of an element-access is not allowed to contain ref or out arguments. // However, we actually do support ref indexing of indexed properties in COM interop // scenarios, and when indexing an object of static type "dynamic". So we enforce // that the ref/out of the argument must match the parameter when binding the argument list. expression = (refKindKeyword?.Kind == SyntaxKind.OutKeyword) ? ParseExpressionOrDeclaration(ParseTypeMode.Normal, feature: MessageID.IDS_FeatureOutVar, permitTupleDesignation: false) : ParseSubExpression(Precedence.Expression); } return _syntaxFactory.Argument(nameColon, refKindKeyword, expression); } private TypeOfExpressionSyntax ParseTypeOfExpression() { var keyword = this.EatToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var type = this.ParseTypeOrVoid(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.TypeOfExpression(keyword, openParen, type, closeParen); } private ExpressionSyntax ParseDefaultExpression() { var keyword = this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var openParen = this.EatToken(SyntaxKind.OpenParenToken); var type = this.ParseType(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); keyword = CheckFeatureAvailability(keyword, MessageID.IDS_FeatureDefault); return _syntaxFactory.DefaultExpression(keyword, openParen, type, closeParen); } else { keyword = CheckFeatureAvailability(keyword, MessageID.IDS_FeatureDefaultLiteral); return _syntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression, keyword); } } private SizeOfExpressionSyntax ParseSizeOfExpression() { var keyword = this.EatToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var type = this.ParseType(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.SizeOfExpression(keyword, openParen, type, closeParen); } private MakeRefExpressionSyntax ParseMakeRefExpression() { var keyword = this.EatToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expr = this.ParseSubExpression(Precedence.Expression); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.MakeRefExpression(keyword, openParen, expr, closeParen); } private RefTypeExpressionSyntax ParseRefTypeExpression() { var keyword = this.EatToken(); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expr = this.ParseSubExpression(Precedence.Expression); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.RefTypeExpression(keyword, openParen, expr, closeParen); } private CheckedExpressionSyntax ParseCheckedOrUncheckedExpression() { var checkedOrUnchecked = this.EatToken(); Debug.Assert(checkedOrUnchecked.Kind == SyntaxKind.CheckedKeyword || checkedOrUnchecked.Kind == SyntaxKind.UncheckedKeyword); var kind = (checkedOrUnchecked.Kind == SyntaxKind.CheckedKeyword) ? SyntaxKind.CheckedExpression : SyntaxKind.UncheckedExpression; var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expr = this.ParseSubExpression(Precedence.Expression); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.CheckedExpression(kind, checkedOrUnchecked, openParen, expr, closeParen); } private RefValueExpressionSyntax ParseRefValueExpression() { var @refvalue = this.EatToken(SyntaxKind.RefValueKeyword); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expr = this.ParseSubExpression(Precedence.Expression); var comma = this.EatToken(SyntaxKind.CommaToken); var type = this.ParseType(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.RefValueExpression(@refvalue, openParen, expr, comma, type, closeParen); } private bool ScanParenthesizedLambda(Precedence precedence) { return ScanParenthesizedImplicitlyTypedLambda(precedence) || ScanExplicitlyTypedLambda(precedence); } private bool ScanParenthesizedImplicitlyTypedLambda(Precedence precedence) { Debug.Assert(CurrentToken.Kind == SyntaxKind.OpenParenToken); if (!(precedence <= Precedence.Lambda)) { return false; } // case 1: ( x , if (this.PeekToken(1).Kind == SyntaxKind.IdentifierToken && (!this.IsInQuery || !IsTokenQueryContextualKeyword(this.PeekToken(1))) && this.PeekToken(2).Kind == SyntaxKind.CommaToken) { // Make sure it really looks like a lambda, not just a tuple int curTk = 3; while (true) { var tk = this.PeekToken(curTk++); // skip identifiers commas and predefined types in any combination for error recovery if (tk.Kind != SyntaxKind.IdentifierToken && !SyntaxFacts.IsPredefinedType(tk.Kind) && tk.Kind != SyntaxKind.CommaToken && (this.IsInQuery || !IsTokenQueryContextualKeyword(tk))) { break; }; } // ) => return this.PeekToken(curTk - 1).Kind == SyntaxKind.CloseParenToken && this.PeekToken(curTk).Kind == SyntaxKind.EqualsGreaterThanToken; } // case 2: ( x ) => if (IsTrueIdentifier(this.PeekToken(1)) && this.PeekToken(2).Kind == SyntaxKind.CloseParenToken && this.PeekToken(3).Kind == SyntaxKind.EqualsGreaterThanToken) { return true; } // case 3: ( ) => if (this.PeekToken(1).Kind == SyntaxKind.CloseParenToken && this.PeekToken(2).Kind == SyntaxKind.EqualsGreaterThanToken) { return true; } // case 4: ( params // This case is interesting in that it is not legal; this error could be caught at parse time but we would rather // recover from the error and let the semantic analyzer deal with it. if (this.PeekToken(1).Kind == SyntaxKind.ParamsKeyword) { return true; } return false; } private bool ScanExplicitlyTypedLambda(Precedence precedence) { Debug.Assert(CurrentToken.Kind == SyntaxKind.OpenParenToken); if (!(precedence <= Precedence.Lambda)) { return false; } var resetPoint = this.GetResetPoint(); try { // Do we have the following, where the attributes, modifier, and type are // optional? If so then parse it as a lambda. // (attributes modifier T x [, ...]) => // // It's not sufficient to assume this is a lambda expression if we see a // modifier such as `(ref x,` because the caller of this method may have // scanned past a preceding identifier, and `F (ref x,` might be a call to // method F rather than a lambda expression with return type F. // Instead, we need to scan to `=>`. while (true) { // Advance past the open paren or comma. this.EatToken(); _ = ParseAttributeDeclarations(); // Eat 'out', 'ref', and 'in'. Even though not allowed in a lambda, // we treat `params` similarly for better error recovery. switch (this.CurrentToken.Kind) { case SyntaxKind.RefKeyword: this.EatToken(); if (this.CurrentToken.Kind == SyntaxKind.ReadOnlyKeyword) { this.EatToken(); } break; case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: case SyntaxKind.ParamsKeyword: this.EatToken(); break; } // NOTE: advances CurrentToken if (this.ScanType() == ScanTypeFlags.NotType) { return false; } if (this.IsTrueIdentifier()) { // eat the identifier this.EatToken(); } switch (this.CurrentToken.Kind) { case SyntaxKind.CommaToken: continue; case SyntaxKind.CloseParenToken: return this.PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken; default: return false; } } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } private ExpressionSyntax ParseCastOrParenExpressionOrTuple() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.OpenParenToken); var resetPoint = this.GetResetPoint(); try { // We have a decision to make -- is this a cast, or is it a parenthesized // expression? Because look-ahead is cheap with our token stream, we check // to see if this "looks like" a cast (without constructing any parse trees) // to help us make the decision. if (this.ScanCast()) { if (!IsCurrentTokenQueryKeywordInQuery()) { // Looks like a cast, so parse it as one. this.Reset(ref resetPoint); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var type = this.ParseType(); var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var expr = this.ParseSubExpression(Precedence.Cast); return _syntaxFactory.CastExpression(openParen, type, closeParen, expr); } } // Doesn't look like a cast, so parse this as a parenthesized expression or tuple. { this.Reset(ref resetPoint); var openParen = this.EatToken(SyntaxKind.OpenParenToken); var expression = this.ParseExpressionOrDeclaration(ParseTypeMode.FirstElementOfPossibleTupleLiteral, feature: 0, permitTupleDesignation: true); // ( <expr>, must be a tuple if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { var firstArg = _syntaxFactory.Argument(nameColon: null, refKindKeyword: null, expression: expression); return ParseTupleExpressionTail(openParen, firstArg); } // ( name: if (expression.Kind == SyntaxKind.IdentifierName && this.CurrentToken.Kind == SyntaxKind.ColonToken) { var nameColon = _syntaxFactory.NameColon((IdentifierNameSyntax)expression, EatToken()); expression = this.ParseExpressionOrDeclaration(ParseTypeMode.FirstElementOfPossibleTupleLiteral, feature: 0, permitTupleDesignation: true); var firstArg = _syntaxFactory.Argument(nameColon, refKindKeyword: null, expression: expression); return ParseTupleExpressionTail(openParen, firstArg); } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.ParenthesizedExpression(openParen, expression, closeParen); } } finally { this.Release(ref resetPoint); } } private TupleExpressionSyntax ParseTupleExpressionTail(SyntaxToken openParen, ArgumentSyntax firstArg) { var list = _pool.AllocateSeparated<ArgumentSyntax>(); try { list.Add(firstArg); while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { var comma = this.EatToken(SyntaxKind.CommaToken); list.AddSeparator(comma); ArgumentSyntax arg; var expression = ParseExpressionOrDeclaration(ParseTypeMode.AfterTupleComma, feature: 0, permitTupleDesignation: true); if (expression.Kind == SyntaxKind.IdentifierName && this.CurrentToken.Kind == SyntaxKind.ColonToken) { var nameColon = _syntaxFactory.NameColon((IdentifierNameSyntax)expression, EatToken()); expression = ParseExpressionOrDeclaration(ParseTypeMode.AfterTupleComma, feature: 0, permitTupleDesignation: true); arg = _syntaxFactory.Argument(nameColon, refKindKeyword: null, expression: expression); } else { arg = _syntaxFactory.Argument(nameColon: null, refKindKeyword: null, expression: expression); } list.Add(arg); } if (list.Count < 2) { list.AddSeparator(SyntaxFactory.MissingToken(SyntaxKind.CommaToken)); var missing = this.AddError(this.CreateMissingIdentifierName(), ErrorCode.ERR_TupleTooFewElements); list.Add(_syntaxFactory.Argument(nameColon: null, refKindKeyword: null, expression: missing)); } var closeParen = this.EatToken(SyntaxKind.CloseParenToken); var result = _syntaxFactory.TupleExpression(openParen, list, closeParen); result = CheckFeatureAvailability(result, MessageID.IDS_FeatureTuples); return result; } finally { _pool.Free(list); } } private bool ScanCast(bool forPattern = false) { if (this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { return false; } this.EatToken(); var type = this.ScanType(forPattern: forPattern); if (type == ScanTypeFlags.NotType) { return false; } if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { return false; } this.EatToken(); if (forPattern && this.CurrentToken.Kind == SyntaxKind.IdentifierToken) { // In a pattern, an identifier can follow a cast unless it's a binary pattern token. return !isBinaryPattern(); } switch (type) { // If we have any of the following, we know it must be a cast: // 1) (Goo*)bar; // 2) (Goo?)bar; // 3) "(int)bar" or "(int[])bar" // 4) (G::Goo)bar case ScanTypeFlags.PointerOrMultiplication: case ScanTypeFlags.NullableType: case ScanTypeFlags.MustBeType: case ScanTypeFlags.AliasQualifiedName: // The thing between parens is unambiguously a type. // In a pattern, we need more lookahead to confirm it is a cast and not // a parenthesized type pattern. In this case the tokens that // have both unary and binary operator forms may appear in their unary form // following a cast. return !forPattern || this.CurrentToken.Kind switch { SyntaxKind.PlusToken or SyntaxKind.MinusToken or SyntaxKind.AmpersandToken or SyntaxKind.AsteriskToken or SyntaxKind.DotDotToken => true, var tk => CanFollowCast(tk) }; case ScanTypeFlags.GenericTypeOrMethod: case ScanTypeFlags.GenericTypeOrExpression: case ScanTypeFlags.NonGenericTypeOrExpression: case ScanTypeFlags.TupleType: // check for ambiguous type or expression followed by disambiguating token. i.e. // // "(A)b" is a cast. But "(A)+b" is not a cast. return CanFollowCast(this.CurrentToken.Kind); default: throw ExceptionUtilities.UnexpectedValue(type); } bool isBinaryPattern() { if (!isBinaryPatternKeyword()) { return false; } bool lastTokenIsBinaryOperator = true; EatToken(); while (isBinaryPatternKeyword()) { // If we see a subsequent binary pattern token, it can't be an operator. // Later, it will be parsed as an identifier. lastTokenIsBinaryOperator = !lastTokenIsBinaryOperator; EatToken(); } // In case a combinator token is used as a constant, we explicitly check that a pattern is NOT followed. // Such as `(e is (int)or or >= 0)` versus `(e is (int) or or)` return lastTokenIsBinaryOperator == IsPossibleSubpatternElement(); } bool isBinaryPatternKeyword() { return this.CurrentToken.ContextualKind is SyntaxKind.OrKeyword or SyntaxKind.AndKeyword; } } /// <summary> /// Tokens that match the following are considered a possible lambda expression: /// <code>attribute-list* ('async' | 'static')* type? ('(' | identifier) ...</code> /// For better error recovery 'static =>' is also considered a possible lambda expression. /// </summary> private bool IsPossibleLambdaExpression(Precedence precedence) { if (precedence > Precedence.Lambda) { return false; } var resetPoint = this.GetResetPoint(); try { if (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { _ = ParseAttributeDeclarations(); } bool seenStatic; if (this.CurrentToken.Kind == SyntaxKind.StaticKeyword) { EatToken(); seenStatic = true; } else if (this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword && this.PeekToken(1).Kind == SyntaxKind.StaticKeyword) { EatToken(); EatToken(); seenStatic = true; } else { seenStatic = false; } if (seenStatic) { if (this.CurrentToken.Kind == SyntaxKind.EqualsGreaterThanToken) { // 1. `static =>` // 2. `async static =>` // This is an error case, but we have enough code in front of us to be certain // the user was trying to write a static lambda. return true; } if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { // 1. `static (... // 2. `async static (... return true; } } if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken) { // 1. `a => ...` // 1. `static a => ...` // 2. `async static a => ...` return true; } // Have checked all the static forms. And have checked for the basic `a => a` form. // At this point we have must be on 'async' or an explicit return type for this to still be a lambda. if (this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword && IsAnonymousFunctionAsyncModifier()) { EatToken(); } var nestedResetPoint = this.GetResetPoint(); try { var st = ScanType(); if (st == ScanTypeFlags.NotType || this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { this.Reset(ref nestedResetPoint); } } finally { this.Release(ref nestedResetPoint); } // However, just because we're on `async` doesn't mean we're a lambda. We might have // something lambda-like like: // // async a => ... // or // async (a) => ... // // Or we could have something that isn't a lambda like: // // async (); // 'async <identifier> => ...' looks like an async simple lambda if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken && this.PeekToken(1).Kind == SyntaxKind.EqualsGreaterThanToken) { // async a => ... return true; } // Non-simple async lambda must be of the form 'async (...' if (this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { return false; } // Check whether looks like implicitly or explicitly typed lambda return ScanParenthesizedLambda(precedence); } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } } private static bool CanFollowCast(SyntaxKind kind) { switch (kind) { case SyntaxKind.AsKeyword: case SyntaxKind.IsKeyword: case SyntaxKind.SemicolonToken: case SyntaxKind.CloseParenToken: case SyntaxKind.CloseBracketToken: case SyntaxKind.OpenBraceToken: case SyntaxKind.CloseBraceToken: case SyntaxKind.CommaToken: case SyntaxKind.EqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.QuestionToken: case SyntaxKind.ColonToken: case SyntaxKind.BarBarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.BarToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.LessThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: case SyntaxKind.AsteriskToken: case SyntaxKind.SlashToken: case SyntaxKind.PercentToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.OpenBracketToken: case SyntaxKind.DotToken: case SyntaxKind.MinusGreaterThanToken: case SyntaxKind.QuestionQuestionToken: case SyntaxKind.EndOfFileToken: case SyntaxKind.SwitchKeyword: case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.DotDotToken: return false; default: return true; } } private ExpressionSyntax ParseNewExpression() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NewKeyword); if (this.IsAnonymousType()) { return this.ParseAnonymousTypeExpression(); } else if (this.IsImplicitlyTypedArray()) { return this.ParseImplicitlyTypedArrayCreation(); } else { // assume object creation as default case return this.ParseArrayOrObjectCreationExpression(); } } private bool IsAnonymousType() { return this.CurrentToken.Kind == SyntaxKind.NewKeyword && this.PeekToken(1).Kind == SyntaxKind.OpenBraceToken; } private AnonymousObjectCreationExpressionSyntax ParseAnonymousTypeExpression() { Debug.Assert(IsAnonymousType()); var @new = this.EatToken(SyntaxKind.NewKeyword); @new = CheckFeatureAvailability(@new, MessageID.IDS_FeatureAnonymousTypes); Debug.Assert(this.CurrentToken.Kind == SyntaxKind.OpenBraceToken); var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var expressions = _pool.AllocateSeparated<AnonymousObjectMemberDeclaratorSyntax>(); this.ParseAnonymousTypeMemberInitializers(ref openBrace, ref expressions); var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); var result = _syntaxFactory.AnonymousObjectCreationExpression(@new, openBrace, expressions, closeBrace); _pool.Free(expressions); return result; } private void ParseAnonymousTypeMemberInitializers(ref SyntaxToken openBrace, ref SeparatedSyntaxListBuilder<AnonymousObjectMemberDeclaratorSyntax> list) { if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsPossibleExpression() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument list.Add(this.ParseAnonymousTypeMemberInitializer()); // additional arguments int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleExpression()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); // check for exit case after legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (!this.IsPossibleExpression()) { goto tryAgain; } list.Add(this.ParseAnonymousTypeMemberInitializer()); continue; } else if (this.SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } } private AnonymousObjectMemberDeclaratorSyntax ParseAnonymousTypeMemberInitializer() { var nameEquals = this.IsNamedAssignment() ? ParseNameEquals() : null; var expression = this.ParseExpressionCore(); return _syntaxFactory.AnonymousObjectMemberDeclarator(nameEquals, expression); } private bool IsInitializerMember() { return this.IsComplexElementInitializer() || this.IsNamedAssignment() || this.IsDictionaryInitializer() || this.IsPossibleExpression(); } private bool IsComplexElementInitializer() { return this.CurrentToken.Kind == SyntaxKind.OpenBraceToken; } private bool IsNamedAssignment() { return IsTrueIdentifier() && this.PeekToken(1).Kind == SyntaxKind.EqualsToken; } private bool IsDictionaryInitializer() { return this.CurrentToken.Kind == SyntaxKind.OpenBracketToken; } private ExpressionSyntax ParseArrayOrObjectCreationExpression() { SyntaxToken @new = this.EatToken(SyntaxKind.NewKeyword); TypeSyntax type = null; InitializerExpressionSyntax initializer = null; if (IsImplicitObjectCreation()) { @new = CheckFeatureAvailability(@new, MessageID.IDS_FeatureImplicitObjectCreation); } else { type = this.ParseType(ParseTypeMode.NewExpression); if (type.Kind == SyntaxKind.ArrayType) { // Check for an initializer. if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { initializer = this.ParseArrayInitializer(); } return _syntaxFactory.ArrayCreationExpression(@new, (ArrayTypeSyntax)type, initializer); } } ArgumentListSyntax argumentList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { argumentList = this.ParseParenthesizedArgumentList(); } if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { initializer = this.ParseObjectOrCollectionInitializer(); } // we need one or the other. also, don't bother reporting this if we already complained about the new type. if (argumentList == null && initializer == null) { argumentList = _syntaxFactory.ArgumentList( this.EatToken(SyntaxKind.OpenParenToken, ErrorCode.ERR_BadNewExpr, reportError: type?.ContainsDiagnostics == false), default(SeparatedSyntaxList<ArgumentSyntax>), SyntaxFactory.MissingToken(SyntaxKind.CloseParenToken)); } return type is null ? (ExpressionSyntax)_syntaxFactory.ImplicitObjectCreationExpression(@new, argumentList, initializer) : (ExpressionSyntax)_syntaxFactory.ObjectCreationExpression(@new, type, argumentList, initializer); } private bool IsImplicitObjectCreation() { // The caller is expected to have consumed the new keyword. if (this.CurrentToken.Kind != SyntaxKind.OpenParenToken) { return false; } var point = this.GetResetPoint(); try { this.EatToken(); // open paren ScanTypeFlags scanTypeFlags = ScanTupleType(out _); if (scanTypeFlags != ScanTypeFlags.NotType) { switch (this.CurrentToken.Kind) { case SyntaxKind.QuestionToken: // e.g. `new(a, b)?()` case SyntaxKind.OpenBracketToken: // e.g. `new(a, b)[]` case SyntaxKind.OpenParenToken: // e.g. `new(a, b)()` for better error recovery return false; } } return true; } finally { this.Reset(ref point); this.Release(ref point); } } #nullable enable private ExpressionSyntax ParseWithExpression(ExpressionSyntax receiverExpression, SyntaxToken withKeyword) { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var list = _pool.AllocateSeparated<ExpressionSyntax>(); if (CurrentToken.Kind != SyntaxKind.CloseBraceToken) { bool foundStart = true; // Skip bad starting tokens until we find a valid start, if possible while (!IsPossibleExpression() && CurrentToken.Kind != SyntaxKind.CommaToken) { if (SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.IdentifierToken) == PostSkipAction.Abort) { foundStart = false; break; } } if (foundStart) { // First list.Add(ParseExpressionCore()); // Rest int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (IsPossibleExpression() || CurrentToken.Kind == SyntaxKind.CommaToken) { list.AddSeparator(EatToken(SyntaxKind.CommaToken)); // check for exit case after legal trailing comma if (CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } list.Add(ParseExpressionCore()); } else if (SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); var initializer = _syntaxFactory.InitializerExpression( SyntaxKind.WithInitializerExpression, openBrace, _pool.ToListAndFree(list), closeBrace); withKeyword = CheckFeatureAvailability(withKeyword, MessageID.IDS_FeatureRecords); var result = _syntaxFactory.WithExpression( receiverExpression, withKeyword, initializer); return result; } #nullable disable private InitializerExpressionSyntax ParseObjectOrCollectionInitializer() { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var initializers = _pool.AllocateSeparated<ExpressionSyntax>(); try { bool isObjectInitializer; this.ParseObjectOrCollectionInitializerMembers(ref openBrace, initializers, out isObjectInitializer); Debug.Assert(initializers.Count > 0 || isObjectInitializer); openBrace = CheckFeatureAvailability(openBrace, isObjectInitializer ? MessageID.IDS_FeatureObjectInitializer : MessageID.IDS_FeatureCollectionInitializer); var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); return _syntaxFactory.InitializerExpression( isObjectInitializer ? SyntaxKind.ObjectInitializerExpression : SyntaxKind.CollectionInitializerExpression, openBrace, initializers, closeBrace); } finally { _pool.Free(initializers); } } private void ParseObjectOrCollectionInitializerMembers(ref SyntaxToken startToken, SeparatedSyntaxListBuilder<ExpressionSyntax> list, out bool isObjectInitializer) { // Empty initializer list must be parsed as an object initializer. isObjectInitializer = true; if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsInitializerMember() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // We have at least one initializer expression. // If at least one initializer expression is a named assignment, this is an object initializer. // Otherwise, this is a collection initializer. isObjectInitializer = false; // first argument list.Add(this.ParseObjectOrCollectionInitializerMember(ref isObjectInitializer)); // additional arguments int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsInitializerMember()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); // check for exit case after legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } list.Add(this.ParseObjectOrCollectionInitializerMember(ref isObjectInitializer)); continue; } else if (this.SkipBadInitializerListTokens(ref startToken, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadInitializerListTokens(ref startToken, list, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } // We may have invalid initializer elements. These will be reported during binding. } private ExpressionSyntax ParseObjectOrCollectionInitializerMember(ref bool isObjectInitializer) { if (this.IsComplexElementInitializer()) { return this.ParseComplexElementInitializer(); } else if (IsDictionaryInitializer()) { isObjectInitializer = true; var initializer = this.ParseDictionaryInitializer(); initializer = CheckFeatureAvailability(initializer, MessageID.IDS_FeatureDictionaryInitializer); return initializer; } else if (this.IsNamedAssignment()) { isObjectInitializer = true; return this.ParseObjectInitializerNamedAssignment(); } else { return this.ParseExpressionCore(); } } private PostSkipAction SkipBadInitializerListTokens<T>(ref SyntaxToken startToken, SeparatedSyntaxListBuilder<T> list, SyntaxKind expected) where T : CSharpSyntaxNode { return this.SkipBadSeparatedListTokensWithExpectedKind(ref startToken, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleExpression(), p => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken || p.IsTerminator(), expected); } private ExpressionSyntax ParseObjectInitializerNamedAssignment() { var identifier = this.ParseIdentifierName(); var equal = this.EatToken(SyntaxKind.EqualsToken); ExpressionSyntax expression; if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { expression = this.ParseObjectOrCollectionInitializer(); } else { expression = this.ParseExpressionCore(); } return _syntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, identifier, equal, expression); } private ExpressionSyntax ParseDictionaryInitializer() { var arguments = this.ParseBracketedArgumentList(); var equal = this.EatToken(SyntaxKind.EqualsToken); var expression = this.CurrentToken.Kind == SyntaxKind.OpenBraceToken ? this.ParseObjectOrCollectionInitializer() : this.ParseExpressionCore(); var elementAccess = _syntaxFactory.ImplicitElementAccess(arguments); return _syntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, elementAccess, equal, expression); } private InitializerExpressionSyntax ParseComplexElementInitializer() { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); var initializers = _pool.AllocateSeparated<ExpressionSyntax>(); try { DiagnosticInfo closeBraceError; this.ParseExpressionsForComplexElementInitializer(ref openBrace, initializers, out closeBraceError); var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); if (closeBraceError != null) { closeBrace = WithAdditionalDiagnostics(closeBrace, closeBraceError); } return _syntaxFactory.InitializerExpression(SyntaxKind.ComplexElementInitializerExpression, openBrace, initializers, closeBrace); } finally { _pool.Free(initializers); } } private void ParseExpressionsForComplexElementInitializer(ref SyntaxToken openBrace, SeparatedSyntaxListBuilder<ExpressionSyntax> list, out DiagnosticInfo closeBraceError) { closeBraceError = null; if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsPossibleExpression() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { // first argument list.Add(this.ParseExpressionCore()); // additional arguments int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleExpression()) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { closeBraceError = MakeError(this.CurrentToken, ErrorCode.ERR_ExpressionExpected); break; } list.Add(this.ParseExpressionCore()); continue; } else if (this.SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadInitializerListTokens(ref openBrace, list, SyntaxKind.IdentifierToken) == PostSkipAction.Continue) { goto tryAgain; } } } private bool IsImplicitlyTypedArray() { Debug.Assert(this.CurrentToken.Kind == SyntaxKind.NewKeyword || this.CurrentToken.Kind == SyntaxKind.StackAllocKeyword); return this.PeekToken(1).Kind == SyntaxKind.OpenBracketToken; } private ImplicitArrayCreationExpressionSyntax ParseImplicitlyTypedArrayCreation() { var @new = this.EatToken(SyntaxKind.NewKeyword); @new = CheckFeatureAvailability(@new, MessageID.IDS_FeatureImplicitArray); var openBracket = this.EatToken(SyntaxKind.OpenBracketToken); var commas = _pool.Allocate(); try { int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.IsPossibleExpression()) { var size = this.AddError(this.ParseExpressionCore(), ErrorCode.ERR_InvalidArray); if (commas.Count == 0) { openBracket = AddTrailingSkippedSyntax(openBracket, size); } else { AddTrailingSkippedSyntax(commas, size); } } if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { commas.Add(this.EatToken()); continue; } break; } var closeBracket = this.EatToken(SyntaxKind.CloseBracketToken); var initializer = this.ParseArrayInitializer(); return _syntaxFactory.ImplicitArrayCreationExpression(@new, openBracket, commas.ToList(), closeBracket, initializer); } finally { _pool.Free(commas); } } private InitializerExpressionSyntax ParseArrayInitializer() { var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); // NOTE: This loop allows " { <initexpr>, } " but not " { , } " var list = _pool.AllocateSeparated<ExpressionSyntax>(); try { if (this.CurrentToken.Kind != SyntaxKind.CloseBraceToken) { tryAgain: if (this.IsPossibleVariableInitializer() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { list.Add(this.ParseVariableInitializer()); int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (this.IsPossibleVariableInitializer() || this.CurrentToken.Kind == SyntaxKind.CommaToken) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); // check for exit case after legal trailing comma if (this.CurrentToken.Kind == SyntaxKind.CloseBraceToken) { break; } else if (!this.IsPossibleVariableInitializer()) { goto tryAgain; } list.Add(this.ParseVariableInitializer()); continue; } else if (SkipBadArrayInitializerTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } } else if (SkipBadArrayInitializerTokens(ref openBrace, list, SyntaxKind.CommaToken) == PostSkipAction.Continue) { goto tryAgain; } } var closeBrace = this.EatToken(SyntaxKind.CloseBraceToken); return _syntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, openBrace, list, closeBrace); } finally { _pool.Free(list); } } private PostSkipAction SkipBadArrayInitializerTokens(ref SyntaxToken openBrace, SeparatedSyntaxListBuilder<ExpressionSyntax> list, SyntaxKind expected) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openBrace, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleVariableInitializer(), p => p.CurrentToken.Kind == SyntaxKind.CloseBraceToken || p.IsTerminator(), expected); } private ExpressionSyntax ParseStackAllocExpression() { if (this.IsImplicitlyTypedArray()) { return ParseImplicitlyTypedStackAllocExpression(); } else { return ParseRegularStackAllocExpression(); } } private ExpressionSyntax ParseImplicitlyTypedStackAllocExpression() { var @stackalloc = this.EatToken(SyntaxKind.StackAllocKeyword); @stackalloc = CheckFeatureAvailability(@stackalloc, MessageID.IDS_FeatureStackAllocInitializer); var openBracket = this.EatToken(SyntaxKind.OpenBracketToken); int lastTokenPosition = -1; while (IsMakingProgress(ref lastTokenPosition)) { if (this.IsPossibleExpression()) { var size = this.AddError(this.ParseExpressionCore(), ErrorCode.ERR_InvalidStackAllocArray); openBracket = AddTrailingSkippedSyntax(openBracket, size); } if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { var comma = this.AddError(this.EatToken(), ErrorCode.ERR_InvalidStackAllocArray); openBracket = AddTrailingSkippedSyntax(openBracket, comma); continue; } break; } var closeBracket = this.EatToken(SyntaxKind.CloseBracketToken); var initializer = this.ParseArrayInitializer(); return _syntaxFactory.ImplicitStackAllocArrayCreationExpression(@stackalloc, openBracket, closeBracket, initializer); } private ExpressionSyntax ParseRegularStackAllocExpression() { var @stackalloc = this.EatToken(SyntaxKind.StackAllocKeyword); var elementType = this.ParseType(); InitializerExpressionSyntax initializer = null; if (this.CurrentToken.Kind == SyntaxKind.OpenBraceToken) { @stackalloc = CheckFeatureAvailability(@stackalloc, MessageID.IDS_FeatureStackAllocInitializer); initializer = this.ParseArrayInitializer(); } return _syntaxFactory.StackAllocArrayCreationExpression(@stackalloc, elementType, initializer); } private AnonymousMethodExpressionSyntax ParseAnonymousMethodExpression() { var parentScopeIsInAsync = this.IsInAsync; var result = parseAnonymousMethodExpressionWorker(); this.IsInAsync = parentScopeIsInAsync; return result; AnonymousMethodExpressionSyntax parseAnonymousMethodExpressionWorker() { var modifiers = ParseAnonymousFunctionModifiers(); if (modifiers.Any((int)SyntaxKind.AsyncKeyword)) { this.IsInAsync = true; } var @delegate = this.EatToken(SyntaxKind.DelegateKeyword); @delegate = CheckFeatureAvailability(@delegate, MessageID.IDS_FeatureAnonDelegates); ParameterListSyntax parameterList = null; if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { parameterList = this.ParseParenthesizedParameterList(); } // In mismatched braces cases (missing a }) it is possible for delegate declarations to be // parsed as delegate statement expressions. When this situation occurs all subsequent // delegate declarations will also be parsed as delegate statement expressions. In a file with // a sufficient number of delegates, common in generated code, it will put considerable // stack pressure on the parser. // // To help avoid this problem we don't recursively descend into a delegate expression unless // { } are actually present. This keeps the stack pressure lower in bad code scenarios. if (this.CurrentToken.Kind != SyntaxKind.OpenBraceToken) { // There's a special error code for a missing token after an accessor keyword var openBrace = this.EatToken(SyntaxKind.OpenBraceToken); return _syntaxFactory.AnonymousMethodExpression( modifiers, @delegate, parameterList, _syntaxFactory.Block( attributeLists: default, openBrace, statements: default, SyntaxFactory.MissingToken(SyntaxKind.CloseBraceToken)), expressionBody: null); } var body = this.ParseBlock(attributes: default); return _syntaxFactory.AnonymousMethodExpression( modifiers, @delegate, parameterList, body, expressionBody: null); } } private SyntaxList<SyntaxToken> ParseAnonymousFunctionModifiers() { var modifiers = _pool.Allocate(); while (true) { if (this.CurrentToken.Kind == SyntaxKind.StaticKeyword) { var staticKeyword = this.EatToken(SyntaxKind.StaticKeyword); staticKeyword = CheckFeatureAvailability(staticKeyword, MessageID.IDS_FeatureStaticAnonymousFunction); modifiers.Add(staticKeyword); continue; } if (this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword && IsAnonymousFunctionAsyncModifier()) { var asyncToken = this.EatContextualToken(SyntaxKind.AsyncKeyword); asyncToken = CheckFeatureAvailability(asyncToken, MessageID.IDS_FeatureAsync); modifiers.Add(asyncToken); continue; } break; } var result = modifiers.ToList(); _pool.Free(modifiers); return result; } private bool IsAnonymousFunctionAsyncModifier() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.AsyncKeyword); switch (this.PeekToken(1).Kind) { case SyntaxKind.OpenParenToken: case SyntaxKind.IdentifierToken: case SyntaxKind.StaticKeyword: case SyntaxKind.RefKeyword: case SyntaxKind.DelegateKeyword: return true; case var kind: return IsPredefinedType(kind); }; } /// <summary> /// Parse expected lambda expression but assume `x ? () => y :` is a conditional /// expression rather than a lambda expression with an explicit return type and /// return null in that case only. /// </summary> private LambdaExpressionSyntax TryParseLambdaExpression() { var resetPoint = this.GetResetPoint(); try { var result = ParseLambdaExpression(); if (this.CurrentToken.Kind == SyntaxKind.ColonToken && result is ParenthesizedLambdaExpressionSyntax { ReturnType: NullableTypeSyntax { } }) { this.Reset(ref resetPoint); return null; } return result; } finally { this.Release(ref resetPoint); } } private LambdaExpressionSyntax ParseLambdaExpression() { var attributes = ParseAttributeDeclarations(); var parentScopeIsInAsync = this.IsInAsync; var result = parseLambdaExpressionWorker(); this.IsInAsync = parentScopeIsInAsync; return result; LambdaExpressionSyntax parseLambdaExpressionWorker() { var modifiers = ParseAnonymousFunctionModifiers(); if (modifiers.Any((int)SyntaxKind.AsyncKeyword)) { this.IsInAsync = true; } TypeSyntax returnType; var resetPoint = this.GetResetPoint(); try { returnType = ParseReturnType(); if (CurrentToken.Kind != SyntaxKind.OpenParenToken) { this.Reset(ref resetPoint); returnType = null; } } finally { this.Release(ref resetPoint); } if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { var paramList = this.ParseLambdaParameterList(); var arrow = this.EatToken(SyntaxKind.EqualsGreaterThanToken); arrow = CheckFeatureAvailability(arrow, MessageID.IDS_FeatureLambda); var (block, expression) = ParseLambdaBody(); return _syntaxFactory.ParenthesizedLambdaExpression( attributes, modifiers, returnType, paramList, arrow, block, expression); } else { var name = this.ParseIdentifierToken(); var arrow = this.EatToken(SyntaxKind.EqualsGreaterThanToken); arrow = CheckFeatureAvailability(arrow, MessageID.IDS_FeatureLambda); var parameter = _syntaxFactory.Parameter( attributeLists: default, modifiers: default, type: null, identifier: name, @default: null); var (block, expression) = ParseLambdaBody(); return _syntaxFactory.SimpleLambdaExpression( attributes, modifiers, parameter, arrow, block, expression); } } } private (BlockSyntax, ExpressionSyntax) ParseLambdaBody() => CurrentToken.Kind == SyntaxKind.OpenBraceToken ? (ParseBlock(attributes: default), (ExpressionSyntax)null) : ((BlockSyntax)null, ParsePossibleRefExpression()); private ParameterListSyntax ParseLambdaParameterList() { var openParen = this.EatToken(SyntaxKind.OpenParenToken); var saveTerm = _termState; _termState |= TerminatorState.IsEndOfParameterList; var nodes = _pool.AllocateSeparated<ParameterSyntax>(); try { if (this.CurrentToken.Kind != SyntaxKind.CloseParenToken) { tryAgain: if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleLambdaParameter()) { // first parameter var parameter = this.ParseLambdaParameter(); nodes.Add(parameter); // additional parameters int tokenProgress = -1; while (IsMakingProgress(ref tokenProgress)) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken || this.IsPossibleLambdaParameter()) { nodes.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); parameter = this.ParseLambdaParameter(); nodes.Add(parameter); continue; } else if (this.SkipBadLambdaParameterListTokens(ref openParen, nodes, SyntaxKind.CommaToken, SyntaxKind.CloseParenToken) == PostSkipAction.Abort) { break; } } } else if (this.SkipBadLambdaParameterListTokens(ref openParen, nodes, SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken) == PostSkipAction.Continue) { goto tryAgain; } } _termState = saveTerm; var closeParen = this.EatToken(SyntaxKind.CloseParenToken); return _syntaxFactory.ParameterList(openParen, nodes, closeParen); } finally { _pool.Free(nodes); } } private bool IsPossibleLambdaParameter() { switch (this.CurrentToken.Kind) { case SyntaxKind.ParamsKeyword: // params is not actually legal in a lambda, but we allow it for error // recovery purposes and then give an error during semantic analysis. case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: case SyntaxKind.OpenParenToken: // tuple case SyntaxKind.OpenBracketToken: // attribute return true; case SyntaxKind.IdentifierToken: return this.IsTrueIdentifier(); case SyntaxKind.DelegateKeyword: return this.IsFunctionPointerStart(); default: return IsPredefinedType(this.CurrentToken.Kind); } } private PostSkipAction SkipBadLambdaParameterListTokens(ref SyntaxToken openParen, SeparatedSyntaxListBuilder<ParameterSyntax> list, SyntaxKind expected, SyntaxKind closeKind) { return this.SkipBadSeparatedListTokensWithExpectedKind(ref openParen, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken && !p.IsPossibleLambdaParameter(), p => p.CurrentToken.Kind == closeKind || p.IsTerminator(), expected); } private ParameterSyntax ParseLambdaParameter() { var attributes = ParseAttributeDeclarations(); // Params are actually illegal in a lambda, but we'll allow it for error recovery purposes and // give the "params unexpected" error at semantic analysis time. bool hasModifier = IsParameterModifier(this.CurrentToken.Kind); TypeSyntax paramType = null; SyntaxListBuilder modifiers = _pool.Allocate(); if (ShouldParseLambdaParameterType(hasModifier)) { if (hasModifier) { ParseParameterModifiers(modifiers); } paramType = ParseType(ParseTypeMode.Parameter); } SyntaxToken paramName = this.ParseIdentifierToken(); var parameter = _syntaxFactory.Parameter(attributes, modifiers.ToList(), paramType, paramName, null); _pool.Free(modifiers); return parameter; } private bool ShouldParseLambdaParameterType(bool hasModifier) { // If we have "ref/out/in/params" always try to parse out a type. if (hasModifier) { return true; } // If we have "int/string/etc." always parse out a type. if (IsPredefinedType(this.CurrentToken.Kind)) { return true; } // if we have a tuple type in a lambda. if (this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { return true; } if (this.IsFunctionPointerStart()) { return true; } if (this.IsTrueIdentifier(this.CurrentToken)) { // Don't parse out a type if we see: // // (a, // (a) // (a => // (a { // // In all other cases, parse out a type. var peek1 = this.PeekToken(1); if (peek1.Kind != SyntaxKind.CommaToken && peek1.Kind != SyntaxKind.CloseParenToken && peek1.Kind != SyntaxKind.EqualsGreaterThanToken && peek1.Kind != SyntaxKind.OpenBraceToken) { return true; } } return false; } private bool IsCurrentTokenQueryContextualKeyword { get { return IsTokenQueryContextualKeyword(this.CurrentToken); } } private static bool IsTokenQueryContextualKeyword(SyntaxToken token) { if (IsTokenStartOfNewQueryClause(token)) { return true; } switch (token.ContextualKind) { case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: case SyntaxKind.ByKeyword: return true; } return false; } private static bool IsTokenStartOfNewQueryClause(SyntaxToken token) { switch (token.ContextualKind) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.IntoKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: case SyntaxKind.LetKeyword: return true; default: return false; } } private bool IsQueryExpression(bool mayBeVariableDeclaration, bool mayBeMemberDeclaration) { if (this.CurrentToken.ContextualKind == SyntaxKind.FromKeyword) { return this.IsQueryExpressionAfterFrom(mayBeVariableDeclaration, mayBeMemberDeclaration); } return false; } // from_clause ::= from <type>? <identifier> in expression private bool IsQueryExpressionAfterFrom(bool mayBeVariableDeclaration, bool mayBeMemberDeclaration) { // from x ... var pk1 = this.PeekToken(1).Kind; if (IsPredefinedType(pk1)) { return true; } if (pk1 == SyntaxKind.IdentifierToken) { var pk2 = this.PeekToken(2).Kind; if (pk2 == SyntaxKind.InKeyword) { return true; } if (mayBeVariableDeclaration) { if (pk2 == SyntaxKind.SemicolonToken || // from x; pk2 == SyntaxKind.CommaToken || // from x, y; pk2 == SyntaxKind.EqualsToken) // from x = null; { return false; } } if (mayBeMemberDeclaration) { // from idf { ... property decl // from idf(... method decl if (pk2 == SyntaxKind.OpenParenToken || pk2 == SyntaxKind.OpenBraceToken) { return false; } // otherwise we need to scan a type } else { return true; } } // from T x ... var resetPoint = this.GetResetPoint(); try { this.EatToken(); ScanTypeFlags isType = this.ScanType(); if (isType != ScanTypeFlags.NotType && (this.CurrentToken.Kind == SyntaxKind.IdentifierToken || this.CurrentToken.Kind == SyntaxKind.InKeyword)) { return true; } } finally { this.Reset(ref resetPoint); this.Release(ref resetPoint); } return false; } private QueryExpressionSyntax ParseQueryExpression(Precedence precedence) { this.EnterQuery(); var fc = this.ParseFromClause(); fc = CheckFeatureAvailability(fc, MessageID.IDS_FeatureQueryExpression); if (precedence > Precedence.Assignment) { fc = this.AddError(fc, ErrorCode.WRN_PrecedenceInversion, SyntaxFacts.GetText(SyntaxKind.FromKeyword)); } var body = this.ParseQueryBody(); this.LeaveQuery(); return _syntaxFactory.QueryExpression(fc, body); } private QueryBodySyntax ParseQueryBody() { var clauses = _pool.Allocate<QueryClauseSyntax>(); try { SelectOrGroupClauseSyntax selectOrGroupBy = null; QueryContinuationSyntax continuation = null; // from, join, let, where and orderby while (true) { switch (this.CurrentToken.ContextualKind) { case SyntaxKind.FromKeyword: var fc = this.ParseFromClause(); clauses.Add(fc); continue; case SyntaxKind.JoinKeyword: clauses.Add(this.ParseJoinClause()); continue; case SyntaxKind.LetKeyword: clauses.Add(this.ParseLetClause()); continue; case SyntaxKind.WhereKeyword: clauses.Add(this.ParseWhereClause()); continue; case SyntaxKind.OrderByKeyword: clauses.Add(this.ParseOrderByClause()); continue; } break; } // select or group clause switch (this.CurrentToken.ContextualKind) { case SyntaxKind.SelectKeyword: selectOrGroupBy = this.ParseSelectClause(); break; case SyntaxKind.GroupKeyword: selectOrGroupBy = this.ParseGroupClause(); break; default: selectOrGroupBy = _syntaxFactory.SelectClause( this.EatToken(SyntaxKind.SelectKeyword, ErrorCode.ERR_ExpectedSelectOrGroup), this.CreateMissingIdentifierName()); break; } // optional query continuation clause if (this.CurrentToken.ContextualKind == SyntaxKind.IntoKeyword) { continuation = this.ParseQueryContinuation(); } return _syntaxFactory.QueryBody(clauses, selectOrGroupBy, continuation); } finally { _pool.Free(clauses); } } private FromClauseSyntax ParseFromClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.FromKeyword); var @from = this.EatContextualToken(SyntaxKind.FromKeyword); @from = CheckFeatureAvailability(@from, MessageID.IDS_FeatureQueryExpression); TypeSyntax type = null; if (this.PeekToken(1).Kind != SyntaxKind.InKeyword) { type = this.ParseType(); } SyntaxToken name; if (this.PeekToken(1).ContextualKind == SyntaxKind.InKeyword && (this.CurrentToken.Kind != SyntaxKind.IdentifierToken || SyntaxFacts.IsQueryContextualKeyword(this.CurrentToken.ContextualKind))) { //if this token is a something other than an identifier (someone accidentally used a contextual //keyword or a literal, for example), but we can see that the "in" is in the right place, then //just replace whatever is here with a missing identifier name = this.EatToken(); name = WithAdditionalDiagnostics(name, this.GetExpectedTokenError(SyntaxKind.IdentifierToken, name.ContextualKind, name.GetLeadingTriviaWidth(), name.Width)); name = this.ConvertToMissingWithTrailingTrivia(name, SyntaxKind.IdentifierToken); } else { name = this.ParseIdentifierToken(); } var @in = this.EatToken(SyntaxKind.InKeyword); var expression = this.ParseExpressionCore(); return _syntaxFactory.FromClause(@from, type, name, @in, expression); } private JoinClauseSyntax ParseJoinClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.JoinKeyword); var @join = this.EatContextualToken(SyntaxKind.JoinKeyword); TypeSyntax type = null; if (this.PeekToken(1).Kind != SyntaxKind.InKeyword) { type = this.ParseType(); } var name = this.ParseIdentifierToken(); var @in = this.EatToken(SyntaxKind.InKeyword); var inExpression = this.ParseExpressionCore(); var @on = this.EatContextualToken(SyntaxKind.OnKeyword, ErrorCode.ERR_ExpectedContextualKeywordOn); var leftExpression = this.ParseExpressionCore(); var @equals = this.EatContextualToken(SyntaxKind.EqualsKeyword, ErrorCode.ERR_ExpectedContextualKeywordEquals); var rightExpression = this.ParseExpressionCore(); JoinIntoClauseSyntax joinInto = null; if (this.CurrentToken.ContextualKind == SyntaxKind.IntoKeyword) { var @into = ConvertToKeyword(this.EatToken()); var intoId = this.ParseIdentifierToken(); joinInto = _syntaxFactory.JoinIntoClause(@into, intoId); } return _syntaxFactory.JoinClause(@join, type, name, @in, inExpression, @on, leftExpression, @equals, rightExpression, joinInto); } private LetClauseSyntax ParseLetClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.LetKeyword); var @let = this.EatContextualToken(SyntaxKind.LetKeyword); var name = this.ParseIdentifierToken(); var equal = this.EatToken(SyntaxKind.EqualsToken); var expression = this.ParseExpressionCore(); return _syntaxFactory.LetClause(@let, name, equal, expression); } private WhereClauseSyntax ParseWhereClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.WhereKeyword); var @where = this.EatContextualToken(SyntaxKind.WhereKeyword); var condition = this.ParseExpressionCore(); return _syntaxFactory.WhereClause(@where, condition); } private OrderByClauseSyntax ParseOrderByClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.OrderByKeyword); var @orderby = this.EatContextualToken(SyntaxKind.OrderByKeyword); var list = _pool.AllocateSeparated<OrderingSyntax>(); try { // first argument list.Add(this.ParseOrdering()); // additional arguments while (this.CurrentToken.Kind == SyntaxKind.CommaToken) { if (this.CurrentToken.Kind == SyntaxKind.CloseParenToken || this.CurrentToken.Kind == SyntaxKind.SemicolonToken) { break; } else if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { list.AddSeparator(this.EatToken(SyntaxKind.CommaToken)); list.Add(this.ParseOrdering()); continue; } else if (this.SkipBadOrderingListTokens(list, SyntaxKind.CommaToken) == PostSkipAction.Abort) { break; } } return _syntaxFactory.OrderByClause(@orderby, list); } finally { _pool.Free(list); } } private PostSkipAction SkipBadOrderingListTokens(SeparatedSyntaxListBuilder<OrderingSyntax> list, SyntaxKind expected) { CSharpSyntaxNode tmp = null; Debug.Assert(list.Count > 0); return this.SkipBadSeparatedListTokensWithExpectedKind(ref tmp, list, p => p.CurrentToken.Kind != SyntaxKind.CommaToken, p => p.CurrentToken.Kind == SyntaxKind.CloseParenToken || p.CurrentToken.Kind == SyntaxKind.SemicolonToken || p.IsCurrentTokenQueryContextualKeyword || p.IsTerminator(), expected); } private OrderingSyntax ParseOrdering() { var expression = this.ParseExpressionCore(); SyntaxToken direction = null; SyntaxKind kind = SyntaxKind.AscendingOrdering; if (this.CurrentToken.ContextualKind == SyntaxKind.AscendingKeyword || this.CurrentToken.ContextualKind == SyntaxKind.DescendingKeyword) { direction = ConvertToKeyword(this.EatToken()); if (direction.Kind == SyntaxKind.DescendingKeyword) { kind = SyntaxKind.DescendingOrdering; } } return _syntaxFactory.Ordering(kind, expression, direction); } private SelectClauseSyntax ParseSelectClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.SelectKeyword); var @select = this.EatContextualToken(SyntaxKind.SelectKeyword); var expression = this.ParseExpressionCore(); return _syntaxFactory.SelectClause(@select, expression); } private GroupClauseSyntax ParseGroupClause() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.GroupKeyword); var @group = this.EatContextualToken(SyntaxKind.GroupKeyword); var groupExpression = this.ParseExpressionCore(); var @by = this.EatContextualToken(SyntaxKind.ByKeyword, ErrorCode.ERR_ExpectedContextualKeywordBy); var byExpression = this.ParseExpressionCore(); return _syntaxFactory.GroupClause(@group, groupExpression, @by, byExpression); } private QueryContinuationSyntax ParseQueryContinuation() { Debug.Assert(this.CurrentToken.ContextualKind == SyntaxKind.IntoKeyword); var @into = this.EatContextualToken(SyntaxKind.IntoKeyword); var name = this.ParseIdentifierToken(); var body = this.ParseQueryBody(); return _syntaxFactory.QueryContinuation(@into, name, body); } [Obsolete("Use IsIncrementalAndFactoryContextMatches")] private new bool IsIncremental { get { throw new Exception("Use IsIncrementalAndFactoryContextMatches"); } } private bool IsIncrementalAndFactoryContextMatches { get { if (!base.IsIncremental) { return false; } CSharp.CSharpSyntaxNode current = this.CurrentNode; return current != null && MatchesFactoryContext(current.Green, _syntaxFactoryContext); } } internal static bool MatchesFactoryContext(GreenNode green, SyntaxFactoryContext context) { return context.IsInAsync == green.ParsedInAsync && context.IsInQuery == green.ParsedInQuery; } private bool IsInAsync { get { return _syntaxFactoryContext.IsInAsync; } set { _syntaxFactoryContext.IsInAsync = value; } } private bool IsInQuery { get { return _syntaxFactoryContext.IsInQuery; } } private void EnterQuery() { _syntaxFactoryContext.QueryDepth++; } private void LeaveQuery() { Debug.Assert(_syntaxFactoryContext.QueryDepth > 0); _syntaxFactoryContext.QueryDepth--; } private new ResetPoint GetResetPoint() { return new ResetPoint( base.GetResetPoint(), _termState, _isInTry, _syntaxFactoryContext.IsInAsync, _syntaxFactoryContext.QueryDepth); } private void Reset(ref ResetPoint state) { _termState = state.TerminatorState; _isInTry = state.IsInTry; _syntaxFactoryContext.IsInAsync = state.IsInAsync; _syntaxFactoryContext.QueryDepth = state.QueryDepth; base.Reset(ref state.BaseResetPoint); } private void Release(ref ResetPoint state) { base.Release(ref state.BaseResetPoint); } private new struct ResetPoint { internal SyntaxParser.ResetPoint BaseResetPoint; internal readonly TerminatorState TerminatorState; internal readonly bool IsInTry; internal readonly bool IsInAsync; internal readonly int QueryDepth; internal ResetPoint( SyntaxParser.ResetPoint resetPoint, TerminatorState terminatorState, bool isInTry, bool isInAsync, int queryDepth) { this.BaseResetPoint = resetPoint; this.TerminatorState = terminatorState; this.IsInTry = isInTry; this.IsInAsync = isInAsync; this.QueryDepth = queryDepth; } } internal TNode ConsumeUnexpectedTokens<TNode>(TNode node) where TNode : CSharpSyntaxNode { if (this.CurrentToken.Kind == SyntaxKind.EndOfFileToken) return node; SyntaxListBuilder<SyntaxToken> b = _pool.Allocate<SyntaxToken>(); while (this.CurrentToken.Kind != SyntaxKind.EndOfFileToken) { b.Add(this.EatToken()); } var trailingTrash = b.ToList(); _pool.Free(b); node = this.AddError(node, ErrorCode.ERR_UnexpectedToken, trailingTrash[0].ToString()); node = this.AddTrailingSkippedSyntax(node, trailingTrash.Node); return node; } } }
1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Compilers/CSharp/Test/Syntax/Parsing/MemberDeclarationParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MemberDeclarationParsingTests : ParsingTests { public MemberDeclarationParsingTests(ITestOutputHelper output) : base(output) { } private MemberDeclarationSyntax ParseDeclaration(string text, int offset = 0, ParseOptions options = null) { return SyntaxFactory.ParseMemberDeclaration(text, offset, options); } private SyntaxTree UsingTree(string text, CSharpParseOptions options, params DiagnosticDescription[] expectedErrors) { var tree = base.UsingTree(text, options); var actualErrors = tree.GetDiagnostics(); actualErrors.Verify(expectedErrors); return tree; } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParsePrivate() { UsingDeclaration("private", options: null, // (1,8): error CS1519: Invalid token '' in class, record, struct, or interface member declaration // private Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "").WithArguments("").WithLocation(1, 8) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.PrivateKeyword); } EOF(); } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParseEmpty() { Assert.Null(ParseDeclaration("")); } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParseTrash() { Assert.Null(ParseDeclaration("+-!@#$%^&*()")); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParseOverflow() { const int n = 10000; var sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.Append("class A{\n"); } for (int i = 0; i < n; i++) { sb.Append("}\n"); } var d = SyntaxFactory.ParseMemberDeclaration(sb.ToString()); if (d.GetDiagnostics().Any()) // some platforms have extra deep stacks and can parse this { d.GetDiagnostics().Verify( // error CS8078: An expression is too long or complex to compile Diagnostic(ErrorCode.ERR_InsufficientStack, "") ); } } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParseOverflow2() { const int n = 10000; var sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.Append("namespace ns {\n"); } for (int i = 0; i < n; i++) { sb.Append("}\n"); } // SyntaxFactory.ParseCompilationUnit has been hardened to be resilient to stack overflow at the same time. var cu = SyntaxFactory.ParseCompilationUnit(sb.ToString()); if (cu.GetDiagnostics().Any()) // some platforms have extra deep stacks and can parse this { cu.GetDiagnostics().Verify( // error CS8078: An expression is too long or complex to compile Diagnostic(ErrorCode.ERR_InsufficientStack, "") ); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void Statement() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("x = x + 1;", offset: 0, options: options, consumeFullText: true, // (1,3): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // x = x + 1; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(1, 3), // (1,1): error CS1073: Unexpected token '=' // x = x + 1; Diagnostic(ErrorCode.ERR_UnexpectedToken, "x").WithArguments("=").WithLocation(1, 1) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void Namespace() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { var d = SyntaxFactory.ParseMemberDeclaration("namespace ns {}", options: options); Assert.Null(d); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void TypeDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("class C { }", options: options); N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void MethodDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("void M() { }", options: options); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void FieldDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("static int F1 = a, F2 = b;", options: options); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "F1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "F2"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void CtorDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public ThisClassName(int x) : base(x) { }", options: options); N(SyntaxKind.ConstructorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.IdentifierToken, "ThisClassName"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BaseConstructorInitializer); { N(SyntaxKind.ColonToken); N(SyntaxKind.BaseKeyword); N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void DtorDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public ~ThisClassName() { }", options: options); N(SyntaxKind.DestructorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.TildeToken); N(SyntaxKind.IdentifierToken, "ThisClassName"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ConversionDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public implicit operator long(int x) => x;", options: options); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void OperatorDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int operator +(int x, int y) => x + y;", options: options); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void TrashAfterDeclaration() { UsingDeclaration("public int x; public int y", offset: 0, options: null, consumeFullText: true, // (1,1): error CS1073: Unexpected token 'public' // public int x; public int y Diagnostic(ErrorCode.ERR_UnexpectedToken, "public int x;").WithArguments("public").WithLocation(1, 1) ); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); UsingDeclaration("public int x; public int y", offset: 0, options: null, consumeFullText: false); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericAsyncTask_01() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("async Task<SomeNamespace.SomeType Method();", options: options, // (1,1): error CS1073: Unexpected token '(' // async Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "async Task<SomeNamespace.SomeType Method").WithArguments("(").WithLocation(1, 1), // (1,35): error CS1003: Syntax error, ',' expected // async Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "Method").WithArguments(",", "").WithLocation(1, 35), // (1,41): error CS1003: Syntax error, '>' expected // async Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(">", "(").WithLocation(1, 41) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeType"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Method"); } M(SyntaxKind.GreaterThanToken); } } } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericPublicTask_01() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public Task<SomeNamespace.SomeType Method();", options: options, // (1,1): error CS1073: Unexpected token '(' // public Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "public Task<SomeNamespace.SomeType Method").WithArguments("(").WithLocation(1, 1), // (1,36): error CS1003: Syntax error, ',' expected // public Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "Method").WithArguments(",", "").WithLocation(1, 36), // (1,42): error CS1003: Syntax error, '>' expected // public Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(">", "(").WithLocation(1, 42) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeType"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Method"); } M(SyntaxKind.GreaterThanToken); } } } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericAsyncTask_02() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("async Task<SomeNamespace. Method();", options: options, // (1,1): error CS1073: Unexpected token '(' // async Task<SomeNamespace. Method(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "async Task<SomeNamespace. Method").WithArguments("(").WithLocation(1, 1), // (1,33): error CS1003: Syntax error, '>' expected // async Task<SomeNamespace. Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(">", "(").WithLocation(1, 33) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Method"); } M(SyntaxKind.GreaterThanToken); } } } } } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericPublicTask_02() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public Task<SomeNamespace. Method();", options: options, // (1,1): error CS1073: Unexpected token '(' // public Task<SomeNamespace. Method(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "public Task<SomeNamespace. Method").WithArguments("(").WithLocation(1, 1), // (1,34): error CS1003: Syntax error, '>' expected // public Task<SomeNamespace. Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(">", "(").WithLocation(1, 34) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Method"); } } M(SyntaxKind.GreaterThanToken); } } } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericAsyncTask_03() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("async Task<SomeNamespace.> Method();", options: options, // (1,26): error CS1001: Identifier expected // async Task<SomeNamespace.> Method(); Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(1, 26) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken, "Method"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericPublicTask_03() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public Task<SomeNamespace.> Method();", options: options, // (1,27): error CS1001: Identifier expected // public Task<SomeNamespace.> Method(); Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(1, 27) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken, "Method"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [CompilerTrait(CompilerFeature.InitOnlySetters)] public void InitAccessor() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("string Property { get; init; }", options: options); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "Property"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.InitAccessorDeclaration); { N(SyntaxKind.InitKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [CompilerTrait(CompilerFeature.InitOnlySetters)] public void InitSetAccessor() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("string Property { init set; }", options: options, // (1,24): error CS8180: { or ; or => expected // string Property { init set; } Diagnostic(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, "set").WithLocation(1, 24), // (1,30): error CS1513: } expected // string Property { init set; } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 30) ); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "Property"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.InitAccessorDeclaration); { N(SyntaxKind.InitKeyword); N(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "set"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [CompilerTrait(CompilerFeature.InitOnlySetters)] public void InitAndSetAccessor() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("string Property { init; set; }", options: options); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "Property"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.InitAccessorDeclaration); { N(SyntaxKind.InitKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.SetAccessorDeclaration); { N(SyntaxKind.SetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [CompilerTrait(CompilerFeature.InitOnlySetters)] public void SetAndInitAccessor() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("string Property { set; init; }", options: options); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "Property"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SetAccessorDeclaration); { N(SyntaxKind.SetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.InitAccessorDeclaration); { N(SyntaxKind.InitKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_01() { var error = // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int N.I.operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_02() { var errors = new[] { // (1,8): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 8), // (1,16): error CS1003: Syntax error, 'operator' expected // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "implicit").WithArguments("operator", "implicit").WithLocation(1, 16), // (1,16): error CS1019: Overloadable unary operator expected // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "implicit").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int N.I.implicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_03() { var errors = new[] { // (1,8): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 8), // (1,16): error CS1003: Syntax error, 'operator' expected // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "explicit").WithArguments("operator", "explicit").WithLocation(1, 16), // (1,16): error CS1019: Overloadable unary operator expected // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "explicit").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int N.I.explicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_04() { var errors = new[] { // (1,16): error CS1003: Syntax error, '.' expected // public int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int N.I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_05() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // public int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_06() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int N::I::operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS7000: Unexpected use of an aliased name // public int N::I::operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 16) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_07() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I::operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,13): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // public int I::operator +(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 13) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_08() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_09() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I<T>.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_10() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int N1::N2::I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,18): error CS7000: Unexpected use of an aliased name // public int N1::N2::I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 18) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_11() { var error = // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int N.I.operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_12() { var errors = new[] { // (1,8): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 8), // (1,16): error CS1003: Syntax error, 'operator' expected // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "implicit").WithArguments("operator", "implicit").WithLocation(1, 16), // (1,16): error CS1019: Overloadable unary operator expected // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "implicit").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int N.I.implicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_13() { var errors = new[] { // (1,8): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 8), // (1,16): error CS1003: Syntax error, 'operator' expected // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "explicit").WithArguments("operator", "explicit").WithLocation(1, 16), // (1,16): error CS1019: Overloadable unary operator expected // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "explicit").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int N.I.explicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_14() { var errors = new[] { // (1,16): error CS1003: Syntax error, '.' expected // public int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int N.I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_15() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // public int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_16() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int N::I::operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS7000: Unexpected use of an aliased name // public int N::I::operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_17() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int I::operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,13): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // public int I::operator +(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 13) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_18() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_19() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int I<T>.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_20() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int N1::N2::I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,18): error CS7000: Unexpected use of an aliased name // public int N1::N2::I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 18) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_21() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I..operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS1001: Identifier expected // public int I..operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 14) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_22() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I . . operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS1001: Identifier expected // public int I . . operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 16) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_23() { var error = // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int N.I.operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_24() { var errors = new[] { // (1,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 1), // (1,9): error CS1003: Syntax error, 'operator' expected // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "implicit").WithArguments("operator", "implicit").WithLocation(1, 9), // (1,9): error CS1019: Overloadable unary operator expected // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "implicit").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int N.I.implicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_25() { var errors = new[] { // (1,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 1), // (1,9): error CS1003: Syntax error, 'operator' expected // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "explicit").WithArguments("operator", "explicit").WithLocation(1, 9), // (1,16): error CS1019: Overloadable unary operator expected // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "explicit").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int N.I.explicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_26() { var errors = new[] { // (1,9): error CS1003: Syntax error, '.' expected // int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int N.I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_27() { var errors = new[] { // (1,7): error CS1003: Syntax error, '.' expected // int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 7) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_28() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N::I::operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,9): error CS7000: Unexpected use of an aliased name // int N::I::operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 9) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_29() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I::operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,6): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I::operator +(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 6) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_30() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_31() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I<T>.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_32() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N1::N2::I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,11): error CS7000: Unexpected use of an aliased name // int N1::N2::I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 11) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_33() { var error = // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int N.I.operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_34() { var errors = new[] { // (1,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 1), // (1,9): error CS1003: Syntax error, 'operator' expected // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "implicit").WithArguments("operator", "implicit").WithLocation(1, 9), // (1,9): error CS1019: Overloadable unary operator expected // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "implicit").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int N.I.implicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_35() { var errors = new[] { // (1,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 1), // (1,9): error CS1003: Syntax error, 'operator' expected // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "explicit").WithArguments("operator", "explicit").WithLocation(1, 9), // (1,9): error CS1019: Overloadable unary operator expected // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "explicit").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int N.I.explicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_36() { var errors = new[] { // (1,9): error CS1003: Syntax error, '.' expected // int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int N.I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_37() { var errors = new[] { // (1,7): error CS1003: Syntax error, '.' expected // int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 7) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_38() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int N::I::operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,9): error CS7000: Unexpected use of an aliased name // int N::I::operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 9) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_39() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int I::operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,6): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I::operator +(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 6) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_40() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_41() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int I<T>.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_42() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int N1::N2::I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,11): error CS7000: Unexpected use of an aliased name // int N1::N2::I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 11) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_43() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I..operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,7): error CS1001: Identifier expected // int I..operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 7) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_44() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I . . operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,9): error CS1001: Identifier expected // int I . . operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 9) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_45() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N.I..operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,9): error CS1001: Identifier expected // int N.I..operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 9) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_46() { var errors = new[] { // (1,5): error CS1001: Identifier expected // N.I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, "operator").WithLocation(1, 5) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("N.I.operator +(int x) => x;", options: options.WithLanguageVersion(version), errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_47() { var errors = new[] { // (1,1): error CS1073: Unexpected token 'int' // N.I. int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedToken, "N.I. ").WithArguments("int").WithLocation(1, 1), // (1,6): error CS1001: Identifier expected // N.I. int(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, "int").WithLocation(1, 6) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("N.I. int(int x) => x;", options: options.WithLanguageVersion(version), errors); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_01() { var error = // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // implicit N.I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 10); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("implicit N.I.operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_02() { var errors = new[] { // (1,1): error CS1003: Syntax error, 'explicit' expected // N.I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "N").WithArguments("explicit", "").WithLocation(1, 1) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("N.I.operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,1): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // N.I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 1) ).ToArray() : errors); N(SyntaxKind.ConversionOperatorDeclaration); { M(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_03() { var errors = new[] { // (1,1): error CS1003: Syntax error, 'explicit' expected // operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments("explicit", "operator").WithLocation(1, 1) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("operator int(int x) => x;", options: options.WithLanguageVersion(version), errors); N(SyntaxKind.ConversionOperatorDeclaration); { M(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_04() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // implicit N.I operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("implicit N.I operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // implicit N.I operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_05() { var errors = new[] { // (1,12): error CS1003: Syntax error, '.' expected // explicit I operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 12) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("explicit I operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // explicit I operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_06() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("implicit N::I::operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS7000: Unexpected use of an aliased name // implicit N::I::operator int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 14) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_07() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I::operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // explicit I::operator int(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 11) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_08() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("implicit I.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_09() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I<T>.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_10() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("implicit N1::N2::I.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS7000: Unexpected use of an aliased name // implicit N1::N2::I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 16) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_11() { var error = // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // explicit N.I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 10); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("explicit N.I.operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_12() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // implicit N.I int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(".", "int").WithLocation(1, 14), // (1,14): error CS1003: Syntax error, 'operator' expected // implicit N.I int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("operator", "int").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("implicit N.I int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // implicit N.I int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_13() { var errors = new[] { // (1,15): error CS1003: Syntax error, 'operator' expected // explicit N.I. int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("operator", "int").WithLocation(1, 15) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("explicit N.I. int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // explicit N.I. int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_14() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // implicit N.I operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("implicit N.I operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // implicit N.I operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_15() { var errors = new[] { // (1,12): error CS1003: Syntax error, '.' expected // explicit I operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 12) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("explicit I operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // explicit I operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_16() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("implicit N::I::operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS7000: Unexpected use of an aliased name // implicit N::I::operator int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 14) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_17() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("explicit I::operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // explicit I::operator int(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 11) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_18() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("implicit I.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_19() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("explicit I<T>.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_20() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("implicit N1::N2::I.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS7000: Unexpected use of an aliased name // implicit N1::N2::I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_21() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I..operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,12): error CS1001: Identifier expected // explicit I..operator int(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 12) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_22() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("implicit I . . operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS1001: Identifier expected // implicit I . . operator int(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 14) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_23() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I T(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,12): error CS1003: Syntax error, '.' expected // explicit I T(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T").WithArguments(".", "").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, 'operator' expected // explicit I T(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T").WithArguments("operator", "").WithLocation(1, 12) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_24() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.T(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,12): error CS1003: Syntax error, 'operator' expected // explicit I.T(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T").WithArguments("operator", "").WithLocation(1, 12) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_25() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_26() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x) { return x; }", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x) { return x; } Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_27() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x);", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_28() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.T1 T2(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,15): error CS1003: Syntax error, '.' expected // explicit I.T1 T2(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T2").WithArguments(".", "").WithLocation(1, 15), // (1,15): error CS1003: Syntax error, 'operator' expected // explicit I.T1 T2(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T2").WithArguments("operator", "").WithLocation(1, 15) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T1"); } } M(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T2"); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_29() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x)", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x) Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21), // (1,28): error CS1002: ; expected // explicit I.operator (int x) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 28) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_30() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x, );", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,29): error CS1031: Type expected // explicit I.operator (int x, ); Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(1, 29), // (1,30): error CS1003: Syntax error, '(' expected // explicit I.operator (int x, ); Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("(", ";").WithLocation(1, 30), // (1,30): error CS1026: ) expected // explicit I.operator (int x, ); Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 30) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_31() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x, int y);", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,35): error CS1003: Syntax error, '(' expected // explicit I.operator (int x, int y); Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("(", ";").WithLocation(1, 35), // (1,35): error CS1026: ) expected // explicit I.operator (int x, int y); Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 35) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_32() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator var(x);", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,26): error CS1001: Identifier expected // explicit I.operator var(x); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(1, 26) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_33() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x int y);", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x int y); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21), // (1,28): error CS1003: Syntax error, ',' expected // explicit I.operator (int x int y); Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(1, 28) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_34() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit N.I..operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS1001: Identifier expected // explicit N.I..operator int(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 14) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_35() { var error = new[] { // (2,9): error CS1003: Syntax error, 'operator' expected // explicit Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("operator", "").WithLocation(2, 9), // (2,9): error CS1001: Identifier expected // explicit Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 9) }; UsingTree( @" explicit Func<int, int> f1 = (param1) => 10; ", options: TestOptions.Regular, error); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); M(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Func"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "f1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "param1"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "10"); } } } } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DotDotRecovery_01() { UsingDeclaration("N1..N2 M(int x) => x;", options: TestOptions.Regular, // (1,4): error CS1001: Identifier expected // N1..N2 M(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 4) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DotDotRecovery_02() { UsingDeclaration("int N1..M(int x) => x;", options: TestOptions.Regular, // (1,8): error CS1001: Identifier expected // int N1..M(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 8) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DotDotRecovery_03() { UsingDeclaration("int N1.N2..M(int x) => x;", options: TestOptions.Regular, // (1,11): error CS1001: Identifier expected // int N1.N2..M(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 11) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MemberDeclarationParsingTests : ParsingTests { public MemberDeclarationParsingTests(ITestOutputHelper output) : base(output) { } private MemberDeclarationSyntax ParseDeclaration(string text, int offset = 0, ParseOptions options = null) { return SyntaxFactory.ParseMemberDeclaration(text, offset, options); } private SyntaxTree UsingTree(string text, CSharpParseOptions options, params DiagnosticDescription[] expectedErrors) { var tree = base.UsingTree(text, options); var actualErrors = tree.GetDiagnostics(); actualErrors.Verify(expectedErrors); return tree; } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParsePrivate() { UsingDeclaration("private", options: null, // (1,8): error CS1519: Invalid token '' in class, record, struct, or interface member declaration // private Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "").WithArguments("").WithLocation(1, 8) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.PrivateKeyword); } EOF(); } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParseEmpty() { Assert.Null(ParseDeclaration("")); } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParseTrash() { Assert.Null(ParseDeclaration("+-!@#$%^&*()")); } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParseOverflow() { const int n = 10000; var sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.Append("class A{\n"); } for (int i = 0; i < n; i++) { sb.Append("}\n"); } var d = SyntaxFactory.ParseMemberDeclaration(sb.ToString()); if (d.GetDiagnostics().Any()) // some platforms have extra deep stacks and can parse this { d.GetDiagnostics().Verify( // error CS8078: An expression is too long or complex to compile Diagnostic(ErrorCode.ERR_InsufficientStack, "") ); } } [ConditionalFact(typeof(WindowsOnly))] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ParseOverflow2() { const int n = 10000; var sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.Append("namespace ns {\n"); } for (int i = 0; i < n; i++) { sb.Append("}\n"); } // SyntaxFactory.ParseCompilationUnit has been hardened to be resilient to stack overflow at the same time. var cu = SyntaxFactory.ParseCompilationUnit(sb.ToString()); if (cu.GetDiagnostics().Any()) // some platforms have extra deep stacks and can parse this { cu.GetDiagnostics().Verify( // error CS8078: An expression is too long or complex to compile Diagnostic(ErrorCode.ERR_InsufficientStack, "") ); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void Statement() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("x = x + 1;", offset: 0, options: options, consumeFullText: true, // (1,3): error CS1519: Invalid token '=' in class, record, struct, or interface member declaration // x = x + 1; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=").WithArguments("=").WithLocation(1, 3), // (1,1): error CS1073: Unexpected token '=' // x = x + 1; Diagnostic(ErrorCode.ERR_UnexpectedToken, "x").WithArguments("=").WithLocation(1, 1) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void Namespace() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { var d = SyntaxFactory.ParseMemberDeclaration("namespace ns {}", options: options); Assert.Null(d); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void TypeDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("class C { }", options: options); N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void MethodDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("void M() { }", options: options); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void FieldDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("static int F1 = a, F2 = b;", options: options); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "F1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "F2"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void CtorDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public ThisClassName(int x) : base(x) { }", options: options); N(SyntaxKind.ConstructorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.IdentifierToken, "ThisClassName"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BaseConstructorInitializer); { N(SyntaxKind.ColonToken); N(SyntaxKind.BaseKeyword); N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void DtorDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public ~ThisClassName() { }", options: options); N(SyntaxKind.DestructorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.TildeToken); N(SyntaxKind.IdentifierToken, "ThisClassName"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void ConversionDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public implicit operator long(int x) => x;", options: options); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void OperatorDeclaration() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int operator +(int x, int y) => x + y;", options: options); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(367, "https://github.com/dotnet/roslyn/issues/367")] public void TrashAfterDeclaration() { UsingDeclaration("public int x; public int y", offset: 0, options: null, consumeFullText: true, // (1,1): error CS1073: Unexpected token 'public' // public int x; public int y Diagnostic(ErrorCode.ERR_UnexpectedToken, "public int x;").WithArguments("public").WithLocation(1, 1) ); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); UsingDeclaration("public int x; public int y", offset: 0, options: null, consumeFullText: false); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericAsyncTask_01() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("async Task<SomeNamespace.SomeType Method();", options: options, // (1,1): error CS1073: Unexpected token '(' // async Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "async Task<SomeNamespace.SomeType Method").WithArguments("(").WithLocation(1, 1), // (1,35): error CS1003: Syntax error, ',' expected // async Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "Method").WithArguments(",", "").WithLocation(1, 35), // (1,41): error CS1003: Syntax error, '>' expected // async Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(">", "(").WithLocation(1, 41) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeType"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Method"); } M(SyntaxKind.GreaterThanToken); } } } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericPublicTask_01() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public Task<SomeNamespace.SomeType Method();", options: options, // (1,1): error CS1073: Unexpected token '(' // public Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "public Task<SomeNamespace.SomeType Method").WithArguments("(").WithLocation(1, 1), // (1,36): error CS1003: Syntax error, ',' expected // public Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "Method").WithArguments(",", "").WithLocation(1, 36), // (1,42): error CS1003: Syntax error, '>' expected // public Task<SomeNamespace.SomeType Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(">", "(").WithLocation(1, 42) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeType"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Method"); } M(SyntaxKind.GreaterThanToken); } } } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericAsyncTask_02() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("async Task<SomeNamespace. Method();", options: options, // (1,1): error CS1073: Unexpected token '(' // async Task<SomeNamespace. Method(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "async Task<SomeNamespace. Method").WithArguments("(").WithLocation(1, 1), // (1,33): error CS1003: Syntax error, '>' expected // async Task<SomeNamespace. Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(">", "(").WithLocation(1, 33) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Method"); } M(SyntaxKind.GreaterThanToken); } } } } } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericPublicTask_02() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public Task<SomeNamespace. Method();", options: options, // (1,1): error CS1073: Unexpected token '(' // public Task<SomeNamespace. Method(); Diagnostic(ErrorCode.ERR_UnexpectedToken, "public Task<SomeNamespace. Method").WithArguments("(").WithLocation(1, 1), // (1,34): error CS1003: Syntax error, '>' expected // public Task<SomeNamespace. Method(); Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(">", "(").WithLocation(1, 34) ); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Method"); } } M(SyntaxKind.GreaterThanToken); } } } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericAsyncTask_03() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("async Task<SomeNamespace.> Method();", options: options, // (1,26): error CS1001: Identifier expected // async Task<SomeNamespace.> Method(); Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(1, 26) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken, "Method"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(11959, "https://github.com/dotnet/roslyn/issues/11959")] public void GenericPublicTask_03() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public Task<SomeNamespace.> Method();", options: options, // (1,27): error CS1001: Identifier expected // public Task<SomeNamespace.> Method(); Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(1, 27) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Task"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "SomeNamespace"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken, "Method"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [CompilerTrait(CompilerFeature.InitOnlySetters)] public void InitAccessor() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("string Property { get; init; }", options: options); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "Property"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.InitAccessorDeclaration); { N(SyntaxKind.InitKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [CompilerTrait(CompilerFeature.InitOnlySetters)] public void InitSetAccessor() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("string Property { init set; }", options: options, // (1,24): error CS8180: { or ; or => expected // string Property { init set; } Diagnostic(ErrorCode.ERR_SemiOrLBraceOrArrowExpected, "set").WithLocation(1, 24), // (1,30): error CS1513: } expected // string Property { init set; } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 30) ); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "Property"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.InitAccessorDeclaration); { N(SyntaxKind.InitKeyword); N(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "set"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [CompilerTrait(CompilerFeature.InitOnlySetters)] public void InitAndSetAccessor() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("string Property { init; set; }", options: options); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "Property"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.InitAccessorDeclaration); { N(SyntaxKind.InitKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.SetAccessorDeclaration); { N(SyntaxKind.SetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] [CompilerTrait(CompilerFeature.InitOnlySetters)] public void SetAndInitAccessor() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("string Property { set; init; }", options: options); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "Property"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SetAccessorDeclaration); { N(SyntaxKind.SetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.InitAccessorDeclaration); { N(SyntaxKind.InitKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_01() { var error = // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int N.I.operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_02() { var errors = new[] { // (1,8): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 8), // (1,16): error CS1003: Syntax error, 'operator' expected // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "implicit").WithArguments("operator", "implicit").WithLocation(1, 16), // (1,16): error CS1019: Overloadable unary operator expected // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "implicit").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int N.I.implicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_03() { var errors = new[] { // (1,8): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 8), // (1,16): error CS1003: Syntax error, 'operator' expected // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "explicit").WithArguments("operator", "explicit").WithLocation(1, 16), // (1,16): error CS1019: Overloadable unary operator expected // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "explicit").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int N.I.explicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_04() { var errors = new[] { // (1,16): error CS1003: Syntax error, '.' expected // public int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int N.I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_05() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // public int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("public int I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_06() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int N::I::operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS7000: Unexpected use of an aliased name // public int N::I::operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 16) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_07() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I::operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,13): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // public int I::operator +(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 13) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_08() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_09() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I<T>.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_10() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int N1::N2::I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,18): error CS7000: Unexpected use of an aliased name // public int N1::N2::I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 18) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_11() { var error = // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int N.I.operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_12() { var errors = new[] { // (1,8): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 8), // (1,16): error CS1003: Syntax error, 'operator' expected // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "implicit").WithArguments("operator", "implicit").WithLocation(1, 16), // (1,16): error CS1019: Overloadable unary operator expected // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "implicit").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int N.I.implicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_13() { var errors = new[] { // (1,8): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 8), // (1,16): error CS1003: Syntax error, 'operator' expected // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "explicit").WithArguments("operator", "explicit").WithLocation(1, 16), // (1,16): error CS1019: Overloadable unary operator expected // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "explicit").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int N.I.explicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_14() { var errors = new[] { // (1,16): error CS1003: Syntax error, '.' expected // public int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 16) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int N.I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_15() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // public int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("public int I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,12): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // public int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 12) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_16() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int N::I::operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS7000: Unexpected use of an aliased name // public int N::I::operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_17() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int I::operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,13): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // public int I::operator +(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 13) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_18() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_19() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int I<T>.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_20() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("public int N1::N2::I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,18): error CS7000: Unexpected use of an aliased name // public int N1::N2::I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 18) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_21() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I..operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS1001: Identifier expected // public int I..operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 14) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_22() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("public int I . . operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS1001: Identifier expected // public int I . . operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 16) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_23() { var error = // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int N.I.operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_24() { var errors = new[] { // (1,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 1), // (1,9): error CS1003: Syntax error, 'operator' expected // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "implicit").WithArguments("operator", "implicit").WithLocation(1, 9), // (1,9): error CS1019: Overloadable unary operator expected // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "implicit").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int N.I.implicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_25() { var errors = new[] { // (1,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 1), // (1,9): error CS1003: Syntax error, 'operator' expected // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "explicit").WithArguments("operator", "explicit").WithLocation(1, 9), // (1,16): error CS1019: Overloadable unary operator expected // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "explicit").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int N.I.explicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_26() { var errors = new[] { // (1,9): error CS1003: Syntax error, '.' expected // int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int N.I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_27() { var errors = new[] { // (1,7): error CS1003: Syntax error, '.' expected // int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 7) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("int I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_28() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N::I::operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,9): error CS7000: Unexpected use of an aliased name // int N::I::operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 9) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_29() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I::operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,6): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I::operator +(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 6) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_30() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_31() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I<T>.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_32() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N1::N2::I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,11): error CS7000: Unexpected use of an aliased name // int N1::N2::I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 11) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_33() { var error = // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int N.I.operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_34() { var errors = new[] { // (1,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 1), // (1,9): error CS1003: Syntax error, 'operator' expected // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "implicit").WithArguments("operator", "implicit").WithLocation(1, 9), // (1,9): error CS1019: Overloadable unary operator expected // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "implicit").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int N.I.implicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.implicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_35() { var errors = new[] { // (1,1): error CS1553: Declaration is not valid; use '+ operator <dest-type> (...' instead // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_BadOperatorSyntax, "int").WithArguments("+").WithLocation(1, 1), // (1,9): error CS1003: Syntax error, 'operator' expected // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "explicit").WithArguments("operator", "explicit").WithLocation(1, 9), // (1,9): error CS1019: Overloadable unary operator expected // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_OvlUnaryOperatorExpected, "explicit").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int N.I.explicit (int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I.explicit (int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); M(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_36() { var errors = new[] { // (1,9): error CS1003: Syntax error, '.' expected // int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 9) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int N.I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int N.I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_37() { var errors = new[] { // (1,7): error CS1003: Syntax error, '.' expected // int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 7) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("int I operator +(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,5): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int I operator +(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 5) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_38() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int N::I::operator +(int x, int y) => x + y;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,9): error CS7000: Unexpected use of an aliased name // int N::I::operator +(int x, int y) => x + y; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 9) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_39() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int I::operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,6): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I::operator +(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 6) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_40() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_41() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int I<T>.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_42() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("int N1::N2::I.operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,11): error CS7000: Unexpected use of an aliased name // int N1::N2::I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 11) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_43() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I..operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,7): error CS1001: Identifier expected // int I..operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 7) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_44() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I . . operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,9): error CS1001: Identifier expected // int I . . operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 9) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_45() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N.I..operator +(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,9): error CS1001: Identifier expected // int N.I..operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 9) ); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void OperatorDeclaration_ExplicitImplementation_46() { var errors = new[] { // (1,5): error CS1001: Identifier expected // N.I.operator +(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, "operator").WithLocation(1, 5) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("N.I.operator +(int x) => x;", options: options.WithLanguageVersion(version), errors); N(SyntaxKind.OperatorDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PlusToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void OperatorDeclaration_ExplicitImplementation_47() { var errors = new[] { // (1,1): error CS1073: Unexpected token 'int' // N.I. int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedToken, "N.I. ").WithArguments("int").WithLocation(1, 1), // (1,6): error CS1001: Identifier expected // N.I. int(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, "int").WithLocation(1, 6) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("N.I. int(int x) => x;", options: options.WithLanguageVersion(version), errors); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_01() { var error = // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // implicit N.I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 10); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("implicit N.I.operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_02() { var errors = new[] { // (1,1): error CS1003: Syntax error, 'explicit' expected // N.I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "N").WithArguments("explicit", "").WithLocation(1, 1) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("N.I.operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,1): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // N.I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 1) ).ToArray() : errors); N(SyntaxKind.ConversionOperatorDeclaration); { M(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_03() { var errors = new[] { // (1,1): error CS1003: Syntax error, 'explicit' expected // operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments("explicit", "operator").WithLocation(1, 1) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("operator int(int x) => x;", options: options.WithLanguageVersion(version), errors); N(SyntaxKind.ConversionOperatorDeclaration); { M(SyntaxKind.ExplicitKeyword); N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_04() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // implicit N.I operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("implicit N.I operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // implicit N.I operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_05() { var errors = new[] { // (1,12): error CS1003: Syntax error, '.' expected // explicit I operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 12) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingDeclaration("explicit I operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // explicit I operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_06() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("implicit N::I::operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS7000: Unexpected use of an aliased name // implicit N::I::operator int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 14) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_07() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I::operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // explicit I::operator int(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 11) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_08() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("implicit I.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_09() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I<T>.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_10() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("implicit N1::N2::I.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS7000: Unexpected use of an aliased name // implicit N1::N2::I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 16) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_11() { var error = // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // explicit N.I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 10); foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("explicit N.I.operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? new[] { error } : new DiagnosticDescription[] { }); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_12() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // implicit N.I int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(".", "int").WithLocation(1, 14), // (1,14): error CS1003: Syntax error, 'operator' expected // implicit N.I int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("operator", "int").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("implicit N.I int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // implicit N.I int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_13() { var errors = new[] { // (1,15): error CS1003: Syntax error, 'operator' expected // explicit N.I. int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("operator", "int").WithLocation(1, 15) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("explicit N.I. int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // explicit N.I. int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I.").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_14() { var errors = new[] { // (1,14): error CS1003: Syntax error, '.' expected // implicit N.I operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 14) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("implicit N.I operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // implicit N.I operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "N.I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_15() { var errors = new[] { // (1,12): error CS1003: Syntax error, '.' expected // explicit I operator int(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "operator").WithArguments(".", "operator").WithLocation(1, 12) }; foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { foreach (var version in new[] { LanguageVersion.CSharp9, LanguageVersion.Preview }) { UsingTree("explicit I operator int(int x) => x;", options: options.WithLanguageVersion(version), version == LanguageVersion.CSharp9 ? errors.Append( // (1,10): error CS8652: The feature 'static abstract members in interfaces' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // explicit I operator int(int x) => x; Diagnostic(ErrorCode.ERR_FeatureInPreview, "I ").WithArguments("static abstract members in interfaces").WithLocation(1, 10) ).ToArray() : errors); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } } [Fact] public void ConversionDeclaration_ExplicitImplementation_16() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("implicit N::I::operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS7000: Unexpected use of an aliased name // implicit N::I::operator int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 14) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_17() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("explicit I::operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,11): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // explicit I::operator int(int x) => x; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 11) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_18() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("implicit I.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_19() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("explicit I<T>.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "I"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_20() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingTree("implicit N1::N2::I.operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,16): error CS7000: Unexpected use of an aliased name // implicit N1::N2::I.operator int(int x) => x; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_21() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I..operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,12): error CS1001: Identifier expected // explicit I..operator int(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 12) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_22() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("implicit I . . operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS1001: Identifier expected // implicit I . . operator int(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 14) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ImplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_23() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I T(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,12): error CS1003: Syntax error, '.' expected // explicit I T(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T").WithArguments(".", "").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, 'operator' expected // explicit I T(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T").WithArguments("operator", "").WithLocation(1, 12) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_24() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.T(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,12): error CS1003: Syntax error, 'operator' expected // explicit I.T(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T").WithArguments("operator", "").WithLocation(1, 12) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_25() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_26() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x) { return x; }", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x) { return x; } Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_27() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x);", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_28() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.T1 T2(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,15): error CS1003: Syntax error, '.' expected // explicit I.T1 T2(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T2").WithArguments(".", "").WithLocation(1, 15), // (1,15): error CS1003: Syntax error, 'operator' expected // explicit I.T1 T2(int x) => x; Diagnostic(ErrorCode.ERR_SyntaxError, "T2").WithArguments("operator", "").WithLocation(1, 15) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T1"); } } M(SyntaxKind.DotToken); } M(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T2"); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_29() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x)", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x) Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21), // (1,28): error CS1002: ; expected // explicit I.operator (int x) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 28) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_30() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x, );", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,29): error CS1031: Type expected // explicit I.operator (int x, ); Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(1, 29), // (1,30): error CS1003: Syntax error, '(' expected // explicit I.operator (int x, ); Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("(", ";").WithLocation(1, 30), // (1,30): error CS1026: ) expected // explicit I.operator (int x, ); Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 30) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_31() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x, int y);", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,35): error CS1003: Syntax error, '(' expected // explicit I.operator (int x, int y); Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("(", ";").WithLocation(1, 35), // (1,35): error CS1026: ) expected // explicit I.operator (int x, int y); Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 35) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_32() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator var(x);", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,26): error CS1001: Identifier expected // explicit I.operator var(x); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(1, 26) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_33() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit I.operator (int x int y);", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,21): error CS1001: Identifier expected // explicit I.operator (int x int y); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(1, 21), // (1,28): error CS1003: Syntax error, ',' expected // explicit I.operator (int x int y); Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(",", "int").WithLocation(1, 28) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_34() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("explicit N.I..operator int(int x) => x;", options: options.WithLanguageVersion(LanguageVersion.Preview), // (1,14): error CS1001: Identifier expected // explicit N.I..operator int(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".operato").WithLocation(1, 14) ); N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.OperatorKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] public void ConversionDeclaration_ExplicitImplementation_35() { var error = new[] { // (2,9): error CS1003: Syntax error, 'operator' expected // explicit Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments("operator", "").WithLocation(2, 9), // (2,9): error CS1001: Identifier expected // explicit Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 9) }; UsingTree( @" explicit Func<int, int> f1 = (param1) => 10; ", options: TestOptions.Regular, error); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ConversionOperatorDeclaration); { N(SyntaxKind.ExplicitKeyword); M(SyntaxKind.OperatorKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "Func"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "f1"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "param1"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "10"); } } } } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DotDotRecovery_01() { UsingDeclaration("N1..N2 M(int x) => x;", options: TestOptions.Regular, // (1,4): error CS1001: Identifier expected // N1..N2 M(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 4) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DotDotRecovery_02() { UsingDeclaration("int N1..M(int x) => x;", options: TestOptions.Regular, // (1,8): error CS1001: Identifier expected // int N1..M(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 8) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DotDotRecovery_03() { UsingDeclaration("int N1.N2..M(int x) => x;", options: TestOptions.Regular, // (1,11): error CS1001: Identifier expected // int N1.N2..M(int x) => x; Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 11) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(53021, "https://github.com/dotnet/roslyn/issues/53021")] public void MisplacedColonColon_01() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N::I::M1() => 0;", options: options, // (1,9): error CS7000: Unexpected use of an aliased name // int N::I::M1() => 0; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 9) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M1"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(53021, "https://github.com/dotnet/roslyn/issues/53021")] public void MisplacedColonColon_02() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N1::N2::I.M1() => 0;", options: options, // (1,11): error CS7000: Unexpected use of an aliased name // int N1::N2::I.M1() => 0; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 11) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } M(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M1"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(53021, "https://github.com/dotnet/roslyn/issues/53021")] public void MisplacedColonColon_03() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N1::N2.I::M1() => 0;", options: options, // (1,13): error CS7000: Unexpected use of an aliased name // int N1::N2.I::M1() => 0; Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithLocation(1, 13) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N2"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } M(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M1"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(53021, "https://github.com/dotnet/roslyn/issues/53021")] public void MisplacedColonColon_04() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int I::M1() => 0;", options: options, // (1,6): error CS0687: The namespace alias qualifier '::' always resolves to a type or namespace so is illegal here. Consider using '.' instead. // int I::M1() => 0; Diagnostic(ErrorCode.ERR_AliasQualAsExpression, "::").WithLocation(1, 6) ); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } M(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M1"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact] [WorkItem(53021, "https://github.com/dotnet/roslyn/issues/53021")] public void MisplacedColonColon_05() { foreach (var options in new[] { TestOptions.Script, TestOptions.Regular }) { UsingDeclaration("int N1::I.M1() => 0;", options: options); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "N1"); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I"); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "M1"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } EOF(); } } } }
1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.AbstractGlobalSuppressMessageCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider { internal abstract class AbstractGlobalSuppressMessageCodeAction : AbstractSuppressionCodeAction { private readonly Project _project; protected AbstractGlobalSuppressMessageCodeAction(AbstractSuppressionCodeFixProvider fixer, Project project) : base(fixer, title: FeaturesResources.in_Suppression_File) { _project = project; } protected sealed override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { var changedSuppressionDocument = await GetChangedSuppressionDocumentAsync(cancellationToken).ConfigureAwait(false); return new CodeActionOperation[] { new ApplyChangesOperation(changedSuppressionDocument.Project.Solution), new OpenDocumentOperation(changedSuppressionDocument.Id, activateIfAlreadyOpen: true), new DocumentNavigationOperation(changedSuppressionDocument.Id, position: 0) }; } protected abstract Task<Document> GetChangedSuppressionDocumentAsync(CancellationToken cancellationToken); private string GetSuppressionsFilePath(string suppressionsFileName) { if (!string.IsNullOrEmpty(_project.FilePath)) { var fullPath = Path.GetFullPath(_project.FilePath); var directory = PathUtilities.GetDirectoryName(fullPath); if (!string.IsNullOrEmpty(directory)) { var suppressionsFilePath = PathUtilities.CombinePossiblyRelativeAndRelativePaths(directory, suppressionsFileName); if (!string.IsNullOrEmpty(suppressionsFilePath)) { return suppressionsFilePath; } } } return suppressionsFileName; } protected async Task<Document> GetOrCreateSuppressionsDocumentAsync(CancellationToken c) { var index = 1; var suppressionsFileName = s_globalSuppressionsFileName + Fixer.DefaultFileExtension; var suppressionsFilePath = GetSuppressionsFilePath(suppressionsFileName); Document suppressionsDoc = null; while (suppressionsDoc == null) { var hasDocWithSuppressionsName = false; foreach (var document in _project.Documents) { var filePath = document.FilePath; var fullPath = !string.IsNullOrEmpty(filePath) ? Path.GetFullPath(filePath) : filePath; if (fullPath == suppressionsFilePath) { // Existing global suppressions file. See if this file only has imports and global assembly // attributes. hasDocWithSuppressionsName = true; var t = await document.GetSyntaxTreeAsync(c).ConfigureAwait(false); var r = await t.GetRootAsync(c).ConfigureAwait(false); var syntaxFacts = _project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); if (r.ChildNodes().All(n => syntaxFacts.IsUsingOrExternOrImport(n) || Fixer.IsAttributeListWithAssemblyAttributes(n))) { suppressionsDoc = document; break; } } } if (suppressionsDoc == null) { if (hasDocWithSuppressionsName || File.Exists(suppressionsFilePath)) { index++; suppressionsFileName = s_globalSuppressionsFileName + index.ToString() + Fixer.DefaultFileExtension; suppressionsFilePath = GetSuppressionsFilePath(suppressionsFileName); } else { // Create an empty global suppressions file. suppressionsDoc = _project.AddDocument(suppressionsFileName, string.Empty); } } } return suppressionsDoc; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider { internal abstract class AbstractGlobalSuppressMessageCodeAction : AbstractSuppressionCodeAction { private readonly Project _project; protected AbstractGlobalSuppressMessageCodeAction(AbstractSuppressionCodeFixProvider fixer, Project project) : base(fixer, title: FeaturesResources.in_Suppression_File) { _project = project; } protected sealed override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { var changedSuppressionDocument = await GetChangedSuppressionDocumentAsync(cancellationToken).ConfigureAwait(false); return new CodeActionOperation[] { new ApplyChangesOperation(changedSuppressionDocument.Project.Solution), new OpenDocumentOperation(changedSuppressionDocument.Id, activateIfAlreadyOpen: true), new DocumentNavigationOperation(changedSuppressionDocument.Id, position: 0) }; } protected abstract Task<Document> GetChangedSuppressionDocumentAsync(CancellationToken cancellationToken); private string GetSuppressionsFilePath(string suppressionsFileName) { if (!string.IsNullOrEmpty(_project.FilePath)) { var fullPath = Path.GetFullPath(_project.FilePath); var directory = PathUtilities.GetDirectoryName(fullPath); if (!string.IsNullOrEmpty(directory)) { var suppressionsFilePath = PathUtilities.CombinePossiblyRelativeAndRelativePaths(directory, suppressionsFileName); if (!string.IsNullOrEmpty(suppressionsFilePath)) { return suppressionsFilePath; } } } return suppressionsFileName; } protected async Task<Document> GetOrCreateSuppressionsDocumentAsync(CancellationToken c) { var index = 1; var suppressionsFileName = s_globalSuppressionsFileName + Fixer.DefaultFileExtension; var suppressionsFilePath = GetSuppressionsFilePath(suppressionsFileName); Document suppressionsDoc = null; while (suppressionsDoc == null) { var hasDocWithSuppressionsName = false; foreach (var document in _project.Documents) { var filePath = document.FilePath; var fullPath = !string.IsNullOrEmpty(filePath) ? Path.GetFullPath(filePath) : filePath; if (fullPath == suppressionsFilePath) { // Existing global suppressions file. See if this file only has imports and global assembly // attributes. hasDocWithSuppressionsName = true; var t = await document.GetSyntaxTreeAsync(c).ConfigureAwait(false); var r = await t.GetRootAsync(c).ConfigureAwait(false); var syntaxFacts = _project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); if (r.ChildNodes().All(n => syntaxFacts.IsUsingOrExternOrImport(n) || Fixer.IsAttributeListWithAssemblyAttributes(n))) { suppressionsDoc = document; break; } } } if (suppressionsDoc == null) { if (hasDocWithSuppressionsName || File.Exists(suppressionsFilePath)) { index++; suppressionsFileName = s_globalSuppressionsFileName + index.ToString() + Fixer.DefaultFileExtension; suppressionsFilePath = GetSuppressionsFilePath(suppressionsFileName); } else { // Create an empty global suppressions file. suppressionsDoc = _project.AddDocument(suppressionsFileName, string.Empty); } } } return suppressionsDoc; } } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Features/Core/Portable/ExtractMethod/MethodExtractor.CodeGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeGeneration; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected abstract partial class CodeGenerator<TStatement, TExpression, TNodeUnderContainer> where TStatement : SyntaxNode where TExpression : SyntaxNode where TNodeUnderContainer : SyntaxNode { protected readonly SyntaxAnnotation MethodNameAnnotation; protected readonly SyntaxAnnotation MethodDefinitionAnnotation; protected readonly SyntaxAnnotation CallSiteAnnotation; protected readonly InsertionPoint InsertionPoint; protected readonly SemanticDocument SemanticDocument; protected readonly SelectionResult SelectionResult; protected readonly AnalyzerResult AnalyzerResult; protected readonly OptionSet Options; protected readonly bool LocalFunction; protected CodeGenerator(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options = null, bool localFunction = false) { Contract.ThrowIfFalse(insertionPoint.SemanticDocument == analyzerResult.SemanticDocument); InsertionPoint = insertionPoint; SemanticDocument = insertionPoint.SemanticDocument; SelectionResult = selectionResult; AnalyzerResult = analyzerResult; Options = options; LocalFunction = localFunction; MethodNameAnnotation = new SyntaxAnnotation(); CallSiteAnnotation = new SyntaxAnnotation(); MethodDefinitionAnnotation = new SyntaxAnnotation(); } #region method to be implemented in sub classes protected abstract SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken); protected abstract Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken); protected abstract SyntaxNode GetPreviousMember(SemanticDocument document); protected abstract OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken); protected abstract bool ShouldLocalFunctionCaptureParameter(SyntaxNode node); protected abstract SyntaxToken CreateIdentifier(string name); protected abstract SyntaxToken CreateMethodName(); protected abstract bool LastStatementOrHasReturnStatementInReturnableConstruct(); protected abstract TNodeUnderContainer GetFirstStatementOrInitializerSelectedAtCallSite(); protected abstract TNodeUnderContainer GetLastStatementOrInitializerSelectedAtCallSite(); protected abstract Task<TNodeUnderContainer> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken); protected abstract TExpression CreateCallSignature(); protected abstract TStatement CreateDeclarationStatement(VariableInfo variable, TExpression initialValue, CancellationToken cancellationToken); protected abstract TStatement CreateAssignmentExpressionStatement(SyntaxToken identifier, TExpression rvalue); protected abstract TStatement CreateReturnStatement(string identifierName = null); protected abstract ImmutableArray<TStatement> GetInitialStatementsForMethodDefinitions(); #endregion public async Task<GeneratedCode> GenerateAsync(CancellationToken cancellationToken) { var root = SemanticDocument.Root; // should I check venus hidden position check here as well? root = root.ReplaceNode(GetOutermostCallSiteContainerToProcess(cancellationToken), await GenerateBodyForCallSiteContainerAsync(cancellationToken).ConfigureAwait(false)); var callSiteDocument = await SemanticDocument.WithSyntaxRootAsync(root, cancellationToken).ConfigureAwait(false); var newCallSiteRoot = callSiteDocument.Root; var codeGenerationService = SemanticDocument.Document.GetLanguageService<ICodeGenerationService>(); var result = GenerateMethodDefinition(LocalFunction, cancellationToken); SyntaxNode destination, newContainer; if (LocalFunction) { destination = InsertionPoint.With(callSiteDocument).GetContext(); // No valid location to insert the new method call. if (destination == null) { return await CreateGeneratedCodeAsync( OperationStatus.NoValidLocationToInsertMethodCall, callSiteDocument, cancellationToken).ConfigureAwait(false); } var localMethod = codeGenerationService.CreateMethodDeclaration( method: result.Data, options: new CodeGenerationOptions(generateDefaultAccessibility: false, generateMethodBodies: true, options: Options, parseOptions: destination?.SyntaxTree.Options)); newContainer = codeGenerationService.AddStatements(destination, new[] { localMethod }, cancellationToken: cancellationToken); } else { var previousMemberNode = GetPreviousMember(callSiteDocument); // it is possible in a script file case where there is no previous member. in that case, insert new text into top level script destination = previousMemberNode.Parent ?? previousMemberNode; newContainer = codeGenerationService.AddMethod( destination, result.Data, new CodeGenerationOptions(afterThisLocation: previousMemberNode.GetLocation(), generateDefaultAccessibility: true, generateMethodBodies: true, options: Options), cancellationToken); } var newSyntaxRoot = newCallSiteRoot.ReplaceNode(destination, newContainer); var newDocument = callSiteDocument.Document.WithSyntaxRoot(newSyntaxRoot); newDocument = await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, null, cancellationToken).ConfigureAwait(false); var generatedDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); // For nullable reference types, we can provide a better experience by reducing use // of nullable reference types after a method is done being generated. If we can // determine that the method never returns null, for example, then we can // make the signature into a non-null reference type even though // the original type was nullable. This allows our code generation to // follow our recommendation of only using nullable when necessary. // This is done after method generation instead of at analyzer time because it's purely // based on the resulting code, which the generator can modify as needed. If return statements // are added, the flow analysis could change to indicate something different. It's cleaner to rely // on flow analysis of the final resulting code than to try and predict from the analyzer what // will happen in the generator. var finalDocument = await UpdateMethodAfterGenerationAsync(generatedDocument, result, cancellationToken).ConfigureAwait(false); var finalRoot = finalDocument.Root; var methodDefinition = finalRoot.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault(); if (!methodDefinition.IsNode || methodDefinition.AsNode() == null) { return await CreateGeneratedCodeAsync( result.Status.With(OperationStatus.FailedWithUnknownReason), finalDocument, cancellationToken).ConfigureAwait(false); } if (methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().SpanStart, cancellationToken) || methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().Span.End, cancellationToken)) { return await CreateGeneratedCodeAsync( result.Status.With(OperationStatus.OverlapsHiddenPosition), finalDocument, cancellationToken).ConfigureAwait(false); } return await CreateGeneratedCodeAsync(result.Status, finalDocument, cancellationToken).ConfigureAwait(false); } protected virtual Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) => Task.FromResult(originalDocument); protected virtual Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { return Task.FromResult(new GeneratedCode( status, newDocument, MethodNameAnnotation, CallSiteAnnotation, MethodDefinitionAnnotation)); } protected VariableInfo GetOutermostVariableToMoveIntoMethodDefinition(CancellationToken cancellationToken) { using var _ = ArrayBuilder<VariableInfo>.GetInstance(out var variables); variables.AddRange(AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken)); if (variables.Count <= 0) return null; VariableInfo.SortVariables(SemanticDocument.SemanticModel.Compilation, variables); return variables[0]; } protected ImmutableArray<TStatement> AddReturnIfUnreachable(ImmutableArray<TStatement> statements) { if (AnalyzerResult.EndOfSelectionReachable) { return statements; } var type = SelectionResult.GetContainingScopeType(); if (type != null && type.SpecialType != SpecialType.System_Void) { return statements; } // no return type + end of selection not reachable if (LastStatementOrHasReturnStatementInReturnableConstruct()) { return statements; } return statements.Concat(CreateReturnStatement()); } protected async Task<ImmutableArray<TStatement>> AddInvocationAtCallSiteAsync( ImmutableArray<TStatement> statements, CancellationToken cancellationToken) { if (AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } Contract.ThrowIfTrue(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Any(v => v.UseAsReturnValue)); // add invocation expression return statements.Concat( (TStatement)(SyntaxNode)await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false)); } protected ImmutableArray<TStatement> AddAssignmentStatementToCallSite( ImmutableArray<TStatement> statements, CancellationToken cancellationToken) { if (!AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } var variable = AnalyzerResult.VariableToUseAsReturnValue; if (variable.ReturnBehavior == ReturnBehavior.Initialization) { // there must be one decl behavior when there is "return value and initialize" variable Contract.ThrowIfFalse(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Single(v => v.ReturnBehavior == ReturnBehavior.Initialization) != null); var declarationStatement = CreateDeclarationStatement( variable, CreateCallSignature(), cancellationToken); declarationStatement = declarationStatement.WithAdditionalAnnotations(CallSiteAnnotation); return statements.Concat(declarationStatement); } Contract.ThrowIfFalse(variable.ReturnBehavior == ReturnBehavior.Assignment); return statements.Concat( CreateAssignmentExpressionStatement(CreateIdentifier(variable.Name), CreateCallSignature()).WithAdditionalAnnotations(CallSiteAnnotation)); } protected ImmutableArray<TStatement> CreateDeclarationStatements( ImmutableArray<VariableInfo> variables, CancellationToken cancellationToken) { return variables.SelectAsArray(v => CreateDeclarationStatement(v, initialValue: null, cancellationToken)); } protected ImmutableArray<TStatement> AddSplitOrMoveDeclarationOutStatementsToCallSite( CancellationToken cancellationToken) { using var _ = ArrayBuilder<TStatement>.GetInstance(out var list); foreach (var variable in AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken)) { if (variable.UseAsReturnValue) continue; var declaration = CreateDeclarationStatement( variable, initialValue: null, cancellationToken: cancellationToken); list.Add(declaration); } return list.ToImmutable(); } protected ImmutableArray<TStatement> AppendReturnStatementIfNeeded(ImmutableArray<TStatement> statements) { if (!AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } var variableToUseAsReturnValue = AnalyzerResult.VariableToUseAsReturnValue; Contract.ThrowIfFalse(variableToUseAsReturnValue.ReturnBehavior is ReturnBehavior.Assignment or ReturnBehavior.Initialization); return statements.Concat(CreateReturnStatement(AnalyzerResult.VariableToUseAsReturnValue.Name)); } protected static HashSet<SyntaxAnnotation> CreateVariableDeclarationToRemoveMap( IEnumerable<VariableInfo> variables, CancellationToken cancellationToken) { var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>(); foreach (var variable in variables) { Contract.ThrowIfFalse(variable.GetDeclarationBehavior(cancellationToken) is DeclarationBehavior.MoveOut or DeclarationBehavior.MoveIn or DeclarationBehavior.Delete); variable.AddIdentifierTokenAnnotationPair(annotations, cancellationToken); } return new HashSet<SyntaxAnnotation>(annotations.Select(t => t.Item2)); } protected ImmutableArray<ITypeParameterSymbol> CreateMethodTypeParameters() { if (AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0) { return ImmutableArray<ITypeParameterSymbol>.Empty; } var set = new HashSet<ITypeParameterSymbol>(AnalyzerResult.MethodTypeParametersInConstraintList); var typeParameters = ArrayBuilder<ITypeParameterSymbol>.GetInstance(); foreach (var parameter in AnalyzerResult.MethodTypeParametersInDeclaration) { if (parameter != null && set.Contains(parameter)) { typeParameters.Add(parameter); continue; } typeParameters.Add(CodeGenerationSymbolFactory.CreateTypeParameter( parameter.GetAttributes(), parameter.Variance, parameter.Name, ImmutableArray.Create<ITypeSymbol>(), parameter.NullableAnnotation, parameter.HasConstructorConstraint, parameter.HasReferenceTypeConstraint, parameter.HasUnmanagedTypeConstraint, parameter.HasValueTypeConstraint, parameter.HasNotNullConstraint, parameter.Ordinal)); } return typeParameters.ToImmutableAndFree(); } protected ImmutableArray<IParameterSymbol> CreateMethodParameters() { var parameters = ArrayBuilder<IParameterSymbol>.GetInstance(); var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root); foreach (var parameter in AnalyzerResult.MethodParameters) { if (!isLocalFunction || !parameter.CanBeCapturedByLocalFunction) { var refKind = GetRefKind(parameter.ParameterModifier); var type = parameter.GetVariableType(SemanticDocument); parameters.Add( CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: ImmutableArray<AttributeData>.Empty, refKind: refKind, isParams: false, type: type, name: parameter.Name)); } } return parameters.ToImmutableAndFree(); } private static RefKind GetRefKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? RefKind.Ref : parameterBehavior == ParameterBehavior.Out ? RefKind.Out : RefKind.None; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected abstract partial class CodeGenerator<TStatement, TExpression, TNodeUnderContainer> where TStatement : SyntaxNode where TExpression : SyntaxNode where TNodeUnderContainer : SyntaxNode { protected readonly SyntaxAnnotation MethodNameAnnotation; protected readonly SyntaxAnnotation MethodDefinitionAnnotation; protected readonly SyntaxAnnotation CallSiteAnnotation; protected readonly InsertionPoint InsertionPoint; protected readonly SemanticDocument SemanticDocument; protected readonly SelectionResult SelectionResult; protected readonly AnalyzerResult AnalyzerResult; protected readonly OptionSet Options; protected readonly bool LocalFunction; protected CodeGenerator(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, OptionSet options = null, bool localFunction = false) { Contract.ThrowIfFalse(insertionPoint.SemanticDocument == analyzerResult.SemanticDocument); InsertionPoint = insertionPoint; SemanticDocument = insertionPoint.SemanticDocument; SelectionResult = selectionResult; AnalyzerResult = analyzerResult; Options = options; LocalFunction = localFunction; MethodNameAnnotation = new SyntaxAnnotation(); CallSiteAnnotation = new SyntaxAnnotation(); MethodDefinitionAnnotation = new SyntaxAnnotation(); } #region method to be implemented in sub classes protected abstract SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken); protected abstract Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken); protected abstract SyntaxNode GetPreviousMember(SemanticDocument document); protected abstract OperationStatus<IMethodSymbol> GenerateMethodDefinition(bool localFunction, CancellationToken cancellationToken); protected abstract bool ShouldLocalFunctionCaptureParameter(SyntaxNode node); protected abstract SyntaxToken CreateIdentifier(string name); protected abstract SyntaxToken CreateMethodName(); protected abstract bool LastStatementOrHasReturnStatementInReturnableConstruct(); protected abstract TNodeUnderContainer GetFirstStatementOrInitializerSelectedAtCallSite(); protected abstract TNodeUnderContainer GetLastStatementOrInitializerSelectedAtCallSite(); protected abstract Task<TNodeUnderContainer> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(CancellationToken cancellationToken); protected abstract TExpression CreateCallSignature(); protected abstract TStatement CreateDeclarationStatement(VariableInfo variable, TExpression initialValue, CancellationToken cancellationToken); protected abstract TStatement CreateAssignmentExpressionStatement(SyntaxToken identifier, TExpression rvalue); protected abstract TStatement CreateReturnStatement(string identifierName = null); protected abstract ImmutableArray<TStatement> GetInitialStatementsForMethodDefinitions(); #endregion public async Task<GeneratedCode> GenerateAsync(CancellationToken cancellationToken) { var root = SemanticDocument.Root; // should I check venus hidden position check here as well? root = root.ReplaceNode(GetOutermostCallSiteContainerToProcess(cancellationToken), await GenerateBodyForCallSiteContainerAsync(cancellationToken).ConfigureAwait(false)); var callSiteDocument = await SemanticDocument.WithSyntaxRootAsync(root, cancellationToken).ConfigureAwait(false); var newCallSiteRoot = callSiteDocument.Root; var codeGenerationService = SemanticDocument.Document.GetLanguageService<ICodeGenerationService>(); var result = GenerateMethodDefinition(LocalFunction, cancellationToken); SyntaxNode destination, newContainer; if (LocalFunction) { destination = InsertionPoint.With(callSiteDocument).GetContext(); // No valid location to insert the new method call. if (destination == null) { return await CreateGeneratedCodeAsync( OperationStatus.NoValidLocationToInsertMethodCall, callSiteDocument, cancellationToken).ConfigureAwait(false); } var localMethod = codeGenerationService.CreateMethodDeclaration( method: result.Data, options: new CodeGenerationOptions(generateDefaultAccessibility: false, generateMethodBodies: true, options: Options, parseOptions: destination?.SyntaxTree.Options)); newContainer = codeGenerationService.AddStatements(destination, new[] { localMethod }, cancellationToken: cancellationToken); } else { var previousMemberNode = GetPreviousMember(callSiteDocument); // it is possible in a script file case where there is no previous member. in that case, insert new text into top level script destination = previousMemberNode.Parent ?? previousMemberNode; newContainer = codeGenerationService.AddMethod( destination, result.Data, new CodeGenerationOptions(afterThisLocation: previousMemberNode.GetLocation(), generateDefaultAccessibility: true, generateMethodBodies: true, options: Options), cancellationToken); } var newSyntaxRoot = newCallSiteRoot.ReplaceNode(destination, newContainer); var newDocument = callSiteDocument.Document.WithSyntaxRoot(newSyntaxRoot); newDocument = await Simplifier.ReduceAsync(newDocument, Simplifier.Annotation, null, cancellationToken).ConfigureAwait(false); var generatedDocument = await SemanticDocument.CreateAsync(newDocument, cancellationToken).ConfigureAwait(false); // For nullable reference types, we can provide a better experience by reducing use // of nullable reference types after a method is done being generated. If we can // determine that the method never returns null, for example, then we can // make the signature into a non-null reference type even though // the original type was nullable. This allows our code generation to // follow our recommendation of only using nullable when necessary. // This is done after method generation instead of at analyzer time because it's purely // based on the resulting code, which the generator can modify as needed. If return statements // are added, the flow analysis could change to indicate something different. It's cleaner to rely // on flow analysis of the final resulting code than to try and predict from the analyzer what // will happen in the generator. var finalDocument = await UpdateMethodAfterGenerationAsync(generatedDocument, result, cancellationToken).ConfigureAwait(false); var finalRoot = finalDocument.Root; var methodDefinition = finalRoot.GetAnnotatedNodesAndTokens(MethodDefinitionAnnotation).FirstOrDefault(); if (!methodDefinition.IsNode || methodDefinition.AsNode() == null) { return await CreateGeneratedCodeAsync( result.Status.With(OperationStatus.FailedWithUnknownReason), finalDocument, cancellationToken).ConfigureAwait(false); } if (methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().SpanStart, cancellationToken) || methodDefinition.SyntaxTree.IsHiddenPosition(methodDefinition.AsNode().Span.End, cancellationToken)) { return await CreateGeneratedCodeAsync( result.Status.With(OperationStatus.OverlapsHiddenPosition), finalDocument, cancellationToken).ConfigureAwait(false); } return await CreateGeneratedCodeAsync(result.Status, finalDocument, cancellationToken).ConfigureAwait(false); } protected virtual Task<SemanticDocument> UpdateMethodAfterGenerationAsync( SemanticDocument originalDocument, OperationStatus<IMethodSymbol> methodSymbolResult, CancellationToken cancellationToken) => Task.FromResult(originalDocument); protected virtual Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { return Task.FromResult(new GeneratedCode( status, newDocument, MethodNameAnnotation, CallSiteAnnotation, MethodDefinitionAnnotation)); } protected VariableInfo GetOutermostVariableToMoveIntoMethodDefinition(CancellationToken cancellationToken) { using var _ = ArrayBuilder<VariableInfo>.GetInstance(out var variables); variables.AddRange(AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken)); if (variables.Count <= 0) return null; VariableInfo.SortVariables(SemanticDocument.SemanticModel.Compilation, variables); return variables[0]; } protected ImmutableArray<TStatement> AddReturnIfUnreachable(ImmutableArray<TStatement> statements) { if (AnalyzerResult.EndOfSelectionReachable) { return statements; } var type = SelectionResult.GetContainingScopeType(); if (type != null && type.SpecialType != SpecialType.System_Void) { return statements; } // no return type + end of selection not reachable if (LastStatementOrHasReturnStatementInReturnableConstruct()) { return statements; } return statements.Concat(CreateReturnStatement()); } protected async Task<ImmutableArray<TStatement>> AddInvocationAtCallSiteAsync( ImmutableArray<TStatement> statements, CancellationToken cancellationToken) { if (AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } Contract.ThrowIfTrue(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Any(v => v.UseAsReturnValue)); // add invocation expression return statements.Concat( (TStatement)(SyntaxNode)await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken).ConfigureAwait(false)); } protected ImmutableArray<TStatement> AddAssignmentStatementToCallSite( ImmutableArray<TStatement> statements, CancellationToken cancellationToken) { if (!AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } var variable = AnalyzerResult.VariableToUseAsReturnValue; if (variable.ReturnBehavior == ReturnBehavior.Initialization) { // there must be one decl behavior when there is "return value and initialize" variable Contract.ThrowIfFalse(AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken).Single(v => v.ReturnBehavior == ReturnBehavior.Initialization) != null); var declarationStatement = CreateDeclarationStatement( variable, CreateCallSignature(), cancellationToken); declarationStatement = declarationStatement.WithAdditionalAnnotations(CallSiteAnnotation); return statements.Concat(declarationStatement); } Contract.ThrowIfFalse(variable.ReturnBehavior == ReturnBehavior.Assignment); return statements.Concat( CreateAssignmentExpressionStatement(CreateIdentifier(variable.Name), CreateCallSignature()).WithAdditionalAnnotations(CallSiteAnnotation)); } protected ImmutableArray<TStatement> CreateDeclarationStatements( ImmutableArray<VariableInfo> variables, CancellationToken cancellationToken) { return variables.SelectAsArray(v => CreateDeclarationStatement(v, initialValue: null, cancellationToken)); } protected ImmutableArray<TStatement> AddSplitOrMoveDeclarationOutStatementsToCallSite( CancellationToken cancellationToken) { using var _ = ArrayBuilder<TStatement>.GetInstance(out var list); foreach (var variable in AnalyzerResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken)) { if (variable.UseAsReturnValue) continue; var declaration = CreateDeclarationStatement( variable, initialValue: null, cancellationToken: cancellationToken); list.Add(declaration); } return list.ToImmutable(); } protected ImmutableArray<TStatement> AppendReturnStatementIfNeeded(ImmutableArray<TStatement> statements) { if (!AnalyzerResult.HasVariableToUseAsReturnValue) { return statements; } var variableToUseAsReturnValue = AnalyzerResult.VariableToUseAsReturnValue; Contract.ThrowIfFalse(variableToUseAsReturnValue.ReturnBehavior is ReturnBehavior.Assignment or ReturnBehavior.Initialization); return statements.Concat(CreateReturnStatement(AnalyzerResult.VariableToUseAsReturnValue.Name)); } protected static HashSet<SyntaxAnnotation> CreateVariableDeclarationToRemoveMap( IEnumerable<VariableInfo> variables, CancellationToken cancellationToken) { var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>(); foreach (var variable in variables) { Contract.ThrowIfFalse(variable.GetDeclarationBehavior(cancellationToken) is DeclarationBehavior.MoveOut or DeclarationBehavior.MoveIn or DeclarationBehavior.Delete); variable.AddIdentifierTokenAnnotationPair(annotations, cancellationToken); } return new HashSet<SyntaxAnnotation>(annotations.Select(t => t.Item2)); } protected ImmutableArray<ITypeParameterSymbol> CreateMethodTypeParameters() { if (AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0) { return ImmutableArray<ITypeParameterSymbol>.Empty; } var set = new HashSet<ITypeParameterSymbol>(AnalyzerResult.MethodTypeParametersInConstraintList); var typeParameters = ArrayBuilder<ITypeParameterSymbol>.GetInstance(); foreach (var parameter in AnalyzerResult.MethodTypeParametersInDeclaration) { if (parameter != null && set.Contains(parameter)) { typeParameters.Add(parameter); continue; } typeParameters.Add(CodeGenerationSymbolFactory.CreateTypeParameter( parameter.GetAttributes(), parameter.Variance, parameter.Name, ImmutableArray.Create<ITypeSymbol>(), parameter.NullableAnnotation, parameter.HasConstructorConstraint, parameter.HasReferenceTypeConstraint, parameter.HasUnmanagedTypeConstraint, parameter.HasValueTypeConstraint, parameter.HasNotNullConstraint, parameter.Ordinal)); } return typeParameters.ToImmutableAndFree(); } protected ImmutableArray<IParameterSymbol> CreateMethodParameters() { var parameters = ArrayBuilder<IParameterSymbol>.GetInstance(); var isLocalFunction = LocalFunction && ShouldLocalFunctionCaptureParameter(SemanticDocument.Root); foreach (var parameter in AnalyzerResult.MethodParameters) { if (!isLocalFunction || !parameter.CanBeCapturedByLocalFunction) { var refKind = GetRefKind(parameter.ParameterModifier); var type = parameter.GetVariableType(SemanticDocument); parameters.Add( CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: ImmutableArray<AttributeData>.Empty, refKind: refKind, isParams: false, type: type, name: parameter.Name)); } } return parameters.ToImmutableAndFree(); } private static RefKind GetRefKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? RefKind.Ref : parameterBehavior == ParameterBehavior.Out ? RefKind.Out : RefKind.None; } } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Compilers/Core/Portable/Symbols/Attributes/AttributeDescription.cs
// Licensed to the .NET Foundation under one or more 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 System.Reflection.Metadata; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal struct AttributeDescription { public readonly string Namespace; public readonly string Name; public readonly byte[][] Signatures; // VB matches ExtensionAttribute name and namespace ignoring case (it's the only attribute that matches its name case-insensitively) public readonly bool MatchIgnoringCase; public AttributeDescription(string @namespace, string name, byte[][] signatures, bool matchIgnoringCase = false) { RoslynDebug.Assert(@namespace != null); RoslynDebug.Assert(name != null); RoslynDebug.Assert(signatures != null); this.Namespace = @namespace; this.Name = name; this.Signatures = signatures; this.MatchIgnoringCase = matchIgnoringCase; } public string FullName { get { return Namespace + "." + Name; } } public override string ToString() { return FullName + "(" + Signatures.Length + ")"; } internal int GetParameterCount(int signatureIndex) { var signature = this.Signatures[signatureIndex]; // only instance ctors are allowed: Debug.Assert(signature[0] == (byte)SignatureAttributes.Instance); // parameter count is the second element of the signature: return signature[1]; } // shortcuts for signature elements supported by our signature comparer: private const byte Void = (byte)SignatureTypeCode.Void; private const byte Boolean = (byte)SignatureTypeCode.Boolean; private const byte Char = (byte)SignatureTypeCode.Char; private const byte SByte = (byte)SignatureTypeCode.SByte; private const byte Byte = (byte)SignatureTypeCode.Byte; private const byte Int16 = (byte)SignatureTypeCode.Int16; private const byte UInt16 = (byte)SignatureTypeCode.UInt16; private const byte Int32 = (byte)SignatureTypeCode.Int32; private const byte UInt32 = (byte)SignatureTypeCode.UInt32; private const byte Int64 = (byte)SignatureTypeCode.Int64; private const byte UInt64 = (byte)SignatureTypeCode.UInt64; private const byte Single = (byte)SignatureTypeCode.Single; private const byte Double = (byte)SignatureTypeCode.Double; private const byte String = (byte)SignatureTypeCode.String; private const byte Object = (byte)SignatureTypeCode.Object; private const byte SzArray = (byte)SignatureTypeCode.SZArray; private const byte TypeHandle = (byte)SignatureTypeCode.TypeHandle; internal enum TypeHandleTarget : byte { AttributeTargets, AssemblyNameFlags, MethodImplOptions, CharSet, LayoutKind, UnmanagedType, TypeLibTypeFlags, ClassInterfaceType, ComInterfaceType, CompilationRelaxations, DebuggingModes, SecurityCriticalScope, CallingConvention, AssemblyHashAlgorithm, TransactionOption, SecurityAction, SystemType, DeprecationType, Platform } internal struct TypeHandleTargetInfo { public readonly string Namespace; public readonly string Name; public readonly SerializationTypeCode Underlying; public TypeHandleTargetInfo(string @namespace, string name, SerializationTypeCode underlying) { Namespace = @namespace; Name = name; Underlying = underlying; } } internal static ImmutableArray<TypeHandleTargetInfo> TypeHandleTargets; static AttributeDescription() { const string system = "System"; const string compilerServices = "System.Runtime.CompilerServices"; const string interopServices = "System.Runtime.InteropServices"; TypeHandleTargets = (new[] { new TypeHandleTargetInfo(system,"AttributeTargets", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Reflection","AssemblyNameFlags", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(compilerServices,"MethodImplOptions", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"CharSet", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"LayoutKind", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"UnmanagedType", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"TypeLibTypeFlags", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"ClassInterfaceType", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"ComInterfaceType", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(compilerServices,"CompilationRelaxations", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Diagnostics.DebuggableAttribute","DebuggingModes", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Security","SecurityCriticalScope", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"CallingConvention", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Configuration.Assemblies","AssemblyHashAlgorithm", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.EnterpriseServices","TransactionOption", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Security.Permissions","SecurityAction", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(system,"Type", SerializationTypeCode.Type) ,new TypeHandleTargetInfo("Windows.Foundation.Metadata","DeprecationType", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("Windows.Foundation.Metadata","Platform", SerializationTypeCode.Int32) }).AsImmutable(); } private static readonly byte[] s_signature_HasThis_Void = new byte[] { (byte)SignatureAttributes.Instance, 0, Void }; private static readonly byte[] s_signature_HasThis_Void_Byte = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Byte }; private static readonly byte[] s_signature_HasThis_Void_Int16 = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Int16 }; private static readonly byte[] s_signature_HasThis_Void_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Int32 }; private static readonly byte[] s_signature_HasThis_Void_UInt32 = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, UInt32 }; private static readonly byte[] s_signature_HasThis_Void_Int32_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Int32, Int32 }; private static readonly byte[] s_signature_HasThis_Void_Int32_Int32_Int32_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, Int32, Int32, Int32, Int32 }; private static readonly byte[] s_signature_HasThis_Void_String = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, String }; private static readonly byte[] s_signature_HasThis_Void_Object = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Object }; private static readonly byte[] s_signature_HasThis_Void_String_String = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, String, String }; private static readonly byte[] s_signature_HasThis_Void_String_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, String, Boolean }; private static readonly byte[] s_signature_HasThis_Void_String_String_String = new byte[] { (byte)SignatureAttributes.Instance, 3, Void, String, String, String }; private static readonly byte[] s_signature_HasThis_Void_String_String_String_String = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, String, String, String, String }; private static readonly byte[] s_signature_HasThis_Void_AttributeTargets = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.AttributeTargets }; private static readonly byte[] s_signature_HasThis_Void_AssemblyNameFlags = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.AssemblyNameFlags }; private static readonly byte[] s_signature_HasThis_Void_MethodImplOptions = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.MethodImplOptions }; private static readonly byte[] s_signature_HasThis_Void_CharSet = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.CharSet }; private static readonly byte[] s_signature_HasThis_Void_LayoutKind = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.LayoutKind }; private static readonly byte[] s_signature_HasThis_Void_UnmanagedType = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.UnmanagedType }; private static readonly byte[] s_signature_HasThis_Void_TypeLibTypeFlags = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.TypeLibTypeFlags }; private static readonly byte[] s_signature_HasThis_Void_ClassInterfaceType = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.ClassInterfaceType }; private static readonly byte[] s_signature_HasThis_Void_ComInterfaceType = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.ComInterfaceType }; private static readonly byte[] s_signature_HasThis_Void_CompilationRelaxations = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.CompilationRelaxations }; private static readonly byte[] s_signature_HasThis_Void_DebuggingModes = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.DebuggingModes }; private static readonly byte[] s_signature_HasThis_Void_SecurityCriticalScope = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.SecurityCriticalScope }; private static readonly byte[] s_signature_HasThis_Void_CallingConvention = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.CallingConvention }; private static readonly byte[] s_signature_HasThis_Void_AssemblyHashAlgorithm = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.AssemblyHashAlgorithm }; private static readonly byte[] s_signature_HasThis_Void_Int64 = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Int64 }; private static readonly byte[] s_signature_HasThis_Void_UInt8_UInt8_UInt32_UInt32_UInt32 = new byte[] { (byte)SignatureAttributes.Instance, 5, Void, Byte, Byte, UInt32, UInt32, UInt32 }; private static readonly byte[] s_signature_HasThis_Void_UIn8_UInt8_Int32_Int32_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 5, Void, Byte, Byte, Int32, Int32, Int32 }; private static readonly byte[] s_signature_HasThis_Void_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Boolean }; private static readonly byte[] s_signature_HasThis_Void_Boolean_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Boolean, Boolean }; private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Boolean, TypeHandle, (byte)TypeHandleTarget.TransactionOption }; private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 3, Void, Boolean, TypeHandle, (byte)TypeHandleTarget.TransactionOption, Int32 }; private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption_Int32_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, Boolean, TypeHandle, (byte)TypeHandleTarget.TransactionOption, Int32, Boolean }; private static readonly byte[] s_signature_HasThis_Void_SecurityAction = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.SecurityAction }; private static readonly byte[] s_signature_HasThis_Void_Type = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_Type_Type = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_Type_Type_Type = new byte[] { (byte)SignatureAttributes.Instance, 3, Void, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_Type_Type_Type_Type = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_Type_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, TypeHandle, (byte)TypeHandleTarget.SystemType, Int32 }; private static readonly byte[] s_signature_HasThis_Void_SzArray_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, SzArray, Boolean }; private static readonly byte[] s_signature_HasThis_Void_SzArray_Byte = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, SzArray, Byte }; private static readonly byte[] s_signature_HasThis_Void_SzArray_String = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, SzArray, String }; private static readonly byte[] s_signature_HasThis_Void_Boolean_SzArray_String = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Boolean, SzArray, String }; private static readonly byte[] s_signature_HasThis_Void_Boolean_String = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Boolean, String }; private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32 = new byte[] { (byte)SignatureAttributes.Instance, 3, Void, String, TypeHandle, (byte)TypeHandleTarget.DeprecationType, UInt32 }; private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_Platform = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, String, TypeHandle, (byte)TypeHandleTarget.DeprecationType, UInt32, TypeHandle, (byte)TypeHandleTarget.Platform }; private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_Type = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, String, TypeHandle, (byte)TypeHandleTarget.DeprecationType, UInt32, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_String = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, String, TypeHandle, (byte)TypeHandleTarget.DeprecationType, UInt32, String }; private static readonly byte[][] s_signatures_HasThis_Void_Only = { s_signature_HasThis_Void }; private static readonly byte[][] s_signatures_HasThis_Void_String_Only = { s_signature_HasThis_Void_String }; private static readonly byte[][] s_signatures_HasThis_Void_Type_Only = { s_signature_HasThis_Void_Type }; private static readonly byte[][] s_signatures_HasThis_Void_Boolean_Only = { s_signature_HasThis_Void_Boolean }; private static readonly byte[][] s_signaturesOfTypeIdentifierAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_String_String }; private static readonly byte[][] s_signaturesOfAttributeUsage = { s_signature_HasThis_Void_AttributeTargets }; private static readonly byte[][] s_signaturesOfAssemblySignatureKeyAttribute = { s_signature_HasThis_Void_String_String }; private static readonly byte[][] s_signaturesOfAssemblyFlagsAttribute = { s_signature_HasThis_Void_AssemblyNameFlags, s_signature_HasThis_Void_Int32, s_signature_HasThis_Void_UInt32 }; private static readonly byte[][] s_signaturesOfDefaultParameterValueAttribute = { s_signature_HasThis_Void_Object }; private static readonly byte[][] s_signaturesOfDateTimeConstantAttribute = { s_signature_HasThis_Void_Int64 }; private static readonly byte[][] s_signaturesOfDecimalConstantAttribute = { s_signature_HasThis_Void_UInt8_UInt8_UInt32_UInt32_UInt32, s_signature_HasThis_Void_UIn8_UInt8_Int32_Int32_Int32 }; private static readonly byte[][] s_signaturesOfSecurityPermissionAttribute = { s_signature_HasThis_Void_SecurityAction }; private static readonly byte[][] s_signaturesOfMethodImplAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_MethodImplOptions, }; private static readonly byte[][] s_signaturesOfDefaultCharSetAttribute = { s_signature_HasThis_Void_CharSet }; private static readonly byte[][] s_signaturesOfFieldOffsetAttribute = { s_signature_HasThis_Void_Int32 }; private static readonly byte[][] s_signaturesOfMemberNotNullAttribute = { s_signature_HasThis_Void_String, s_signature_HasThis_Void_SzArray_String }; private static readonly byte[][] s_signaturesOfMemberNotNullWhenAttribute = { s_signature_HasThis_Void_Boolean_String, s_signature_HasThis_Void_Boolean_SzArray_String }; private static readonly byte[][] s_signaturesOfFixedBufferAttribute = { s_signature_HasThis_Void_Type_Int32 }; private static readonly byte[][] s_signaturesOfPrincipalPermissionAttribute = { s_signature_HasThis_Void_SecurityAction }; private static readonly byte[][] s_signaturesOfPermissionSetAttribute = { s_signature_HasThis_Void_SecurityAction }; private static readonly byte[][] s_signaturesOfStructLayoutAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_LayoutKind, }; private static readonly byte[][] s_signaturesOfMarshalAsAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_UnmanagedType, }; private static readonly byte[][] s_signaturesOfTypeLibTypeAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_TypeLibTypeFlags, }; private static readonly byte[][] s_signaturesOfWebMethodAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_Boolean, s_signature_HasThis_Void_Boolean_TransactionOption, s_signature_HasThis_Void_Boolean_TransactionOption_Int32, s_signature_HasThis_Void_Boolean_TransactionOption_Int32_Boolean }; private static readonly byte[][] s_signaturesOfHostProtectionAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SecurityAction }; private static readonly byte[][] s_signaturesOfVisualBasicComClassAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_String, s_signature_HasThis_Void_String_String, s_signature_HasThis_Void_String_String_String }; private static readonly byte[][] s_signaturesOfClassInterfaceAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_ClassInterfaceType }; private static readonly byte[][] s_signaturesOfInterfaceTypeAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_ComInterfaceType }; private static readonly byte[][] s_signaturesOfCompilationRelaxationsAttribute = { s_signature_HasThis_Void_Int32, s_signature_HasThis_Void_CompilationRelaxations }; private static readonly byte[][] s_signaturesOfDebuggableAttribute = { s_signature_HasThis_Void_Boolean_Boolean, s_signature_HasThis_Void_DebuggingModes }; private static readonly byte[][] s_signaturesOfComSourceInterfacesAttribute = { s_signature_HasThis_Void_String, s_signature_HasThis_Void_Type, s_signature_HasThis_Void_Type_Type, s_signature_HasThis_Void_Type_Type_Type, s_signature_HasThis_Void_Type_Type_Type_Type }; private static readonly byte[][] s_signaturesOfTypeLibVersionAttribute = { s_signature_HasThis_Void_Int32_Int32 }; private static readonly byte[][] s_signaturesOfComCompatibleVersionAttribute = { s_signature_HasThis_Void_Int32_Int32_Int32_Int32 }; private static readonly byte[][] s_signaturesOfObsoleteAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_String, s_signature_HasThis_Void_String_Boolean }; private static readonly byte[][] s_signaturesOfDynamicAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_Boolean }; private static readonly byte[][] s_signaturesOfTupleElementNamesAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_String }; private static readonly byte[][] s_signaturesOfSecurityCriticalAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SecurityCriticalScope }; private static readonly byte[][] s_signaturesOfMyGroupCollectionAttribute = { s_signature_HasThis_Void_String_String_String_String }; private static readonly byte[][] s_signaturesOfComEventInterfaceAttribute = { s_signature_HasThis_Void_Type_Type }; private static readonly byte[][] s_signaturesOfLCIDConversionAttribute = { s_signature_HasThis_Void_Int32 }; private static readonly byte[][] s_signaturesOfUnmanagedFunctionPointerAttribute = { s_signature_HasThis_Void_CallingConvention }; private static readonly byte[][] s_signaturesOfPrimaryInteropAssemblyAttribute = { s_signature_HasThis_Void_Int32_Int32 }; private static readonly byte[][] s_signaturesOfAssemblyAlgorithmIdAttribute = { s_signature_HasThis_Void_AssemblyHashAlgorithm, s_signature_HasThis_Void_UInt32 }; private static readonly byte[][] s_signaturesOfDeprecatedAttribute = { s_signature_HasThis_Void_String_DeprecationType_UInt32, s_signature_HasThis_Void_String_DeprecationType_UInt32_Platform, s_signature_HasThis_Void_String_DeprecationType_UInt32_Type, s_signature_HasThis_Void_String_DeprecationType_UInt32_String, }; private static readonly byte[][] s_signaturesOfNullableAttribute = { s_signature_HasThis_Void_Byte, s_signature_HasThis_Void_SzArray_Byte }; private static readonly byte[][] s_signaturesOfNullableContextAttribute = { s_signature_HasThis_Void_Byte }; private static readonly byte[][] s_signaturesOfNativeIntegerAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_Boolean }; private static readonly byte[][] s_signaturesOfInterpolatedStringArgumentAttribute = { s_signature_HasThis_Void_String, s_signature_HasThis_Void_SzArray_String }; // early decoded attributes: internal static readonly AttributeDescription OptionalAttribute = new AttributeDescription("System.Runtime.InteropServices", "OptionalAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription ComImportAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComImportAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription AttributeUsageAttribute = new AttributeDescription("System", "AttributeUsageAttribute", s_signaturesOfAttributeUsage); internal static readonly AttributeDescription ConditionalAttribute = new AttributeDescription("System.Diagnostics", "ConditionalAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription CaseInsensitiveExtensionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ExtensionAttribute", s_signatures_HasThis_Void_Only, matchIgnoringCase: true); internal static readonly AttributeDescription CaseSensitiveExtensionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ExtensionAttribute", s_signatures_HasThis_Void_Only, matchIgnoringCase: false); internal static readonly AttributeDescription InternalsVisibleToAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InternalsVisibleToAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblySignatureKeyAttribute = new AttributeDescription("System.Reflection", "AssemblySignatureKeyAttribute", s_signaturesOfAssemblySignatureKeyAttribute); internal static readonly AttributeDescription AssemblyKeyFileAttribute = new AttributeDescription("System.Reflection", "AssemblyKeyFileAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyKeyNameAttribute = new AttributeDescription("System.Reflection", "AssemblyKeyNameAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription ParamArrayAttribute = new AttributeDescription("System", "ParamArrayAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DefaultMemberAttribute = new AttributeDescription("System.Reflection", "DefaultMemberAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription IndexerNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IndexerNameAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyDelaySignAttribute = new AttributeDescription("System.Reflection", "AssemblyDelaySignAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription AssemblyVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyVersionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyFileVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyFileVersionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyTitleAttribute = new AttributeDescription("System.Reflection", "AssemblyTitleAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyDescriptionAttribute = new AttributeDescription("System.Reflection", "AssemblyDescriptionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyCultureAttribute = new AttributeDescription("System.Reflection", "AssemblyCultureAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyCompanyAttribute = new AttributeDescription("System.Reflection", "AssemblyCompanyAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyProductAttribute = new AttributeDescription("System.Reflection", "AssemblyProductAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyInformationalVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyInformationalVersionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyCopyrightAttribute = new AttributeDescription("System.Reflection", "AssemblyCopyrightAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription SatelliteContractVersionAttribute = new AttributeDescription("System.Resources", "SatelliteContractVersionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyTrademarkAttribute = new AttributeDescription("System.Reflection", "AssemblyTrademarkAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyFlagsAttribute = new AttributeDescription("System.Reflection", "AssemblyFlagsAttribute", s_signaturesOfAssemblyFlagsAttribute); internal static readonly AttributeDescription DecimalConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DecimalConstantAttribute", s_signaturesOfDecimalConstantAttribute); internal static readonly AttributeDescription IUnknownConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IUnknownConstantAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CallerFilePathAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerFilePathAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CallerLineNumberAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerLineNumberAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CallerMemberNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerMemberNameAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CallerArgumentExpressionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerArgumentExpressionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription IDispatchConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IDispatchConstantAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DefaultParameterValueAttribute = new AttributeDescription("System.Runtime.InteropServices", "DefaultParameterValueAttribute", s_signaturesOfDefaultParameterValueAttribute); internal static readonly AttributeDescription UnverifiableCodeAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnverifiableCodeAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription SecurityPermissionAttribute = new AttributeDescription("System.Runtime.InteropServices", "SecurityPermissionAttribute", s_signaturesOfSecurityPermissionAttribute); internal static readonly AttributeDescription DllImportAttribute = new AttributeDescription("System.Runtime.InteropServices", "DllImportAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription MethodImplAttribute = new AttributeDescription("System.Runtime.CompilerServices", "MethodImplAttribute", s_signaturesOfMethodImplAttribute); internal static readonly AttributeDescription PreserveSigAttribute = new AttributeDescription("System.Runtime.InteropServices", "PreserveSigAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DefaultCharSetAttribute = new AttributeDescription("System.Runtime.InteropServices", "DefaultCharSetAttribute", s_signaturesOfDefaultCharSetAttribute); internal static readonly AttributeDescription SpecialNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "SpecialNameAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription SerializableAttribute = new AttributeDescription("System", "SerializableAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription NonSerializedAttribute = new AttributeDescription("System", "NonSerializedAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription StructLayoutAttribute = new AttributeDescription("System.Runtime.InteropServices", "StructLayoutAttribute", s_signaturesOfStructLayoutAttribute); internal static readonly AttributeDescription FieldOffsetAttribute = new AttributeDescription("System.Runtime.InteropServices", "FieldOffsetAttribute", s_signaturesOfFieldOffsetAttribute); internal static readonly AttributeDescription FixedBufferAttribute = new AttributeDescription("System.Runtime.CompilerServices", "FixedBufferAttribute", s_signaturesOfFixedBufferAttribute); internal static readonly AttributeDescription AllowNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "AllowNullAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DisallowNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DisallowNullAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MaybeNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MaybeNullAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MaybeNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MaybeNullWhenAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription NotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MemberNotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MemberNotNullAttribute", s_signaturesOfMemberNotNullAttribute); internal static readonly AttributeDescription MemberNotNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MemberNotNullWhenAttribute", s_signaturesOfMemberNotNullWhenAttribute); internal static readonly AttributeDescription NotNullIfNotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullIfNotNullAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription NotNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullWhenAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription DoesNotReturnIfAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DoesNotReturnIfAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription DoesNotReturnAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DoesNotReturnAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MarshalAsAttribute = new AttributeDescription("System.Runtime.InteropServices", "MarshalAsAttribute", s_signaturesOfMarshalAsAttribute); internal static readonly AttributeDescription InAttribute = new AttributeDescription("System.Runtime.InteropServices", "InAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription OutAttribute = new AttributeDescription("System.Runtime.InteropServices", "OutAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription IsReadOnlyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsReadOnlyAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription IsUnmanagedAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsUnmanagedAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CoClassAttribute = new AttributeDescription("System.Runtime.InteropServices", "CoClassAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription GuidAttribute = new AttributeDescription("System.Runtime.InteropServices", "GuidAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription CLSCompliantAttribute = new AttributeDescription("System", "CLSCompliantAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription HostProtectionAttribute = new AttributeDescription("System.Security.Permissions", "HostProtectionAttribute", s_signaturesOfHostProtectionAttribute); internal static readonly AttributeDescription SuppressUnmanagedCodeSecurityAttribute = new AttributeDescription("System.Security", "SuppressUnmanagedCodeSecurityAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription PrincipalPermissionAttribute = new AttributeDescription("System.Security.Permissions", "PrincipalPermissionAttribute", s_signaturesOfPrincipalPermissionAttribute); internal static readonly AttributeDescription PermissionSetAttribute = new AttributeDescription("System.Security.Permissions", "PermissionSetAttribute", s_signaturesOfPermissionSetAttribute); internal static readonly AttributeDescription TypeIdentifierAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeIdentifierAttribute", s_signaturesOfTypeIdentifierAttribute); internal static readonly AttributeDescription VisualBasicEmbeddedAttribute = new AttributeDescription("Microsoft.VisualBasic", "Embedded", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CodeAnalysisEmbeddedAttribute = new AttributeDescription("Microsoft.CodeAnalysis", "EmbeddedAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription VisualBasicComClassAttribute = new AttributeDescription("Microsoft.VisualBasic", "ComClassAttribute", s_signaturesOfVisualBasicComClassAttribute); internal static readonly AttributeDescription StandardModuleAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "StandardModuleAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription OptionCompareAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "OptionCompareAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription AccessedThroughPropertyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AccessedThroughPropertyAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription WebMethodAttribute = new AttributeDescription("System.Web.Services", "WebMethodAttribute", s_signaturesOfWebMethodAttribute); internal static readonly AttributeDescription DateTimeConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DateTimeConstantAttribute", s_signaturesOfDateTimeConstantAttribute); internal static readonly AttributeDescription ClassInterfaceAttribute = new AttributeDescription("System.Runtime.InteropServices", "ClassInterfaceAttribute", s_signaturesOfClassInterfaceAttribute); internal static readonly AttributeDescription ComSourceInterfacesAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComSourceInterfacesAttribute", s_signaturesOfComSourceInterfacesAttribute); internal static readonly AttributeDescription ComVisibleAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComVisibleAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription DispIdAttribute = new AttributeDescription("System.Runtime.InteropServices", "DispIdAttribute", new byte[][] { s_signature_HasThis_Void_Int32 }); internal static readonly AttributeDescription TypeLibVersionAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeLibVersionAttribute", s_signaturesOfTypeLibVersionAttribute); internal static readonly AttributeDescription ComCompatibleVersionAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComCompatibleVersionAttribute", s_signaturesOfComCompatibleVersionAttribute); internal static readonly AttributeDescription InterfaceTypeAttribute = new AttributeDescription("System.Runtime.InteropServices", "InterfaceTypeAttribute", s_signaturesOfInterfaceTypeAttribute); internal static readonly AttributeDescription WindowsRuntimeImportAttribute = new AttributeDescription("System.Runtime.InteropServices.WindowsRuntime", "WindowsRuntimeImportAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DynamicSecurityMethodAttribute = new AttributeDescription("System.Security", "DynamicSecurityMethodAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription RequiredAttributeAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RequiredAttributeAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription AsyncMethodBuilderAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AsyncMethodBuilderAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription AsyncStateMachineAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AsyncStateMachineAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription IteratorStateMachineAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IteratorStateMachineAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription CompilationRelaxationsAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CompilationRelaxationsAttribute", s_signaturesOfCompilationRelaxationsAttribute); internal static readonly AttributeDescription ReferenceAssemblyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ReferenceAssemblyAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription RuntimeCompatibilityAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggableAttribute = new AttributeDescription("System.Diagnostics", "DebuggableAttribute", s_signaturesOfDebuggableAttribute); internal static readonly AttributeDescription TypeForwardedToAttribute = new AttributeDescription("System.Runtime.CompilerServices", "TypeForwardedToAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription STAThreadAttribute = new AttributeDescription("System", "STAThreadAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MTAThreadAttribute = new AttributeDescription("System", "MTAThreadAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription ObsoleteAttribute = new AttributeDescription("System", "ObsoleteAttribute", s_signaturesOfObsoleteAttribute); internal static readonly AttributeDescription TypeLibTypeAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeLibTypeAttribute", s_signaturesOfTypeLibTypeAttribute); internal static readonly AttributeDescription DynamicAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DynamicAttribute", s_signaturesOfDynamicAttribute); internal static readonly AttributeDescription TupleElementNamesAttribute = new AttributeDescription("System.Runtime.CompilerServices", "TupleElementNamesAttribute", s_signaturesOfTupleElementNamesAttribute); internal static readonly AttributeDescription IsByRefLikeAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsByRefLikeAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggerHiddenAttribute = new AttributeDescription("System.Diagnostics", "DebuggerHiddenAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggerNonUserCodeAttribute = new AttributeDescription("System.Diagnostics", "DebuggerNonUserCodeAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggerStepperBoundaryAttribute = new AttributeDescription("System.Diagnostics", "DebuggerStepperBoundaryAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggerStepThroughAttribute = new AttributeDescription("System.Diagnostics", "DebuggerStepThroughAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription SecurityCriticalAttribute = new AttributeDescription("System.Security", "SecurityCriticalAttribute", s_signaturesOfSecurityCriticalAttribute); internal static readonly AttributeDescription SecuritySafeCriticalAttribute = new AttributeDescription("System.Security", "SecuritySafeCriticalAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DesignerGeneratedAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "DesignerGeneratedAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MyGroupCollectionAttribute = new AttributeDescription("Microsoft.VisualBasic", "MyGroupCollectionAttribute", s_signaturesOfMyGroupCollectionAttribute); internal static readonly AttributeDescription ComEventInterfaceAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComEventInterfaceAttribute", s_signaturesOfComEventInterfaceAttribute); internal static readonly AttributeDescription BestFitMappingAttribute = new AttributeDescription("System.Runtime.InteropServices", "BestFitMappingAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription FlagsAttribute = new AttributeDescription("System", "FlagsAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription LCIDConversionAttribute = new AttributeDescription("System.Runtime.InteropServices", "LCIDConversionAttribute", s_signaturesOfLCIDConversionAttribute); internal static readonly AttributeDescription UnmanagedFunctionPointerAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute", s_signaturesOfUnmanagedFunctionPointerAttribute); internal static readonly AttributeDescription PrimaryInteropAssemblyAttribute = new AttributeDescription("System.Runtime.InteropServices", "PrimaryInteropAssemblyAttribute", s_signaturesOfPrimaryInteropAssemblyAttribute); internal static readonly AttributeDescription ImportedFromTypeLibAttribute = new AttributeDescription("System.Runtime.InteropServices", "ImportedFromTypeLibAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription DefaultEventAttribute = new AttributeDescription("System.ComponentModel", "DefaultEventAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyConfigurationAttribute = new AttributeDescription("System.Reflection", "AssemblyConfigurationAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyAlgorithmIdAttribute = new AttributeDescription("System.Reflection", "AssemblyAlgorithmIdAttribute", s_signaturesOfAssemblyAlgorithmIdAttribute); internal static readonly AttributeDescription DeprecatedAttribute = new AttributeDescription("Windows.Foundation.Metadata", "DeprecatedAttribute", s_signaturesOfDeprecatedAttribute); internal static readonly AttributeDescription NullableAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullableAttribute", s_signaturesOfNullableAttribute); internal static readonly AttributeDescription NullableContextAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullableContextAttribute", s_signaturesOfNullableContextAttribute); internal static readonly AttributeDescription NullablePublicOnlyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullablePublicOnlyAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription ExperimentalAttribute = new AttributeDescription("Windows.Foundation.Metadata", "ExperimentalAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription ExcludeFromCodeCoverageAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "ExcludeFromCodeCoverageAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription EnumeratorCancellationAttribute = new AttributeDescription("System.Runtime.CompilerServices", "EnumeratorCancellationAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription SkipLocalsInitAttribute = new AttributeDescription("System.Runtime.CompilerServices", "SkipLocalsInitAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription NativeIntegerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NativeIntegerAttribute", s_signaturesOfNativeIntegerAttribute); internal static readonly AttributeDescription ModuleInitializerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ModuleInitializerAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription UnmanagedCallersOnlyAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnmanagedCallersOnlyAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription InterpolatedStringHandlerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InterpolatedStringHandlerAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription InterpolatedStringHandlerArgumentAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InterpolatedStringHandlerArgumentAttribute", s_signaturesOfInterpolatedStringArgumentAttribute); } }
// Licensed to the .NET Foundation under one or more 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 System.Reflection.Metadata; using System.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal struct AttributeDescription { public readonly string Namespace; public readonly string Name; public readonly byte[][] Signatures; // VB matches ExtensionAttribute name and namespace ignoring case (it's the only attribute that matches its name case-insensitively) public readonly bool MatchIgnoringCase; public AttributeDescription(string @namespace, string name, byte[][] signatures, bool matchIgnoringCase = false) { RoslynDebug.Assert(@namespace != null); RoslynDebug.Assert(name != null); RoslynDebug.Assert(signatures != null); this.Namespace = @namespace; this.Name = name; this.Signatures = signatures; this.MatchIgnoringCase = matchIgnoringCase; } public string FullName { get { return Namespace + "." + Name; } } public override string ToString() { return FullName + "(" + Signatures.Length + ")"; } internal int GetParameterCount(int signatureIndex) { var signature = this.Signatures[signatureIndex]; // only instance ctors are allowed: Debug.Assert(signature[0] == (byte)SignatureAttributes.Instance); // parameter count is the second element of the signature: return signature[1]; } // shortcuts for signature elements supported by our signature comparer: private const byte Void = (byte)SignatureTypeCode.Void; private const byte Boolean = (byte)SignatureTypeCode.Boolean; private const byte Char = (byte)SignatureTypeCode.Char; private const byte SByte = (byte)SignatureTypeCode.SByte; private const byte Byte = (byte)SignatureTypeCode.Byte; private const byte Int16 = (byte)SignatureTypeCode.Int16; private const byte UInt16 = (byte)SignatureTypeCode.UInt16; private const byte Int32 = (byte)SignatureTypeCode.Int32; private const byte UInt32 = (byte)SignatureTypeCode.UInt32; private const byte Int64 = (byte)SignatureTypeCode.Int64; private const byte UInt64 = (byte)SignatureTypeCode.UInt64; private const byte Single = (byte)SignatureTypeCode.Single; private const byte Double = (byte)SignatureTypeCode.Double; private const byte String = (byte)SignatureTypeCode.String; private const byte Object = (byte)SignatureTypeCode.Object; private const byte SzArray = (byte)SignatureTypeCode.SZArray; private const byte TypeHandle = (byte)SignatureTypeCode.TypeHandle; internal enum TypeHandleTarget : byte { AttributeTargets, AssemblyNameFlags, MethodImplOptions, CharSet, LayoutKind, UnmanagedType, TypeLibTypeFlags, ClassInterfaceType, ComInterfaceType, CompilationRelaxations, DebuggingModes, SecurityCriticalScope, CallingConvention, AssemblyHashAlgorithm, TransactionOption, SecurityAction, SystemType, DeprecationType, Platform } internal struct TypeHandleTargetInfo { public readonly string Namespace; public readonly string Name; public readonly SerializationTypeCode Underlying; public TypeHandleTargetInfo(string @namespace, string name, SerializationTypeCode underlying) { Namespace = @namespace; Name = name; Underlying = underlying; } } internal static ImmutableArray<TypeHandleTargetInfo> TypeHandleTargets; static AttributeDescription() { const string system = "System"; const string compilerServices = "System.Runtime.CompilerServices"; const string interopServices = "System.Runtime.InteropServices"; TypeHandleTargets = (new[] { new TypeHandleTargetInfo(system,"AttributeTargets", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Reflection","AssemblyNameFlags", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(compilerServices,"MethodImplOptions", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"CharSet", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"LayoutKind", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"UnmanagedType", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"TypeLibTypeFlags", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"ClassInterfaceType", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"ComInterfaceType", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(compilerServices,"CompilationRelaxations", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Diagnostics.DebuggableAttribute","DebuggingModes", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Security","SecurityCriticalScope", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(interopServices,"CallingConvention", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Configuration.Assemblies","AssemblyHashAlgorithm", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.EnterpriseServices","TransactionOption", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("System.Security.Permissions","SecurityAction", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo(system,"Type", SerializationTypeCode.Type) ,new TypeHandleTargetInfo("Windows.Foundation.Metadata","DeprecationType", SerializationTypeCode.Int32) ,new TypeHandleTargetInfo("Windows.Foundation.Metadata","Platform", SerializationTypeCode.Int32) }).AsImmutable(); } private static readonly byte[] s_signature_HasThis_Void = new byte[] { (byte)SignatureAttributes.Instance, 0, Void }; private static readonly byte[] s_signature_HasThis_Void_Byte = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Byte }; private static readonly byte[] s_signature_HasThis_Void_Int16 = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Int16 }; private static readonly byte[] s_signature_HasThis_Void_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Int32 }; private static readonly byte[] s_signature_HasThis_Void_UInt32 = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, UInt32 }; private static readonly byte[] s_signature_HasThis_Void_Int32_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Int32, Int32 }; private static readonly byte[] s_signature_HasThis_Void_Int32_Int32_Int32_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, Int32, Int32, Int32, Int32 }; private static readonly byte[] s_signature_HasThis_Void_String = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, String }; private static readonly byte[] s_signature_HasThis_Void_Object = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Object }; private static readonly byte[] s_signature_HasThis_Void_String_String = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, String, String }; private static readonly byte[] s_signature_HasThis_Void_String_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, String, Boolean }; private static readonly byte[] s_signature_HasThis_Void_String_String_String = new byte[] { (byte)SignatureAttributes.Instance, 3, Void, String, String, String }; private static readonly byte[] s_signature_HasThis_Void_String_String_String_String = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, String, String, String, String }; private static readonly byte[] s_signature_HasThis_Void_AttributeTargets = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.AttributeTargets }; private static readonly byte[] s_signature_HasThis_Void_AssemblyNameFlags = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.AssemblyNameFlags }; private static readonly byte[] s_signature_HasThis_Void_MethodImplOptions = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.MethodImplOptions }; private static readonly byte[] s_signature_HasThis_Void_CharSet = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.CharSet }; private static readonly byte[] s_signature_HasThis_Void_LayoutKind = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.LayoutKind }; private static readonly byte[] s_signature_HasThis_Void_UnmanagedType = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.UnmanagedType }; private static readonly byte[] s_signature_HasThis_Void_TypeLibTypeFlags = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.TypeLibTypeFlags }; private static readonly byte[] s_signature_HasThis_Void_ClassInterfaceType = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.ClassInterfaceType }; private static readonly byte[] s_signature_HasThis_Void_ComInterfaceType = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.ComInterfaceType }; private static readonly byte[] s_signature_HasThis_Void_CompilationRelaxations = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.CompilationRelaxations }; private static readonly byte[] s_signature_HasThis_Void_DebuggingModes = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.DebuggingModes }; private static readonly byte[] s_signature_HasThis_Void_SecurityCriticalScope = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.SecurityCriticalScope }; private static readonly byte[] s_signature_HasThis_Void_CallingConvention = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.CallingConvention }; private static readonly byte[] s_signature_HasThis_Void_AssemblyHashAlgorithm = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.AssemblyHashAlgorithm }; private static readonly byte[] s_signature_HasThis_Void_Int64 = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Int64 }; private static readonly byte[] s_signature_HasThis_Void_UInt8_UInt8_UInt32_UInt32_UInt32 = new byte[] { (byte)SignatureAttributes.Instance, 5, Void, Byte, Byte, UInt32, UInt32, UInt32 }; private static readonly byte[] s_signature_HasThis_Void_UIn8_UInt8_Int32_Int32_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 5, Void, Byte, Byte, Int32, Int32, Int32 }; private static readonly byte[] s_signature_HasThis_Void_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, Boolean }; private static readonly byte[] s_signature_HasThis_Void_Boolean_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Boolean, Boolean }; private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Boolean, TypeHandle, (byte)TypeHandleTarget.TransactionOption }; private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 3, Void, Boolean, TypeHandle, (byte)TypeHandleTarget.TransactionOption, Int32 }; private static readonly byte[] s_signature_HasThis_Void_Boolean_TransactionOption_Int32_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, Boolean, TypeHandle, (byte)TypeHandleTarget.TransactionOption, Int32, Boolean }; private static readonly byte[] s_signature_HasThis_Void_SecurityAction = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.SecurityAction }; private static readonly byte[] s_signature_HasThis_Void_Type = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_Type_Type = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_Type_Type_Type = new byte[] { (byte)SignatureAttributes.Instance, 3, Void, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_Type_Type_Type_Type = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_Type_Int32 = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, TypeHandle, (byte)TypeHandleTarget.SystemType, Int32 }; private static readonly byte[] s_signature_HasThis_Void_SzArray_Boolean = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, SzArray, Boolean }; private static readonly byte[] s_signature_HasThis_Void_SzArray_Byte = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, SzArray, Byte }; private static readonly byte[] s_signature_HasThis_Void_SzArray_String = new byte[] { (byte)SignatureAttributes.Instance, 1, Void, SzArray, String }; private static readonly byte[] s_signature_HasThis_Void_Boolean_SzArray_String = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Boolean, SzArray, String }; private static readonly byte[] s_signature_HasThis_Void_Boolean_String = new byte[] { (byte)SignatureAttributes.Instance, 2, Void, Boolean, String }; private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32 = new byte[] { (byte)SignatureAttributes.Instance, 3, Void, String, TypeHandle, (byte)TypeHandleTarget.DeprecationType, UInt32 }; private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_Platform = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, String, TypeHandle, (byte)TypeHandleTarget.DeprecationType, UInt32, TypeHandle, (byte)TypeHandleTarget.Platform }; private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_Type = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, String, TypeHandle, (byte)TypeHandleTarget.DeprecationType, UInt32, TypeHandle, (byte)TypeHandleTarget.SystemType }; private static readonly byte[] s_signature_HasThis_Void_String_DeprecationType_UInt32_String = new byte[] { (byte)SignatureAttributes.Instance, 4, Void, String, TypeHandle, (byte)TypeHandleTarget.DeprecationType, UInt32, String }; private static readonly byte[][] s_signatures_HasThis_Void_Only = { s_signature_HasThis_Void }; private static readonly byte[][] s_signatures_HasThis_Void_String_Only = { s_signature_HasThis_Void_String }; private static readonly byte[][] s_signatures_HasThis_Void_Type_Only = { s_signature_HasThis_Void_Type }; private static readonly byte[][] s_signatures_HasThis_Void_Boolean_Only = { s_signature_HasThis_Void_Boolean }; private static readonly byte[][] s_signaturesOfTypeIdentifierAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_String_String }; private static readonly byte[][] s_signaturesOfAttributeUsage = { s_signature_HasThis_Void_AttributeTargets }; private static readonly byte[][] s_signaturesOfAssemblySignatureKeyAttribute = { s_signature_HasThis_Void_String_String }; private static readonly byte[][] s_signaturesOfAssemblyFlagsAttribute = { s_signature_HasThis_Void_AssemblyNameFlags, s_signature_HasThis_Void_Int32, s_signature_HasThis_Void_UInt32 }; private static readonly byte[][] s_signaturesOfDefaultParameterValueAttribute = { s_signature_HasThis_Void_Object }; private static readonly byte[][] s_signaturesOfDateTimeConstantAttribute = { s_signature_HasThis_Void_Int64 }; private static readonly byte[][] s_signaturesOfDecimalConstantAttribute = { s_signature_HasThis_Void_UInt8_UInt8_UInt32_UInt32_UInt32, s_signature_HasThis_Void_UIn8_UInt8_Int32_Int32_Int32 }; private static readonly byte[][] s_signaturesOfSecurityPermissionAttribute = { s_signature_HasThis_Void_SecurityAction }; private static readonly byte[][] s_signaturesOfMethodImplAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_MethodImplOptions, }; private static readonly byte[][] s_signaturesOfDefaultCharSetAttribute = { s_signature_HasThis_Void_CharSet }; private static readonly byte[][] s_signaturesOfFieldOffsetAttribute = { s_signature_HasThis_Void_Int32 }; private static readonly byte[][] s_signaturesOfMemberNotNullAttribute = { s_signature_HasThis_Void_String, s_signature_HasThis_Void_SzArray_String }; private static readonly byte[][] s_signaturesOfMemberNotNullWhenAttribute = { s_signature_HasThis_Void_Boolean_String, s_signature_HasThis_Void_Boolean_SzArray_String }; private static readonly byte[][] s_signaturesOfFixedBufferAttribute = { s_signature_HasThis_Void_Type_Int32 }; private static readonly byte[][] s_signaturesOfPrincipalPermissionAttribute = { s_signature_HasThis_Void_SecurityAction }; private static readonly byte[][] s_signaturesOfPermissionSetAttribute = { s_signature_HasThis_Void_SecurityAction }; private static readonly byte[][] s_signaturesOfStructLayoutAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_LayoutKind, }; private static readonly byte[][] s_signaturesOfMarshalAsAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_UnmanagedType, }; private static readonly byte[][] s_signaturesOfTypeLibTypeAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_TypeLibTypeFlags, }; private static readonly byte[][] s_signaturesOfWebMethodAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_Boolean, s_signature_HasThis_Void_Boolean_TransactionOption, s_signature_HasThis_Void_Boolean_TransactionOption_Int32, s_signature_HasThis_Void_Boolean_TransactionOption_Int32_Boolean }; private static readonly byte[][] s_signaturesOfHostProtectionAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SecurityAction }; private static readonly byte[][] s_signaturesOfVisualBasicComClassAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_String, s_signature_HasThis_Void_String_String, s_signature_HasThis_Void_String_String_String }; private static readonly byte[][] s_signaturesOfClassInterfaceAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_ClassInterfaceType }; private static readonly byte[][] s_signaturesOfInterfaceTypeAttribute = { s_signature_HasThis_Void_Int16, s_signature_HasThis_Void_ComInterfaceType }; private static readonly byte[][] s_signaturesOfCompilationRelaxationsAttribute = { s_signature_HasThis_Void_Int32, s_signature_HasThis_Void_CompilationRelaxations }; private static readonly byte[][] s_signaturesOfDebuggableAttribute = { s_signature_HasThis_Void_Boolean_Boolean, s_signature_HasThis_Void_DebuggingModes }; private static readonly byte[][] s_signaturesOfComSourceInterfacesAttribute = { s_signature_HasThis_Void_String, s_signature_HasThis_Void_Type, s_signature_HasThis_Void_Type_Type, s_signature_HasThis_Void_Type_Type_Type, s_signature_HasThis_Void_Type_Type_Type_Type }; private static readonly byte[][] s_signaturesOfTypeLibVersionAttribute = { s_signature_HasThis_Void_Int32_Int32 }; private static readonly byte[][] s_signaturesOfComCompatibleVersionAttribute = { s_signature_HasThis_Void_Int32_Int32_Int32_Int32 }; private static readonly byte[][] s_signaturesOfObsoleteAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_String, s_signature_HasThis_Void_String_Boolean }; private static readonly byte[][] s_signaturesOfDynamicAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_Boolean }; private static readonly byte[][] s_signaturesOfTupleElementNamesAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_String }; private static readonly byte[][] s_signaturesOfSecurityCriticalAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SecurityCriticalScope }; private static readonly byte[][] s_signaturesOfMyGroupCollectionAttribute = { s_signature_HasThis_Void_String_String_String_String }; private static readonly byte[][] s_signaturesOfComEventInterfaceAttribute = { s_signature_HasThis_Void_Type_Type }; private static readonly byte[][] s_signaturesOfLCIDConversionAttribute = { s_signature_HasThis_Void_Int32 }; private static readonly byte[][] s_signaturesOfUnmanagedFunctionPointerAttribute = { s_signature_HasThis_Void_CallingConvention }; private static readonly byte[][] s_signaturesOfPrimaryInteropAssemblyAttribute = { s_signature_HasThis_Void_Int32_Int32 }; private static readonly byte[][] s_signaturesOfAssemblyAlgorithmIdAttribute = { s_signature_HasThis_Void_AssemblyHashAlgorithm, s_signature_HasThis_Void_UInt32 }; private static readonly byte[][] s_signaturesOfDeprecatedAttribute = { s_signature_HasThis_Void_String_DeprecationType_UInt32, s_signature_HasThis_Void_String_DeprecationType_UInt32_Platform, s_signature_HasThis_Void_String_DeprecationType_UInt32_Type, s_signature_HasThis_Void_String_DeprecationType_UInt32_String, }; private static readonly byte[][] s_signaturesOfNullableAttribute = { s_signature_HasThis_Void_Byte, s_signature_HasThis_Void_SzArray_Byte }; private static readonly byte[][] s_signaturesOfNullableContextAttribute = { s_signature_HasThis_Void_Byte }; private static readonly byte[][] s_signaturesOfNativeIntegerAttribute = { s_signature_HasThis_Void, s_signature_HasThis_Void_SzArray_Boolean }; private static readonly byte[][] s_signaturesOfInterpolatedStringArgumentAttribute = { s_signature_HasThis_Void_String, s_signature_HasThis_Void_SzArray_String }; // early decoded attributes: internal static readonly AttributeDescription OptionalAttribute = new AttributeDescription("System.Runtime.InteropServices", "OptionalAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription ComImportAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComImportAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription AttributeUsageAttribute = new AttributeDescription("System", "AttributeUsageAttribute", s_signaturesOfAttributeUsage); internal static readonly AttributeDescription ConditionalAttribute = new AttributeDescription("System.Diagnostics", "ConditionalAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription CaseInsensitiveExtensionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ExtensionAttribute", s_signatures_HasThis_Void_Only, matchIgnoringCase: true); internal static readonly AttributeDescription CaseSensitiveExtensionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ExtensionAttribute", s_signatures_HasThis_Void_Only, matchIgnoringCase: false); internal static readonly AttributeDescription InternalsVisibleToAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InternalsVisibleToAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblySignatureKeyAttribute = new AttributeDescription("System.Reflection", "AssemblySignatureKeyAttribute", s_signaturesOfAssemblySignatureKeyAttribute); internal static readonly AttributeDescription AssemblyKeyFileAttribute = new AttributeDescription("System.Reflection", "AssemblyKeyFileAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyKeyNameAttribute = new AttributeDescription("System.Reflection", "AssemblyKeyNameAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription ParamArrayAttribute = new AttributeDescription("System", "ParamArrayAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DefaultMemberAttribute = new AttributeDescription("System.Reflection", "DefaultMemberAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription IndexerNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IndexerNameAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyDelaySignAttribute = new AttributeDescription("System.Reflection", "AssemblyDelaySignAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription AssemblyVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyVersionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyFileVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyFileVersionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyTitleAttribute = new AttributeDescription("System.Reflection", "AssemblyTitleAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyDescriptionAttribute = new AttributeDescription("System.Reflection", "AssemblyDescriptionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyCultureAttribute = new AttributeDescription("System.Reflection", "AssemblyCultureAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyCompanyAttribute = new AttributeDescription("System.Reflection", "AssemblyCompanyAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyProductAttribute = new AttributeDescription("System.Reflection", "AssemblyProductAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyInformationalVersionAttribute = new AttributeDescription("System.Reflection", "AssemblyInformationalVersionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyCopyrightAttribute = new AttributeDescription("System.Reflection", "AssemblyCopyrightAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription SatelliteContractVersionAttribute = new AttributeDescription("System.Resources", "SatelliteContractVersionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyTrademarkAttribute = new AttributeDescription("System.Reflection", "AssemblyTrademarkAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyFlagsAttribute = new AttributeDescription("System.Reflection", "AssemblyFlagsAttribute", s_signaturesOfAssemblyFlagsAttribute); internal static readonly AttributeDescription DecimalConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DecimalConstantAttribute", s_signaturesOfDecimalConstantAttribute); internal static readonly AttributeDescription IUnknownConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IUnknownConstantAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CallerFilePathAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerFilePathAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CallerLineNumberAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerLineNumberAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CallerMemberNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerMemberNameAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CallerArgumentExpressionAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CallerArgumentExpressionAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription IDispatchConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IDispatchConstantAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DefaultParameterValueAttribute = new AttributeDescription("System.Runtime.InteropServices", "DefaultParameterValueAttribute", s_signaturesOfDefaultParameterValueAttribute); internal static readonly AttributeDescription UnverifiableCodeAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnverifiableCodeAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription SecurityPermissionAttribute = new AttributeDescription("System.Runtime.InteropServices", "SecurityPermissionAttribute", s_signaturesOfSecurityPermissionAttribute); internal static readonly AttributeDescription DllImportAttribute = new AttributeDescription("System.Runtime.InteropServices", "DllImportAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription MethodImplAttribute = new AttributeDescription("System.Runtime.CompilerServices", "MethodImplAttribute", s_signaturesOfMethodImplAttribute); internal static readonly AttributeDescription PreserveSigAttribute = new AttributeDescription("System.Runtime.InteropServices", "PreserveSigAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DefaultCharSetAttribute = new AttributeDescription("System.Runtime.InteropServices", "DefaultCharSetAttribute", s_signaturesOfDefaultCharSetAttribute); internal static readonly AttributeDescription SpecialNameAttribute = new AttributeDescription("System.Runtime.CompilerServices", "SpecialNameAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription SerializableAttribute = new AttributeDescription("System", "SerializableAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription NonSerializedAttribute = new AttributeDescription("System", "NonSerializedAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription StructLayoutAttribute = new AttributeDescription("System.Runtime.InteropServices", "StructLayoutAttribute", s_signaturesOfStructLayoutAttribute); internal static readonly AttributeDescription FieldOffsetAttribute = new AttributeDescription("System.Runtime.InteropServices", "FieldOffsetAttribute", s_signaturesOfFieldOffsetAttribute); internal static readonly AttributeDescription FixedBufferAttribute = new AttributeDescription("System.Runtime.CompilerServices", "FixedBufferAttribute", s_signaturesOfFixedBufferAttribute); internal static readonly AttributeDescription AllowNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "AllowNullAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DisallowNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DisallowNullAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MaybeNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MaybeNullAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MaybeNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MaybeNullWhenAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription NotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MemberNotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MemberNotNullAttribute", s_signaturesOfMemberNotNullAttribute); internal static readonly AttributeDescription MemberNotNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "MemberNotNullWhenAttribute", s_signaturesOfMemberNotNullWhenAttribute); internal static readonly AttributeDescription NotNullIfNotNullAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullIfNotNullAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription NotNullWhenAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "NotNullWhenAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription DoesNotReturnIfAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DoesNotReturnIfAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription DoesNotReturnAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "DoesNotReturnAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MarshalAsAttribute = new AttributeDescription("System.Runtime.InteropServices", "MarshalAsAttribute", s_signaturesOfMarshalAsAttribute); internal static readonly AttributeDescription InAttribute = new AttributeDescription("System.Runtime.InteropServices", "InAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription OutAttribute = new AttributeDescription("System.Runtime.InteropServices", "OutAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription IsReadOnlyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsReadOnlyAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription IsUnmanagedAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsUnmanagedAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CoClassAttribute = new AttributeDescription("System.Runtime.InteropServices", "CoClassAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription GuidAttribute = new AttributeDescription("System.Runtime.InteropServices", "GuidAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription CLSCompliantAttribute = new AttributeDescription("System", "CLSCompliantAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription HostProtectionAttribute = new AttributeDescription("System.Security.Permissions", "HostProtectionAttribute", s_signaturesOfHostProtectionAttribute); internal static readonly AttributeDescription SuppressUnmanagedCodeSecurityAttribute = new AttributeDescription("System.Security", "SuppressUnmanagedCodeSecurityAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription PrincipalPermissionAttribute = new AttributeDescription("System.Security.Permissions", "PrincipalPermissionAttribute", s_signaturesOfPrincipalPermissionAttribute); internal static readonly AttributeDescription PermissionSetAttribute = new AttributeDescription("System.Security.Permissions", "PermissionSetAttribute", s_signaturesOfPermissionSetAttribute); internal static readonly AttributeDescription TypeIdentifierAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeIdentifierAttribute", s_signaturesOfTypeIdentifierAttribute); internal static readonly AttributeDescription VisualBasicEmbeddedAttribute = new AttributeDescription("Microsoft.VisualBasic", "Embedded", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription CodeAnalysisEmbeddedAttribute = new AttributeDescription("Microsoft.CodeAnalysis", "EmbeddedAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription VisualBasicComClassAttribute = new AttributeDescription("Microsoft.VisualBasic", "ComClassAttribute", s_signaturesOfVisualBasicComClassAttribute); internal static readonly AttributeDescription StandardModuleAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "StandardModuleAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription OptionCompareAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "OptionCompareAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription AccessedThroughPropertyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AccessedThroughPropertyAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription WebMethodAttribute = new AttributeDescription("System.Web.Services", "WebMethodAttribute", s_signaturesOfWebMethodAttribute); internal static readonly AttributeDescription DateTimeConstantAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DateTimeConstantAttribute", s_signaturesOfDateTimeConstantAttribute); internal static readonly AttributeDescription ClassInterfaceAttribute = new AttributeDescription("System.Runtime.InteropServices", "ClassInterfaceAttribute", s_signaturesOfClassInterfaceAttribute); internal static readonly AttributeDescription ComSourceInterfacesAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComSourceInterfacesAttribute", s_signaturesOfComSourceInterfacesAttribute); internal static readonly AttributeDescription ComVisibleAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComVisibleAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription DispIdAttribute = new AttributeDescription("System.Runtime.InteropServices", "DispIdAttribute", new byte[][] { s_signature_HasThis_Void_Int32 }); internal static readonly AttributeDescription TypeLibVersionAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeLibVersionAttribute", s_signaturesOfTypeLibVersionAttribute); internal static readonly AttributeDescription ComCompatibleVersionAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComCompatibleVersionAttribute", s_signaturesOfComCompatibleVersionAttribute); internal static readonly AttributeDescription InterfaceTypeAttribute = new AttributeDescription("System.Runtime.InteropServices", "InterfaceTypeAttribute", s_signaturesOfInterfaceTypeAttribute); internal static readonly AttributeDescription WindowsRuntimeImportAttribute = new AttributeDescription("System.Runtime.InteropServices.WindowsRuntime", "WindowsRuntimeImportAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DynamicSecurityMethodAttribute = new AttributeDescription("System.Security", "DynamicSecurityMethodAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription RequiredAttributeAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RequiredAttributeAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription AsyncMethodBuilderAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AsyncMethodBuilderAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription AsyncStateMachineAttribute = new AttributeDescription("System.Runtime.CompilerServices", "AsyncStateMachineAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription IteratorStateMachineAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IteratorStateMachineAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription CompilationRelaxationsAttribute = new AttributeDescription("System.Runtime.CompilerServices", "CompilationRelaxationsAttribute", s_signaturesOfCompilationRelaxationsAttribute); internal static readonly AttributeDescription ReferenceAssemblyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ReferenceAssemblyAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription RuntimeCompatibilityAttribute = new AttributeDescription("System.Runtime.CompilerServices", "RuntimeCompatibilityAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggableAttribute = new AttributeDescription("System.Diagnostics", "DebuggableAttribute", s_signaturesOfDebuggableAttribute); internal static readonly AttributeDescription TypeForwardedToAttribute = new AttributeDescription("System.Runtime.CompilerServices", "TypeForwardedToAttribute", s_signatures_HasThis_Void_Type_Only); internal static readonly AttributeDescription STAThreadAttribute = new AttributeDescription("System", "STAThreadAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MTAThreadAttribute = new AttributeDescription("System", "MTAThreadAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription ObsoleteAttribute = new AttributeDescription("System", "ObsoleteAttribute", s_signaturesOfObsoleteAttribute); internal static readonly AttributeDescription TypeLibTypeAttribute = new AttributeDescription("System.Runtime.InteropServices", "TypeLibTypeAttribute", s_signaturesOfTypeLibTypeAttribute); internal static readonly AttributeDescription DynamicAttribute = new AttributeDescription("System.Runtime.CompilerServices", "DynamicAttribute", s_signaturesOfDynamicAttribute); internal static readonly AttributeDescription TupleElementNamesAttribute = new AttributeDescription("System.Runtime.CompilerServices", "TupleElementNamesAttribute", s_signaturesOfTupleElementNamesAttribute); internal static readonly AttributeDescription IsByRefLikeAttribute = new AttributeDescription("System.Runtime.CompilerServices", "IsByRefLikeAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggerHiddenAttribute = new AttributeDescription("System.Diagnostics", "DebuggerHiddenAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggerNonUserCodeAttribute = new AttributeDescription("System.Diagnostics", "DebuggerNonUserCodeAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggerStepperBoundaryAttribute = new AttributeDescription("System.Diagnostics", "DebuggerStepperBoundaryAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DebuggerStepThroughAttribute = new AttributeDescription("System.Diagnostics", "DebuggerStepThroughAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription SecurityCriticalAttribute = new AttributeDescription("System.Security", "SecurityCriticalAttribute", s_signaturesOfSecurityCriticalAttribute); internal static readonly AttributeDescription SecuritySafeCriticalAttribute = new AttributeDescription("System.Security", "SecuritySafeCriticalAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription DesignerGeneratedAttribute = new AttributeDescription("Microsoft.VisualBasic.CompilerServices", "DesignerGeneratedAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription MyGroupCollectionAttribute = new AttributeDescription("Microsoft.VisualBasic", "MyGroupCollectionAttribute", s_signaturesOfMyGroupCollectionAttribute); internal static readonly AttributeDescription ComEventInterfaceAttribute = new AttributeDescription("System.Runtime.InteropServices", "ComEventInterfaceAttribute", s_signaturesOfComEventInterfaceAttribute); internal static readonly AttributeDescription BestFitMappingAttribute = new AttributeDescription("System.Runtime.InteropServices", "BestFitMappingAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription FlagsAttribute = new AttributeDescription("System", "FlagsAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription LCIDConversionAttribute = new AttributeDescription("System.Runtime.InteropServices", "LCIDConversionAttribute", s_signaturesOfLCIDConversionAttribute); internal static readonly AttributeDescription UnmanagedFunctionPointerAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute", s_signaturesOfUnmanagedFunctionPointerAttribute); internal static readonly AttributeDescription PrimaryInteropAssemblyAttribute = new AttributeDescription("System.Runtime.InteropServices", "PrimaryInteropAssemblyAttribute", s_signaturesOfPrimaryInteropAssemblyAttribute); internal static readonly AttributeDescription ImportedFromTypeLibAttribute = new AttributeDescription("System.Runtime.InteropServices", "ImportedFromTypeLibAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription DefaultEventAttribute = new AttributeDescription("System.ComponentModel", "DefaultEventAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyConfigurationAttribute = new AttributeDescription("System.Reflection", "AssemblyConfigurationAttribute", s_signatures_HasThis_Void_String_Only); internal static readonly AttributeDescription AssemblyAlgorithmIdAttribute = new AttributeDescription("System.Reflection", "AssemblyAlgorithmIdAttribute", s_signaturesOfAssemblyAlgorithmIdAttribute); internal static readonly AttributeDescription DeprecatedAttribute = new AttributeDescription("Windows.Foundation.Metadata", "DeprecatedAttribute", s_signaturesOfDeprecatedAttribute); internal static readonly AttributeDescription NullableAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullableAttribute", s_signaturesOfNullableAttribute); internal static readonly AttributeDescription NullableContextAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullableContextAttribute", s_signaturesOfNullableContextAttribute); internal static readonly AttributeDescription NullablePublicOnlyAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NullablePublicOnlyAttribute", s_signatures_HasThis_Void_Boolean_Only); internal static readonly AttributeDescription ExperimentalAttribute = new AttributeDescription("Windows.Foundation.Metadata", "ExperimentalAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription ExcludeFromCodeCoverageAttribute = new AttributeDescription("System.Diagnostics.CodeAnalysis", "ExcludeFromCodeCoverageAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription EnumeratorCancellationAttribute = new AttributeDescription("System.Runtime.CompilerServices", "EnumeratorCancellationAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription SkipLocalsInitAttribute = new AttributeDescription("System.Runtime.CompilerServices", "SkipLocalsInitAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription NativeIntegerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "NativeIntegerAttribute", s_signaturesOfNativeIntegerAttribute); internal static readonly AttributeDescription ModuleInitializerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "ModuleInitializerAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription UnmanagedCallersOnlyAttribute = new AttributeDescription("System.Runtime.InteropServices", "UnmanagedCallersOnlyAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription InterpolatedStringHandlerAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InterpolatedStringHandlerAttribute", s_signatures_HasThis_Void_Only); internal static readonly AttributeDescription InterpolatedStringHandlerArgumentAttribute = new AttributeDescription("System.Runtime.CompilerServices", "InterpolatedStringHandlerArgumentAttribute", s_signaturesOfInterpolatedStringArgumentAttribute); } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/VisualStudio/Core/Def/EditorConfigSettings/Common/SettingsEntriesSnapshotBase.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.VisualStudio.Shell.TableControl; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal abstract class SettingsEntriesSnapshotBase<T> : WpfTableEntriesSnapshotBase { private readonly ImmutableArray<T> _data; private readonly int _currentVersionNumber; public SettingsEntriesSnapshotBase(ImmutableArray<T> data, int currentVersionNumber) { _data = data; _currentVersionNumber = currentVersionNumber; } public override int VersionNumber => _currentVersionNumber; public override int Count => _data.Length; public override bool TryGetValue(int index, string keyName, out object? content) { T? result; try { if (index < 0 || index > _data.Length) { content = null; return false; } result = _data[index]; if (result == null) { content = null; return false; } } catch (Exception) { content = null; return false; } return TryGetValue(result, keyName, out content); } protected abstract bool TryGetValue(T result, string keyName, out object? content); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.VisualStudio.Shell.TableControl; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { internal abstract class SettingsEntriesSnapshotBase<T> : WpfTableEntriesSnapshotBase { private readonly ImmutableArray<T> _data; private readonly int _currentVersionNumber; public SettingsEntriesSnapshotBase(ImmutableArray<T> data, int currentVersionNumber) { _data = data; _currentVersionNumber = currentVersionNumber; } public override int VersionNumber => _currentVersionNumber; public override int Count => _data.Length; public override bool TryGetValue(int index, string keyName, out object? content) { T? result; try { if (index < 0 || index > _data.Length) { content = null; return false; } result = _data[index]; if (result == null) { content = null; return false; } } catch (Exception) { content = null; return false; } return TryGetValue(result, keyName, out content); } protected abstract bool TryGetValue(T result, string keyName, out object? content); } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.Executor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// Return all cached local diagnostics (syntax, semantic) that belong to given document for the given StateSet (analyzer). /// Also returns empty diagnostics for suppressed analyzer. /// Returns null if the diagnostics need to be computed. /// </summary> private async Task<DocumentAnalysisData?> TryGetCachedDocumentAnalysisDataAsync( TextDocument document, StateSet stateSet, AnalysisKind kind, CancellationToken cancellationToken) { try { var version = await GetDiagnosticVersionAsync(document.Project, cancellationToken).ConfigureAwait(false); var state = stateSet.GetOrCreateActiveFileState(document.Id); var existingData = state.GetAnalysisData(kind); if (existingData.Version == version) { return existingData; } // Perf optimization: Check whether analyzer is suppressed and avoid getting diagnostics if suppressed. if (DiagnosticAnalyzerInfoCache.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project)) { return new DocumentAnalysisData(version, existingData.Items, ImmutableArray<DiagnosticData>.Empty); } return null; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Computes all local diagnostics (syntax, semantic) that belong to given document for the given StateSet (analyzer). /// </summary> private static async Task<DocumentAnalysisData> ComputeDocumentAnalysisDataAsync( DocumentAnalysisExecutor executor, StateSet stateSet, CancellationToken cancellationToken) { var kind = executor.AnalysisScope.Kind; var document = executor.AnalysisScope.TextDocument; // get log title and functionId GetLogFunctionIdAndTitle(kind, out var functionId, out var title); using (Logger.LogBlock(functionId, GetDocumentLogMessage, title, document, stateSet.Analyzer, cancellationToken)) { try { var diagnostics = await executor.ComputeDiagnosticsAsync(stateSet.Analyzer, cancellationToken).ConfigureAwait(false); // this is no-op in product. only run in test environment Logger.Log(functionId, (t, d, a, ds) => $"{GetDocumentLogMessage(t, d, a)}, {string.Join(Environment.NewLine, ds)}", title, document, stateSet.Analyzer, diagnostics); var version = await GetDiagnosticVersionAsync(document.Project, cancellationToken).ConfigureAwait(false); var state = stateSet.GetOrCreateActiveFileState(document.Id); var existingData = state.GetAnalysisData(kind); // we only care about local diagnostics return new DocumentAnalysisData(version, existingData.Items, diagnostics.ToImmutableArrayOrEmpty()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } /// <summary> /// Return all diagnostics that belong to given project for the given StateSets (analyzers) either from cache or by calculating them /// </summary> private async Task<ProjectAnalysisData> GetProjectAnalysisDataAsync( CompilationWithAnalyzers? compilationWithAnalyzers, Project project, IEnumerable<StateSet> stateSets, bool forceAnalyzerRun, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, project, stateSets, cancellationToken)) { try { // PERF: We need to flip this to false when we do actual diffing. var avoidLoadingData = true; var version = await GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false); var existingData = await ProjectAnalysisData.CreateAsync(project, stateSets, avoidLoadingData, cancellationToken).ConfigureAwait(false); // We can't return here if we have open file only analyzers since saved data for open file only analyzer // is incomplete -- it only contains info on open files rather than whole project. if (existingData.Version == version && !CompilationHasOpenFileOnlyAnalyzers(compilationWithAnalyzers, project.Solution.Options)) { return existingData; } // PERF: Check whether we want to analyze this project or not. if (!FullAnalysisEnabled(project, forceAnalyzerRun)) { Logger.Log(FunctionId.Diagnostics_ProjectDiagnostic, p => $"FSA off ({p.FilePath ?? p.Name})", project); return new ProjectAnalysisData(project.Id, VersionStamp.Default, existingData.Result, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty); } var result = await ComputeDiagnosticsAsync(compilationWithAnalyzers, project, stateSets, forceAnalyzerRun, existingData.Result, cancellationToken).ConfigureAwait(false); // If project is not loaded successfully, get rid of any semantic errors from compiler analyzer. // Note: In the past when project was not loaded successfully we did not run any analyzers on the project. // Now we run analyzers but filter out some information. So on such projects, there will be some perf degradation. result = await RemoveCompilerSemanticErrorsIfProjectNotLoadedAsync(result, project, cancellationToken).ConfigureAwait(false); return new ProjectAnalysisData(project.Id, version, existingData.Result, result); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } private static bool CompilationHasOpenFileOnlyAnalyzers(CompilationWithAnalyzers? compilationWithAnalyzers, OptionSet options) { if (compilationWithAnalyzers == null) { return false; } foreach (var analyzer in compilationWithAnalyzers.Analyzers) { if (analyzer.IsOpenFileOnly(options)) { return true; } } return false; } private static async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> RemoveCompilerSemanticErrorsIfProjectNotLoadedAsync( ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result, Project project, CancellationToken cancellationToken) { // see whether solution is loaded successfully var projectLoadedSuccessfully = await project.HasSuccessfullyLoadedAsync(cancellationToken).ConfigureAwait(false); if (projectLoadedSuccessfully) { return result; } var compilerAnalyzer = project.Solution.State.Analyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer == null) { // this language doesn't support compiler analyzer return result; } if (!result.TryGetValue(compilerAnalyzer, out var analysisResult)) { // no result from compiler analyzer return result; } Logger.Log(FunctionId.Diagnostics_ProjectDiagnostic, p => $"Failed to Load Successfully ({p.FilePath ?? p.Name})", project); // get rid of any result except syntax from compiler analyzer result var newCompilerAnalysisResult = analysisResult.DropExceptSyntax(); // return new result return result.SetItem(compilerAnalyzer, newCompilerAnalysisResult); } /// <summary> /// Calculate all diagnostics for a given project using analyzers referenced by the project and specified IDE analyzers. /// </summary> private async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> ComputeDiagnosticsAsync( CompilationWithAnalyzers? compilationWithAnalyzers, Project project, ImmutableArray<DiagnosticAnalyzer> ideAnalyzers, bool forcedAnalysis, CancellationToken cancellationToken) { try { var result = ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty; // can be null if given project doesn't support compilation. if (compilationWithAnalyzers?.Analyzers.Length > 0) { // calculate regular diagnostic analyzers diagnostics var resultMap = await _diagnosticAnalyzerRunner.AnalyzeProjectAsync(project, compilationWithAnalyzers, forcedAnalysis, logPerformanceInfo: true, getTelemetryInfo: true, cancellationToken).ConfigureAwait(false); result = resultMap.AnalysisResult; // record telemetry data UpdateAnalyzerTelemetryData(resultMap.TelemetryInfo); } // check whether there is IDE specific project diagnostic analyzer return await MergeProjectDiagnosticAnalyzerDiagnosticsAsync(project, ideAnalyzers, compilationWithAnalyzers?.Compilation, result, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> ComputeDiagnosticsAsync( CompilationWithAnalyzers? compilationWithAnalyzers, Project project, IEnumerable<StateSet> stateSets, bool forcedAnalysis, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> existing, CancellationToken cancellationToken) { try { // PERF: check whether we can reduce number of analyzers we need to run. // this can happen since caller could have created the driver with different set of analyzers that are different // than what we used to create the cache. var version = await GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false); var ideAnalyzers = stateSets.Select(s => s.Analyzer).Where(a => a is ProjectDiagnosticAnalyzer or DocumentDiagnosticAnalyzer).ToImmutableArrayOrEmpty(); if (compilationWithAnalyzers != null && TryReduceAnalyzersToRun(compilationWithAnalyzers, project, version, existing, out var analyzersToRun)) { // it looks like we can reduce the set. create new CompilationWithAnalyzer. // if we reduced to 0, we just pass in null for analyzer drvier. it could be reduced to 0 // since we might have up to date results for analyzers from compiler but not for // workspace analyzers. var compilationWithReducedAnalyzers = (analyzersToRun.Length == 0) ? null : await AnalyzerHelper.CreateCompilationWithAnalyzersAsync(project, analyzersToRun, compilationWithAnalyzers.AnalysisOptions.ReportSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); var result = await ComputeDiagnosticsAsync(compilationWithReducedAnalyzers, project, ideAnalyzers, forcedAnalysis, cancellationToken).ConfigureAwait(false); return MergeExistingDiagnostics(version, existing, result); } // we couldn't reduce the set. return await ComputeDiagnosticsAsync(compilationWithAnalyzers, project, ideAnalyzers, forcedAnalysis, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> MergeExistingDiagnostics( VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> existing, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result) { // quick bail out. if (existing.IsEmpty) { return result; } foreach (var (analyzer, results) in existing) { if (results.Version != version) { continue; } result = result.SetItem(analyzer, results); } return result; } private static bool TryReduceAnalyzersToRun( CompilationWithAnalyzers compilationWithAnalyzers, Project project, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> existing, out ImmutableArray<DiagnosticAnalyzer> analyzers) { analyzers = default; var options = project.Solution.Options; var existingAnalyzers = compilationWithAnalyzers.Analyzers; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); foreach (var analyzer in existingAnalyzers) { if (existing.TryGetValue(analyzer, out var analysisResult) && analysisResult.Version == version && !analyzer.IsOpenFileOnly(options)) { // we already have up to date result. continue; } // analyzer that is out of date. // open file only analyzer is always out of date for project wide data builder.Add(analyzer); } // all of analyzers are out of date. if (builder.Count == existingAnalyzers.Length) { return false; } analyzers = builder.ToImmutable(); return true; } private static async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> MergeProjectDiagnosticAnalyzerDiagnosticsAsync( Project project, ImmutableArray<DiagnosticAnalyzer> ideAnalyzers, Compilation? compilation, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result, CancellationToken cancellationToken) { try { var version = await GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false); var (fileLoadAnalysisResult, failedDocuments) = await GetDocumentLoadFailuresAsync(project, version, cancellationToken).ConfigureAwait(false); result = result.SetItem(FileContentLoadAnalyzer.Instance, fileLoadAnalysisResult); foreach (var analyzer in ideAnalyzers) { var builder = new DiagnosticAnalysisResultBuilder(project, version); switch (analyzer) { case DocumentDiagnosticAnalyzer documentAnalyzer: foreach (var document in project.Documents) { // don't analyze documents whose content failed to load if (failedDocuments == null || !failedDocuments.Contains(document)) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (tree != null) { builder.AddSyntaxDiagnostics(tree, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Syntax, compilation, cancellationToken).ConfigureAwait(false)); builder.AddSemanticDiagnostics(tree, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Semantic, compilation, cancellationToken).ConfigureAwait(false)); } else { builder.AddExternalSyntaxDiagnostics(document.Id, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Syntax, compilation, cancellationToken).ConfigureAwait(false)); builder.AddExternalSemanticDiagnostics(document.Id, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Semantic, compilation, cancellationToken).ConfigureAwait(false)); } } } break; case ProjectDiagnosticAnalyzer projectAnalyzer: builder.AddCompilationDiagnostics(await AnalyzerHelper.ComputeProjectDiagnosticAnalyzerDiagnosticsAsync(projectAnalyzer, project, compilation, cancellationToken).ConfigureAwait(false)); break; } // merge the result to existing one. // there can be existing one from compiler driver with empty set. overwrite it with // ide one. result = result.SetItem(analyzer, DiagnosticAnalysisResult.CreateFromBuilder(builder)); } return result; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static async Task<(DiagnosticAnalysisResult loadDiagnostics, ImmutableHashSet<Document>? failedDocuments)> GetDocumentLoadFailuresAsync(Project project, VersionStamp version, CancellationToken cancellationToken) { ImmutableHashSet<Document>.Builder? failedDocuments = null; ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Builder? lazyLoadDiagnostics = null; foreach (var document in project.Documents) { var loadDiagnostic = await document.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false); if (loadDiagnostic != null) { lazyLoadDiagnostics ??= ImmutableDictionary.CreateBuilder<DocumentId, ImmutableArray<DiagnosticData>>(); lazyLoadDiagnostics.Add(document.Id, ImmutableArray.Create(DiagnosticData.Create(loadDiagnostic, document))); failedDocuments ??= ImmutableHashSet.CreateBuilder<Document>(); failedDocuments.Add(document); } } var result = DiagnosticAnalysisResult.Create( project, version, syntaxLocalMap: lazyLoadDiagnostics?.ToImmutable() ?? ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty, semanticLocalMap: ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty, nonLocalMap: ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty, others: ImmutableArray<DiagnosticData>.Empty, documentIds: null); return (result, failedDocuments?.ToImmutable()); } private void UpdateAnalyzerTelemetryData(ImmutableDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> telemetry) { foreach (var (analyzer, telemetryInfo) in telemetry) { var isTelemetryCollectionAllowed = DiagnosticAnalyzerInfoCache.IsTelemetryCollectionAllowed(analyzer); _telemetry.UpdateAnalyzerActionsTelemetry(analyzer, telemetryInfo, isTelemetryCollectionAllowed); } } internal static bool FullAnalysisEnabled(Project project, bool forceAnalyzerRun) { if (forceAnalyzerRun) { // asked to ignore any checks. return true; } return SolutionCrawlerOptions.GetBackgroundAnalysisScope(project) == BackgroundAnalysisScope.FullSolution; } private static void GetLogFunctionIdAndTitle(AnalysisKind kind, out FunctionId functionId, out string title) { switch (kind) { case AnalysisKind.Syntax: functionId = FunctionId.Diagnostics_SyntaxDiagnostic; title = "syntax"; break; case AnalysisKind.Semantic: functionId = FunctionId.Diagnostics_SemanticDiagnostic; title = "semantic"; break; default: throw ExceptionUtilities.UnexpectedValue(kind); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// Return all cached local diagnostics (syntax, semantic) that belong to given document for the given StateSet (analyzer). /// Also returns empty diagnostics for suppressed analyzer. /// Returns null if the diagnostics need to be computed. /// </summary> private async Task<DocumentAnalysisData?> TryGetCachedDocumentAnalysisDataAsync( TextDocument document, StateSet stateSet, AnalysisKind kind, CancellationToken cancellationToken) { try { var version = await GetDiagnosticVersionAsync(document.Project, cancellationToken).ConfigureAwait(false); var state = stateSet.GetOrCreateActiveFileState(document.Id); var existingData = state.GetAnalysisData(kind); if (existingData.Version == version) { return existingData; } // Perf optimization: Check whether analyzer is suppressed and avoid getting diagnostics if suppressed. if (DiagnosticAnalyzerInfoCache.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project)) { return new DocumentAnalysisData(version, existingData.Items, ImmutableArray<DiagnosticData>.Empty); } return null; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Computes all local diagnostics (syntax, semantic) that belong to given document for the given StateSet (analyzer). /// </summary> private static async Task<DocumentAnalysisData> ComputeDocumentAnalysisDataAsync( DocumentAnalysisExecutor executor, StateSet stateSet, CancellationToken cancellationToken) { var kind = executor.AnalysisScope.Kind; var document = executor.AnalysisScope.TextDocument; // get log title and functionId GetLogFunctionIdAndTitle(kind, out var functionId, out var title); using (Logger.LogBlock(functionId, GetDocumentLogMessage, title, document, stateSet.Analyzer, cancellationToken)) { try { var diagnostics = await executor.ComputeDiagnosticsAsync(stateSet.Analyzer, cancellationToken).ConfigureAwait(false); // this is no-op in product. only run in test environment Logger.Log(functionId, (t, d, a, ds) => $"{GetDocumentLogMessage(t, d, a)}, {string.Join(Environment.NewLine, ds)}", title, document, stateSet.Analyzer, diagnostics); var version = await GetDiagnosticVersionAsync(document.Project, cancellationToken).ConfigureAwait(false); var state = stateSet.GetOrCreateActiveFileState(document.Id); var existingData = state.GetAnalysisData(kind); // we only care about local diagnostics return new DocumentAnalysisData(version, existingData.Items, diagnostics.ToImmutableArrayOrEmpty()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } /// <summary> /// Return all diagnostics that belong to given project for the given StateSets (analyzers) either from cache or by calculating them /// </summary> private async Task<ProjectAnalysisData> GetProjectAnalysisDataAsync( CompilationWithAnalyzers? compilationWithAnalyzers, Project project, IEnumerable<StateSet> stateSets, bool forceAnalyzerRun, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, project, stateSets, cancellationToken)) { try { // PERF: We need to flip this to false when we do actual diffing. var avoidLoadingData = true; var version = await GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false); var existingData = await ProjectAnalysisData.CreateAsync(project, stateSets, avoidLoadingData, cancellationToken).ConfigureAwait(false); // We can't return here if we have open file only analyzers since saved data for open file only analyzer // is incomplete -- it only contains info on open files rather than whole project. if (existingData.Version == version && !CompilationHasOpenFileOnlyAnalyzers(compilationWithAnalyzers, project.Solution.Options)) { return existingData; } // PERF: Check whether we want to analyze this project or not. if (!FullAnalysisEnabled(project, forceAnalyzerRun)) { Logger.Log(FunctionId.Diagnostics_ProjectDiagnostic, p => $"FSA off ({p.FilePath ?? p.Name})", project); return new ProjectAnalysisData(project.Id, VersionStamp.Default, existingData.Result, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty); } var result = await ComputeDiagnosticsAsync(compilationWithAnalyzers, project, stateSets, forceAnalyzerRun, existingData.Result, cancellationToken).ConfigureAwait(false); // If project is not loaded successfully, get rid of any semantic errors from compiler analyzer. // Note: In the past when project was not loaded successfully we did not run any analyzers on the project. // Now we run analyzers but filter out some information. So on such projects, there will be some perf degradation. result = await RemoveCompilerSemanticErrorsIfProjectNotLoadedAsync(result, project, cancellationToken).ConfigureAwait(false); return new ProjectAnalysisData(project.Id, version, existingData.Result, result); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } private static bool CompilationHasOpenFileOnlyAnalyzers(CompilationWithAnalyzers? compilationWithAnalyzers, OptionSet options) { if (compilationWithAnalyzers == null) { return false; } foreach (var analyzer in compilationWithAnalyzers.Analyzers) { if (analyzer.IsOpenFileOnly(options)) { return true; } } return false; } private static async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> RemoveCompilerSemanticErrorsIfProjectNotLoadedAsync( ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result, Project project, CancellationToken cancellationToken) { // see whether solution is loaded successfully var projectLoadedSuccessfully = await project.HasSuccessfullyLoadedAsync(cancellationToken).ConfigureAwait(false); if (projectLoadedSuccessfully) { return result; } var compilerAnalyzer = project.Solution.State.Analyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer == null) { // this language doesn't support compiler analyzer return result; } if (!result.TryGetValue(compilerAnalyzer, out var analysisResult)) { // no result from compiler analyzer return result; } Logger.Log(FunctionId.Diagnostics_ProjectDiagnostic, p => $"Failed to Load Successfully ({p.FilePath ?? p.Name})", project); // get rid of any result except syntax from compiler analyzer result var newCompilerAnalysisResult = analysisResult.DropExceptSyntax(); // return new result return result.SetItem(compilerAnalyzer, newCompilerAnalysisResult); } /// <summary> /// Calculate all diagnostics for a given project using analyzers referenced by the project and specified IDE analyzers. /// </summary> private async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> ComputeDiagnosticsAsync( CompilationWithAnalyzers? compilationWithAnalyzers, Project project, ImmutableArray<DiagnosticAnalyzer> ideAnalyzers, bool forcedAnalysis, CancellationToken cancellationToken) { try { var result = ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty; // can be null if given project doesn't support compilation. if (compilationWithAnalyzers?.Analyzers.Length > 0) { // calculate regular diagnostic analyzers diagnostics var resultMap = await _diagnosticAnalyzerRunner.AnalyzeProjectAsync(project, compilationWithAnalyzers, forcedAnalysis, logPerformanceInfo: true, getTelemetryInfo: true, cancellationToken).ConfigureAwait(false); result = resultMap.AnalysisResult; // record telemetry data UpdateAnalyzerTelemetryData(resultMap.TelemetryInfo); } // check whether there is IDE specific project diagnostic analyzer return await MergeProjectDiagnosticAnalyzerDiagnosticsAsync(project, ideAnalyzers, compilationWithAnalyzers?.Compilation, result, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> ComputeDiagnosticsAsync( CompilationWithAnalyzers? compilationWithAnalyzers, Project project, IEnumerable<StateSet> stateSets, bool forcedAnalysis, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> existing, CancellationToken cancellationToken) { try { // PERF: check whether we can reduce number of analyzers we need to run. // this can happen since caller could have created the driver with different set of analyzers that are different // than what we used to create the cache. var version = await GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false); var ideAnalyzers = stateSets.Select(s => s.Analyzer).Where(a => a is ProjectDiagnosticAnalyzer or DocumentDiagnosticAnalyzer).ToImmutableArrayOrEmpty(); if (compilationWithAnalyzers != null && TryReduceAnalyzersToRun(compilationWithAnalyzers, project, version, existing, out var analyzersToRun)) { // it looks like we can reduce the set. create new CompilationWithAnalyzer. // if we reduced to 0, we just pass in null for analyzer drvier. it could be reduced to 0 // since we might have up to date results for analyzers from compiler but not for // workspace analyzers. var compilationWithReducedAnalyzers = (analyzersToRun.Length == 0) ? null : await AnalyzerHelper.CreateCompilationWithAnalyzersAsync(project, analyzersToRun, compilationWithAnalyzers.AnalysisOptions.ReportSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); var result = await ComputeDiagnosticsAsync(compilationWithReducedAnalyzers, project, ideAnalyzers, forcedAnalysis, cancellationToken).ConfigureAwait(false); return MergeExistingDiagnostics(version, existing, result); } // we couldn't reduce the set. return await ComputeDiagnosticsAsync(compilationWithAnalyzers, project, ideAnalyzers, forcedAnalysis, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> MergeExistingDiagnostics( VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> existing, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result) { // quick bail out. if (existing.IsEmpty) { return result; } foreach (var (analyzer, results) in existing) { if (results.Version != version) { continue; } result = result.SetItem(analyzer, results); } return result; } private static bool TryReduceAnalyzersToRun( CompilationWithAnalyzers compilationWithAnalyzers, Project project, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> existing, out ImmutableArray<DiagnosticAnalyzer> analyzers) { analyzers = default; var options = project.Solution.Options; var existingAnalyzers = compilationWithAnalyzers.Analyzers; var builder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(); foreach (var analyzer in existingAnalyzers) { if (existing.TryGetValue(analyzer, out var analysisResult) && analysisResult.Version == version && !analyzer.IsOpenFileOnly(options)) { // we already have up to date result. continue; } // analyzer that is out of date. // open file only analyzer is always out of date for project wide data builder.Add(analyzer); } // all of analyzers are out of date. if (builder.Count == existingAnalyzers.Length) { return false; } analyzers = builder.ToImmutable(); return true; } private static async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>> MergeProjectDiagnosticAnalyzerDiagnosticsAsync( Project project, ImmutableArray<DiagnosticAnalyzer> ideAnalyzers, Compilation? compilation, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result, CancellationToken cancellationToken) { try { var version = await GetDiagnosticVersionAsync(project, cancellationToken).ConfigureAwait(false); var (fileLoadAnalysisResult, failedDocuments) = await GetDocumentLoadFailuresAsync(project, version, cancellationToken).ConfigureAwait(false); result = result.SetItem(FileContentLoadAnalyzer.Instance, fileLoadAnalysisResult); foreach (var analyzer in ideAnalyzers) { var builder = new DiagnosticAnalysisResultBuilder(project, version); switch (analyzer) { case DocumentDiagnosticAnalyzer documentAnalyzer: foreach (var document in project.Documents) { // don't analyze documents whose content failed to load if (failedDocuments == null || !failedDocuments.Contains(document)) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (tree != null) { builder.AddSyntaxDiagnostics(tree, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Syntax, compilation, cancellationToken).ConfigureAwait(false)); builder.AddSemanticDiagnostics(tree, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Semantic, compilation, cancellationToken).ConfigureAwait(false)); } else { builder.AddExternalSyntaxDiagnostics(document.Id, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Syntax, compilation, cancellationToken).ConfigureAwait(false)); builder.AddExternalSemanticDiagnostics(document.Id, await AnalyzerHelper.ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync(documentAnalyzer, document, AnalysisKind.Semantic, compilation, cancellationToken).ConfigureAwait(false)); } } } break; case ProjectDiagnosticAnalyzer projectAnalyzer: builder.AddCompilationDiagnostics(await AnalyzerHelper.ComputeProjectDiagnosticAnalyzerDiagnosticsAsync(projectAnalyzer, project, compilation, cancellationToken).ConfigureAwait(false)); break; } // merge the result to existing one. // there can be existing one from compiler driver with empty set. overwrite it with // ide one. result = result.SetItem(analyzer, DiagnosticAnalysisResult.CreateFromBuilder(builder)); } return result; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static async Task<(DiagnosticAnalysisResult loadDiagnostics, ImmutableHashSet<Document>? failedDocuments)> GetDocumentLoadFailuresAsync(Project project, VersionStamp version, CancellationToken cancellationToken) { ImmutableHashSet<Document>.Builder? failedDocuments = null; ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Builder? lazyLoadDiagnostics = null; foreach (var document in project.Documents) { var loadDiagnostic = await document.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false); if (loadDiagnostic != null) { lazyLoadDiagnostics ??= ImmutableDictionary.CreateBuilder<DocumentId, ImmutableArray<DiagnosticData>>(); lazyLoadDiagnostics.Add(document.Id, ImmutableArray.Create(DiagnosticData.Create(loadDiagnostic, document))); failedDocuments ??= ImmutableHashSet.CreateBuilder<Document>(); failedDocuments.Add(document); } } var result = DiagnosticAnalysisResult.Create( project, version, syntaxLocalMap: lazyLoadDiagnostics?.ToImmutable() ?? ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty, semanticLocalMap: ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty, nonLocalMap: ImmutableDictionary<DocumentId, ImmutableArray<DiagnosticData>>.Empty, others: ImmutableArray<DiagnosticData>.Empty, documentIds: null); return (result, failedDocuments?.ToImmutable()); } private void UpdateAnalyzerTelemetryData(ImmutableDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> telemetry) { foreach (var (analyzer, telemetryInfo) in telemetry) { var isTelemetryCollectionAllowed = DiagnosticAnalyzerInfoCache.IsTelemetryCollectionAllowed(analyzer); _telemetry.UpdateAnalyzerActionsTelemetry(analyzer, telemetryInfo, isTelemetryCollectionAllowed); } } internal static bool FullAnalysisEnabled(Project project, bool forceAnalyzerRun) { if (forceAnalyzerRun) { // asked to ignore any checks. return true; } return SolutionCrawlerOptions.GetBackgroundAnalysisScope(project) == BackgroundAnalysisScope.FullSolution; } private static void GetLogFunctionIdAndTitle(AnalysisKind kind, out FunctionId functionId, out string title) { switch (kind) { case AnalysisKind.Syntax: functionId = FunctionId.Diagnostics_SyntaxDiagnostic; title = "syntax"; break; case AnalysisKind.Semantic: functionId = FunctionId.Diagnostics_SemanticDiagnostic; title = "semantic"; break; default: throw ExceptionUtilities.UnexpectedValue(kind); } } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Storage; namespace Microsoft.CodeAnalysis.Host { internal class NoOpPersistentStorageService : IChecksummedPersistentStorageService { #if DOTNET_BUILD_FROM_SOURCE public static readonly IPersistentStorageService Instance = new NoOpPersistentStorageService(); #else private static readonly IPersistentStorageService Instance = new NoOpPersistentStorageService(); #endif private NoOpPersistentStorageService() { } public static IPersistentStorageService GetOrThrow(OptionSet optionSet) => optionSet.GetOption(StorageOptions.DatabaseMustSucceed) ? throw new InvalidOperationException("Database was not supported") : Instance; public IPersistentStorage GetStorage(Solution solution) => NoOpPersistentStorage.GetOrThrow(solution.Options); public ValueTask<IPersistentStorage> GetStorageAsync(Solution solution, CancellationToken cancellationToken) => new(NoOpPersistentStorage.GetOrThrow(solution.Options)); ValueTask<IChecksummedPersistentStorage> IChecksummedPersistentStorageService.GetStorageAsync(Solution solution, CancellationToken cancellationToken) => new(NoOpPersistentStorage.GetOrThrow(solution.Options)); ValueTask<IChecksummedPersistentStorage> IChecksummedPersistentStorageService.GetStorageAsync(Solution solution, bool checkBranchId, CancellationToken cancellationToken) => new(NoOpPersistentStorage.GetOrThrow(solution.Options)); ValueTask<IChecksummedPersistentStorage> IChecksummedPersistentStorageService.GetStorageAsync(Workspace workspace, SolutionKey solutionKey, bool checkBranchId, CancellationToken cancellationToken) => new(NoOpPersistentStorage.GetOrThrow(workspace.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. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Storage; namespace Microsoft.CodeAnalysis.Host { internal class NoOpPersistentStorageService : IChecksummedPersistentStorageService { #if DOTNET_BUILD_FROM_SOURCE public static readonly IPersistentStorageService Instance = new NoOpPersistentStorageService(); #else private static readonly IPersistentStorageService Instance = new NoOpPersistentStorageService(); #endif private NoOpPersistentStorageService() { } public static IPersistentStorageService GetOrThrow(OptionSet optionSet) => optionSet.GetOption(StorageOptions.DatabaseMustSucceed) ? throw new InvalidOperationException("Database was not supported") : Instance; public IPersistentStorage GetStorage(Solution solution) => NoOpPersistentStorage.GetOrThrow(solution.Options); public ValueTask<IPersistentStorage> GetStorageAsync(Solution solution, CancellationToken cancellationToken) => new(NoOpPersistentStorage.GetOrThrow(solution.Options)); ValueTask<IChecksummedPersistentStorage> IChecksummedPersistentStorageService.GetStorageAsync(Solution solution, CancellationToken cancellationToken) => new(NoOpPersistentStorage.GetOrThrow(solution.Options)); ValueTask<IChecksummedPersistentStorage> IChecksummedPersistentStorageService.GetStorageAsync(Solution solution, bool checkBranchId, CancellationToken cancellationToken) => new(NoOpPersistentStorage.GetOrThrow(solution.Options)); ValueTask<IChecksummedPersistentStorage> IChecksummedPersistentStorageService.GetStorageAsync(Workspace workspace, SolutionKey solutionKey, bool checkBranchId, CancellationToken cancellationToken) => new(NoOpPersistentStorage.GetOrThrow(workspace.Options)); } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Workspaces/Core/MSBuild/MSBuild/ProjectLoadProgress.cs
// Licensed to the .NET Foundation under one or more 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.MSBuild { /// <summary> /// Provides details as a project is loaded. /// </summary> public struct ProjectLoadProgress { /// <summary> /// The project for which progress is being reported. /// </summary> public string FilePath { get; } /// <summary> /// The operation that has just completed. /// </summary> public ProjectLoadOperation Operation { get; } /// <summary> /// The target framework of the project being built or resolved. This property is only valid for SDK-style projects /// during the <see cref="ProjectLoadOperation.Resolve"/> operation. /// </summary> public string? TargetFramework { get; } /// <summary> /// The amount of time elapsed for this operation. /// </summary> public TimeSpan ElapsedTime { get; } internal ProjectLoadProgress(string filePath, ProjectLoadOperation operation, string? targetFramework, TimeSpan elapsedTime) { FilePath = filePath; Operation = operation; TargetFramework = targetFramework; ElapsedTime = elapsedTime; } } }
// Licensed to the .NET Foundation under one or more 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.MSBuild { /// <summary> /// Provides details as a project is loaded. /// </summary> public struct ProjectLoadProgress { /// <summary> /// The project for which progress is being reported. /// </summary> public string FilePath { get; } /// <summary> /// The operation that has just completed. /// </summary> public ProjectLoadOperation Operation { get; } /// <summary> /// The target framework of the project being built or resolved. This property is only valid for SDK-style projects /// during the <see cref="ProjectLoadOperation.Resolve"/> operation. /// </summary> public string? TargetFramework { get; } /// <summary> /// The amount of time elapsed for this operation. /// </summary> public TimeSpan ElapsedTime { get; } internal ProjectLoadProgress(string filePath, ProjectLoadOperation operation, string? targetFramework, TimeSpan elapsedTime) { FilePath = filePath; Operation = operation; TargetFramework = targetFramework; ElapsedTime = elapsedTime; } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Features/Core/Portable/ChangeSignature/IChangeSignatureOptionsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ChangeSignature { internal interface IChangeSignatureOptionsService : IWorkspaceService { /// <summary> /// Gets options and produces a <see cref="SignatureChange"/> if successful. /// </summary> /// <param name="document">the context document</param> /// <param name="positionForTypeBinding">the position in the document with /// the signature of the method, used for binding types (e.g. for added /// parameters)</param> /// <param name="symbol">the symbol for changing the signature</param> /// <param name="parameters">existing parameters of the symbol</param> /// <returns></returns> ChangeSignatureOptionsResult? GetChangeSignatureOptions( Document document, int positionForTypeBinding, ISymbol symbol, ParameterConfiguration parameters); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ChangeSignature { internal interface IChangeSignatureOptionsService : IWorkspaceService { /// <summary> /// Gets options and produces a <see cref="SignatureChange"/> if successful. /// </summary> /// <param name="document">the context document</param> /// <param name="positionForTypeBinding">the position in the document with /// the signature of the method, used for binding types (e.g. for added /// parameters)</param> /// <param name="symbol">the symbol for changing the signature</param> /// <param name="parameters">existing parameters of the symbol</param> /// <returns></returns> ChangeSignatureOptionsResult? GetChangeSignatureOptions( Document document, int positionForTypeBinding, ISymbol symbol, ParameterConfiguration parameters); } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DiagnosticStartAnalysisScope.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for code within a symbol and its members. /// </summary> internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSymbolStartAnalysisScope _scope; internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) : base(owningSymbol, compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolEndAction(_analyzer, action); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions.IsEmpty) { return compilationActions; } if (compilationActions.IsEmpty) { return sessionActions; } return compilationActions.Append(in sessionActions); } } /// <summary> /// Scope for setting up analyzers for analyzing a symbol and its members. /// </summary> internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope { public HostSymbolStartAnalysisScope() { } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>(); public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { return this.GetOrCreateAnalyzerActions(analyzer).Value; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction); } public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action) { var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction); } public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action) { var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction); } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction); } protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty)); } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal struct AnalyzerActions { public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false); private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions; private ImmutableArray<CompilationAnalyzerAction> _compilationActions; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions; private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions; private ImmutableArray<SymbolAnalyzerAction> _symbolActions; private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions; private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions; private ImmutableArray<AnalyzerAction> _codeBlockStartActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions; private ImmutableArray<AnalyzerAction> _syntaxNodeActions; private ImmutableArray<OperationAnalyzerAction> _operationActions; private bool _concurrent; internal AnalyzerActions(bool concurrent) { _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; _additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty; _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; _symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty; _symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty; _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; _concurrent = concurrent; IsEmpty = true; } public AnalyzerActions( ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions, ImmutableArray<CompilationAnalyzerAction> compilationEndActions, ImmutableArray<CompilationAnalyzerAction> compilationActions, ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions, ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions, ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions, ImmutableArray<SymbolAnalyzerAction> symbolActions, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, ImmutableArray<AnalyzerAction> codeBlockStartActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions, ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions, ImmutableArray<AnalyzerAction> syntaxNodeActions, ImmutableArray<OperationAnalyzerAction> operationActions, bool concurrent, bool isEmpty) { _compilationStartActions = compilationStartActions; _compilationEndActions = compilationEndActions; _compilationActions = compilationActions; _syntaxTreeActions = syntaxTreeActions; _additionalFileActions = additionalFileActions; _semanticModelActions = semanticModelActions; _symbolActions = symbolActions; _symbolStartActions = symbolStartActions; _symbolEndActions = symbolEndActions; _codeBlockStartActions = codeBlockStartActions; _codeBlockEndActions = codeBlockEndActions; _codeBlockActions = codeBlockActions; _operationBlockStartActions = operationBlockStartActions; _operationBlockEndActions = operationBlockEndActions; _operationBlockActions = operationBlockActions; _syntaxNodeActions = syntaxNodeActions; _operationActions = operationActions; _concurrent = concurrent; IsEmpty = isEmpty; } public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public readonly int CompilationActionsCount { get { return _compilationActions.Length; } } public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } } public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public readonly int SymbolActionsCount { get { return _symbolActions.Length; } } public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } } public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } } public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public readonly int OperationActionsCount { get { return _operationActions.Length; } } public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public readonly bool Concurrent => _concurrent; public bool IsEmpty { readonly get; private set; } public readonly bool IsDefault => _compilationStartActions.IsDefault; internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions { get { return _additionalFileActions; } } internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions { get { return _symbolStartActions; } } internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions { get { return _symbolEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct { var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance(); foreach (var action in _syntaxNodeActions) { if (action.Analyzer == analyzer && action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction) { builder.Add(syntaxNodeAction); } } return builder.ToImmutableAndFree(); } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); IsEmpty = false; } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); IsEmpty = false; } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); IsEmpty = false; } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); IsEmpty = false; } internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) { _additionalFileActions = _additionalFileActions.Add(action); IsEmpty = false; } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); IsEmpty = false; } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); IsEmpty = false; } internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) { _symbolStartActions = _symbolStartActions.Add(action); IsEmpty = false; } internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) { _symbolEndActions = _symbolEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); IsEmpty = false; } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); IsEmpty = false; } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); IsEmpty = false; } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); IsEmpty = false; } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); IsEmpty = false; } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); IsEmpty = false; } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); IsEmpty = false; } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) { if (otherActions.IsDefault) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions; actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions; actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions.IsEmpty = IsEmpty && otherActions.IsEmpty; return actions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterAdditionalFileAction(Action<AdditionalFileAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterAdditionalFileAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterSymbolStartAction(Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolStartAction(_analyzer, action, symbolKind); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, [MaybeNullWhen(false)] out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for code within a symbol and its members. /// </summary> internal sealed class AnalyzerSymbolStartAnalysisContext : SymbolStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSymbolStartAnalysisScope _scope; internal AnalyzerSymbolStartAnalysisContext(DiagnosticAnalyzer analyzer, HostSymbolStartAnalysisScope scope, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, CancellationToken cancellationToken) : base(owningSymbol, compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterSymbolEndAction(Action<SymbolAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSymbolEndAction(_analyzer, action); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private readonly ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationStartAction(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).Value.EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions.IsEmpty) { return compilationActions; } if (compilationActions.IsEmpty) { return sessionActions; } return compilationActions.Append(in sessionActions); } } /// <summary> /// Scope for setting up analyzers for analyzing a symbol and its members. /// </summary> internal sealed class HostSymbolStartAnalysisScope : HostAnalysisScope { public HostSymbolStartAnalysisScope() { } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private readonly ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>> _analyzerActions = new ConcurrentDictionary<DiagnosticAnalyzer, StrongBox<AnalyzerActions>>(); public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { return this.GetOrCreateAnalyzerActions(analyzer).Value; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationAction(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCompilationEndAction(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSemanticModelAction(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxTreeAction(analyzerAction); } public void RegisterAdditionalFileAction(DiagnosticAnalyzer analyzer, Action<AdditionalFileAnalysisContext> action) { var analyzerAction = new AdditionalFileAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddAdditionalFileAction(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolAction(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterSymbolStartAction(DiagnosticAnalyzer analyzer, Action<SymbolStartAnalysisContext> action, SymbolKind symbolKind) { var analyzerAction = new SymbolStartAnalyzerAction(action, symbolKind, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolStartAction(analyzerAction); } public void RegisterSymbolEndAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action) { var analyzerAction = new SymbolEndAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSymbolEndAction(analyzerAction); } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockStartAction(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockEndAction(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddCodeBlockAction(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddSyntaxNodeAction(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockStartAction(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockEndAction(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationBlockAction(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).Value.AddOperationAction(analyzerAction); } protected StrongBox<AnalyzerActions> GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { return _analyzerActions.GetOrAdd(analyzer, _ => new StrongBox<AnalyzerActions>(AnalyzerActions.Empty)); } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal struct AnalyzerActions { public static readonly AnalyzerActions Empty = new AnalyzerActions(concurrent: false); private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions; private ImmutableArray<CompilationAnalyzerAction> _compilationActions; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions; private ImmutableArray<AdditionalFileAnalyzerAction> _additionalFileActions; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions; private ImmutableArray<SymbolAnalyzerAction> _symbolActions; private ImmutableArray<SymbolStartAnalyzerAction> _symbolStartActions; private ImmutableArray<SymbolEndAnalyzerAction> _symbolEndActions; private ImmutableArray<AnalyzerAction> _codeBlockStartActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions; private ImmutableArray<AnalyzerAction> _syntaxNodeActions; private ImmutableArray<OperationAnalyzerAction> _operationActions; private bool _concurrent; internal AnalyzerActions(bool concurrent) { _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; _additionalFileActions = ImmutableArray<AdditionalFileAnalyzerAction>.Empty; _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; _symbolStartActions = ImmutableArray<SymbolStartAnalyzerAction>.Empty; _symbolEndActions = ImmutableArray<SymbolEndAnalyzerAction>.Empty; _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; _concurrent = concurrent; IsEmpty = true; } public AnalyzerActions( ImmutableArray<CompilationStartAnalyzerAction> compilationStartActions, ImmutableArray<CompilationAnalyzerAction> compilationEndActions, ImmutableArray<CompilationAnalyzerAction> compilationActions, ImmutableArray<SyntaxTreeAnalyzerAction> syntaxTreeActions, ImmutableArray<AdditionalFileAnalyzerAction> additionalFileActions, ImmutableArray<SemanticModelAnalyzerAction> semanticModelActions, ImmutableArray<SymbolAnalyzerAction> symbolActions, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, ImmutableArray<AnalyzerAction> codeBlockStartActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockEndActions, ImmutableArray<CodeBlockAnalyzerAction> codeBlockActions, ImmutableArray<OperationBlockStartAnalyzerAction> operationBlockStartActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockEndActions, ImmutableArray<OperationBlockAnalyzerAction> operationBlockActions, ImmutableArray<AnalyzerAction> syntaxNodeActions, ImmutableArray<OperationAnalyzerAction> operationActions, bool concurrent, bool isEmpty) { _compilationStartActions = compilationStartActions; _compilationEndActions = compilationEndActions; _compilationActions = compilationActions; _syntaxTreeActions = syntaxTreeActions; _additionalFileActions = additionalFileActions; _semanticModelActions = semanticModelActions; _symbolActions = symbolActions; _symbolStartActions = symbolStartActions; _symbolEndActions = symbolEndActions; _codeBlockStartActions = codeBlockStartActions; _codeBlockEndActions = codeBlockEndActions; _codeBlockActions = codeBlockActions; _operationBlockStartActions = operationBlockStartActions; _operationBlockEndActions = operationBlockEndActions; _operationBlockActions = operationBlockActions; _syntaxNodeActions = syntaxNodeActions; _operationActions = operationActions; _concurrent = concurrent; IsEmpty = isEmpty; } public readonly int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public readonly int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public readonly int CompilationActionsCount { get { return _compilationActions.Length; } } public readonly int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public readonly int AdditionalFileActionsCount { get { return _additionalFileActions.Length; } } public readonly int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public readonly int SymbolActionsCount { get { return _symbolActions.Length; } } public readonly int SymbolStartActionsCount { get { return _symbolStartActions.Length; } } public readonly int SymbolEndActionsCount { get { return _symbolEndActions.Length; } } public readonly int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public readonly int OperationActionsCount { get { return _operationActions.Length; } } public readonly int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public readonly int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public readonly int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public readonly int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public readonly int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public readonly int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public readonly bool Concurrent => _concurrent; public bool IsEmpty { readonly get; private set; } public readonly bool IsDefault => _compilationStartActions.IsDefault; internal readonly ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal readonly ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal readonly ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal readonly ImmutableArray<AdditionalFileAnalyzerAction> AdditionalFileActions { get { return _additionalFileActions; } } internal readonly ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal readonly ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal readonly ImmutableArray<SymbolStartAnalyzerAction> SymbolStartActions { get { return _symbolStartActions; } } internal readonly ImmutableArray<SymbolEndAnalyzerAction> SymbolEndActions { get { return _symbolEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal readonly ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal readonly ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal readonly ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>(DiagnosticAnalyzer analyzer) where TLanguageKindEnum : struct { var builder = ArrayBuilder<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.GetInstance(); foreach (var action in _syntaxNodeActions) { if (action.Analyzer == analyzer && action is SyntaxNodeAnalyzerAction<TLanguageKindEnum> syntaxNodeAction) { builder.Add(syntaxNodeAction); } } return builder.ToImmutableAndFree(); } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal readonly ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal readonly ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal readonly ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); IsEmpty = false; } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); IsEmpty = false; } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); IsEmpty = false; } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); IsEmpty = false; } internal void AddAdditionalFileAction(AdditionalFileAnalyzerAction action) { _additionalFileActions = _additionalFileActions.Add(action); IsEmpty = false; } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); IsEmpty = false; } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); IsEmpty = false; } internal void AddSymbolStartAction(SymbolStartAnalyzerAction action) { _symbolStartActions = _symbolStartActions.Add(action); IsEmpty = false; } internal void AddSymbolEndAction(SymbolEndAnalyzerAction action) { _symbolEndActions = _symbolEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); IsEmpty = false; } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); IsEmpty = false; } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); IsEmpty = false; } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); IsEmpty = false; } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); IsEmpty = false; } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); IsEmpty = false; } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); IsEmpty = false; } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); IsEmpty = false; } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public readonly AnalyzerActions Append(in AnalyzerActions otherActions, bool appendSymbolStartAndSymbolEndActions = true) { if (otherActions.IsDefault) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(concurrent: _concurrent || otherActions.Concurrent); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._additionalFileActions = _additionalFileActions.AddRange(otherActions._additionalFileActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._symbolStartActions = appendSymbolStartAndSymbolEndActions ? _symbolStartActions.AddRange(otherActions._symbolStartActions) : _symbolStartActions; actions._symbolEndActions = appendSymbolStartAndSymbolEndActions ? _symbolEndActions.AddRange(otherActions._symbolEndActions) : _symbolEndActions; actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions.IsEmpty = IsEmpty && otherActions.IsEmpty; return actions; } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MethodContextReuseConstraintsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class MethodContextReuseConstraintsTests : ExpressionCompilerTestBase { [Fact] public void AreSatisfied() { var moduleVersionId = Guid.NewGuid(); const int methodToken = 0x06000001; const int methodVersion = 1; const uint startOffset = 1; const uint endOffsetExclusive = 3; var constraints = new MethodContextReuseConstraints( moduleVersionId, methodToken, methodVersion, new ILSpan(startOffset, endOffsetExclusive)); Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset)); Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive - 1)); Assert.False(constraints.AreSatisfied(Guid.NewGuid(), methodToken, methodVersion, (int)startOffset)); Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken + 1, methodVersion, (int)startOffset)); Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion + 1, (int)startOffset)); Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset - 1)); Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive)); } [Fact] public void EndExclusive() { var spans = new[] { new ILSpan(0u, uint.MaxValue), new ILSpan(1, 9), new ILSpan(2, 8), new ILSpan(1, 3), new ILSpan(7, 9), }; Assert.Equal(new ILSpan(0u, uint.MaxValue), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(1))); Assert.Equal(new ILSpan(1, 9), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(2))); Assert.Equal(new ILSpan(2, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(3))); Assert.Equal(new ILSpan(3, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(4))); Assert.Equal(new ILSpan(3, 7), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(5))); } [Fact] public void Cumulative() { var span = ILSpan.MaxValue; span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new ILSpan[0]); Assert.Equal(new ILSpan(0u, uint.MaxValue), span); span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 10) }); Assert.Equal(new ILSpan(1, 10), span); span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(2, 9) }); Assert.Equal(new ILSpan(2, 9), span); span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 3) }); Assert.Equal(new ILSpan(3, 9), span); span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(7, 9) }); Assert.Equal(new ILSpan(3, 7), span); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class MethodContextReuseConstraintsTests : ExpressionCompilerTestBase { [Fact] public void AreSatisfied() { var moduleVersionId = Guid.NewGuid(); const int methodToken = 0x06000001; const int methodVersion = 1; const uint startOffset = 1; const uint endOffsetExclusive = 3; var constraints = new MethodContextReuseConstraints( moduleVersionId, methodToken, methodVersion, new ILSpan(startOffset, endOffsetExclusive)); Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset)); Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive - 1)); Assert.False(constraints.AreSatisfied(Guid.NewGuid(), methodToken, methodVersion, (int)startOffset)); Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken + 1, methodVersion, (int)startOffset)); Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion + 1, (int)startOffset)); Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset - 1)); Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive)); } [Fact] public void EndExclusive() { var spans = new[] { new ILSpan(0u, uint.MaxValue), new ILSpan(1, 9), new ILSpan(2, 8), new ILSpan(1, 3), new ILSpan(7, 9), }; Assert.Equal(new ILSpan(0u, uint.MaxValue), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(1))); Assert.Equal(new ILSpan(1, 9), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(2))); Assert.Equal(new ILSpan(2, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(3))); Assert.Equal(new ILSpan(3, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(4))); Assert.Equal(new ILSpan(3, 7), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(5))); } [Fact] public void Cumulative() { var span = ILSpan.MaxValue; span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new ILSpan[0]); Assert.Equal(new ILSpan(0u, uint.MaxValue), span); span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 10) }); Assert.Equal(new ILSpan(1, 10), span); span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(2, 9) }); Assert.Equal(new ILSpan(2, 9), span); span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 3) }); Assert.Equal(new ILSpan(3, 9), span); span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(7, 9) }); Assert.Equal(new ILSpan(3, 7), span); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Features/Core/Portable/Notification/NotificationSeverity.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Notification { internal enum NotificationSeverity { Information, Warning, Error } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Notification { internal enum NotificationSeverity { Information, Warning, Error } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpDeclarationComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal class CSharpDeclarationComparer : IComparer<SyntaxNode> { private static readonly Dictionary<SyntaxKind, int> s_kindPrecedenceMap = new(SyntaxFacts.EqualityComparer) { { SyntaxKind.FieldDeclaration, 0 }, { SyntaxKind.ConstructorDeclaration, 1 }, { SyntaxKind.DestructorDeclaration, 2 }, { SyntaxKind.IndexerDeclaration, 3 }, { SyntaxKind.PropertyDeclaration, 4 }, { SyntaxKind.EventFieldDeclaration, 5 }, { SyntaxKind.EventDeclaration, 6 }, { SyntaxKind.MethodDeclaration, 7 }, { SyntaxKind.OperatorDeclaration, 8 }, { SyntaxKind.ConversionOperatorDeclaration, 9 }, { SyntaxKind.EnumDeclaration, 10 }, { SyntaxKind.InterfaceDeclaration, 11 }, { SyntaxKind.StructDeclaration, 12 }, { SyntaxKind.ClassDeclaration, 13 }, { SyntaxKind.RecordDeclaration, 14 }, { SyntaxKind.RecordStructDeclaration, 15 }, { SyntaxKind.DelegateDeclaration, 16 } }; private static readonly Dictionary<SyntaxKind, int> s_operatorPrecedenceMap = new(SyntaxFacts.EqualityComparer) { { SyntaxKind.PlusToken, 0 }, { SyntaxKind.MinusToken, 1 }, { SyntaxKind.ExclamationToken, 2 }, { SyntaxKind.TildeToken, 3 }, { SyntaxKind.PlusPlusToken, 4 }, { SyntaxKind.MinusMinusToken, 5 }, { SyntaxKind.AsteriskToken, 6 }, { SyntaxKind.SlashToken, 7 }, { SyntaxKind.PercentToken, 8 }, { SyntaxKind.AmpersandToken, 9 }, { SyntaxKind.BarToken, 10 }, { SyntaxKind.CaretToken, 11 }, { SyntaxKind.LessThanLessThanToken, 12 }, { SyntaxKind.GreaterThanGreaterThanToken, 13 }, { SyntaxKind.EqualsEqualsToken, 14 }, { SyntaxKind.ExclamationEqualsToken, 15 }, { SyntaxKind.LessThanToken, 16 }, { SyntaxKind.GreaterThanToken, 17 }, { SyntaxKind.LessThanEqualsToken, 18 }, { SyntaxKind.GreaterThanEqualsToken, 19 }, { SyntaxKind.TrueKeyword, 20 }, { SyntaxKind.FalseKeyword, 21 }, }; public static readonly CSharpDeclarationComparer WithNamesInstance = new(includeName: true); public static readonly CSharpDeclarationComparer WithoutNamesInstance = new(includeName: false); private readonly bool _includeName; private CSharpDeclarationComparer(bool includeName) => _includeName = includeName; public int Compare(SyntaxNode x, SyntaxNode y) { if (x.Kind() != y.Kind()) { if (!s_kindPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence) || !s_kindPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence)) { // The containing declaration is malformed and contains a node kind we did not expect. // Ignore comparisons with those unexpected nodes and sort them to the end of the declaration. return 1; } return xPrecedence < yPrecedence ? -1 : 1; } switch (x.Kind()) { case SyntaxKind.DelegateDeclaration: return Compare((DelegateDeclarationSyntax)x, (DelegateDeclarationSyntax)y); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return Compare((BaseFieldDeclarationSyntax)x, (BaseFieldDeclarationSyntax)y); case SyntaxKind.ConstructorDeclaration: return Compare((ConstructorDeclarationSyntax)x, (ConstructorDeclarationSyntax)y); case SyntaxKind.DestructorDeclaration: // All destructors are equal since there can only be one per named type return 0; case SyntaxKind.MethodDeclaration: return Compare((MethodDeclarationSyntax)x, (MethodDeclarationSyntax)y); case SyntaxKind.OperatorDeclaration: return Compare((OperatorDeclarationSyntax)x, (OperatorDeclarationSyntax)y); case SyntaxKind.EventDeclaration: return Compare((EventDeclarationSyntax)x, (EventDeclarationSyntax)y); case SyntaxKind.IndexerDeclaration: return Compare((IndexerDeclarationSyntax)x, (IndexerDeclarationSyntax)y); case SyntaxKind.PropertyDeclaration: return Compare((PropertyDeclarationSyntax)x, (PropertyDeclarationSyntax)y); case SyntaxKind.EnumDeclaration: return Compare((EnumDeclarationSyntax)x, (EnumDeclarationSyntax)y); case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return Compare((BaseTypeDeclarationSyntax)x, (BaseTypeDeclarationSyntax)y); case SyntaxKind.ConversionOperatorDeclaration: return Compare((ConversionOperatorDeclarationSyntax)x, (ConversionOperatorDeclarationSyntax)y); case SyntaxKind.IncompleteMember: // Since these are incomplete members they are considered to be equal return 0; case SyntaxKind.GlobalStatement: // for REPL, don't mess with order, just put new one at the end. return 1; default: throw ExceptionUtilities.UnexpectedValue(x.Kind()); } } private int Compare(DelegateDeclarationSyntax x, DelegateDeclarationSyntax y) { if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private int Compare(BaseFieldDeclarationSyntax x, BaseFieldDeclarationSyntax y) { if (EqualConstness(x.Modifiers, y.Modifiers, out var result) && EqualStaticness(x.Modifiers, y.Modifiers, out result) && EqualReadOnlyness(x.Modifiers, y.Modifiers, out result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (_includeName) { EqualIdentifierName( x.Declaration.Variables.FirstOrDefault().Identifier, y.Declaration.Variables.FirstOrDefault().Identifier, out result); } } return result; } private static int Compare(ConstructorDeclarationSyntax x, ConstructorDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { EqualParameterCount(x.ParameterList, y.ParameterList, out result); } return result; } private int Compare(MethodDeclarationSyntax x, MethodDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (!_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private static int Compare(ConversionOperatorDeclarationSyntax x, ConversionOperatorDeclarationSyntax y) { if (x.ImplicitOrExplicitKeyword.Kind() != y.ImplicitOrExplicitKeyword.Kind()) { return x.ImplicitOrExplicitKeyword.Kind() == SyntaxKind.ImplicitKeyword ? -1 : 1; } EqualParameterCount(x.ParameterList, y.ParameterList, out var result); return result; } private static int Compare(OperatorDeclarationSyntax x, OperatorDeclarationSyntax y) { if (EqualOperatorPrecedence(x.OperatorToken, y.OperatorToken, out var result)) { EqualParameterCount(x.ParameterList, y.ParameterList, out result); } return result; } private int Compare(EventDeclarationSyntax x, EventDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private static int Compare(IndexerDeclarationSyntax x, IndexerDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { EqualParameterCount(x.ParameterList, y.ParameterList, out result); } return result; } private int Compare(PropertyDeclarationSyntax x, PropertyDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private int Compare(EnumDeclarationSyntax x, EnumDeclarationSyntax y) { if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private int Compare(BaseTypeDeclarationSyntax x, BaseTypeDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private static bool NeitherNull(object x, object y, out int comparisonResult) { if (x == null && y == null) { comparisonResult = 0; return false; } else if (x == null) { // x == null && y != null comparisonResult = -1; return false; } else if (y == null) { // x != null && y == null comparisonResult = 1; return false; } else { // x != null && y != null comparisonResult = 0; return true; } } private static bool ContainsToken(SyntaxTokenList list, SyntaxKind kind) => list.Contains(token => token.Kind() == kind); private enum Accessibility { Public, Protected, ProtectedInternal, Internal, PrivateProtected, Private } private static int GetAccessibilityPrecedence(SyntaxTokenList modifiers, SyntaxNode parent) { if (ContainsToken(modifiers, SyntaxKind.PublicKeyword)) { return (int)Accessibility.Public; } else if (ContainsToken(modifiers, SyntaxKind.ProtectedKeyword)) { if (ContainsToken(modifiers, SyntaxKind.InternalKeyword)) { return (int)Accessibility.ProtectedInternal; } if (ContainsToken(modifiers, SyntaxKind.PrivateKeyword)) { return (int)Accessibility.PrivateProtected; } return (int)Accessibility.Protected; } else if (ContainsToken(modifiers, SyntaxKind.InternalKeyword)) { return (int)Accessibility.Internal; } else if (ContainsToken(modifiers, SyntaxKind.PrivateKeyword)) { return (int)Accessibility.Private; } // Determine default accessibility: This declaration is internal if we traverse up // the syntax tree and don't find a containing named type. for (var node = parent; node != null; node = node.Parent) { if (node.Kind() == SyntaxKind.InterfaceDeclaration) { // All interface members are public return (int)Accessibility.Public; } else if (node.Kind() is SyntaxKind.StructDeclaration or SyntaxKind.ClassDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration) { // Members and nested types default to private return (int)Accessibility.Private; } } return (int)Accessibility.Internal; } private static bool BothHaveModifier(SyntaxTokenList x, SyntaxTokenList y, SyntaxKind modifierKind, out int comparisonResult) { var xHasModifier = ContainsToken(x, modifierKind); var yHasModifier = ContainsToken(y, modifierKind); if (xHasModifier == yHasModifier) { comparisonResult = 0; return true; } comparisonResult = xHasModifier ? -1 : 1; return false; } private static bool EqualStaticness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult) => BothHaveModifier(x, y, SyntaxKind.StaticKeyword, out comparisonResult); private static bool EqualConstness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult) => BothHaveModifier(x, y, SyntaxKind.ConstKeyword, out comparisonResult); private static bool EqualReadOnlyness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult) => BothHaveModifier(x, y, SyntaxKind.ReadOnlyKeyword, out comparisonResult); private static bool EqualAccessibility(SyntaxNode x, SyntaxTokenList xModifiers, SyntaxNode y, SyntaxTokenList yModifiers, out int comparisonResult) { var xAccessibility = GetAccessibilityPrecedence(xModifiers, x.Parent ?? y.Parent); var yAccessibility = GetAccessibilityPrecedence(yModifiers, y.Parent ?? x.Parent); comparisonResult = xAccessibility - yAccessibility; return comparisonResult == 0; } private static bool EqualIdentifierName(SyntaxToken x, SyntaxToken y, out int comparisonResult) { if (NeitherNull(x, y, out comparisonResult)) { comparisonResult = string.Compare(x.ValueText, y.ValueText, StringComparison.OrdinalIgnoreCase); } return comparisonResult == 0; } private static bool EqualOperatorPrecedence(SyntaxToken x, SyntaxToken y, out int comparisonResult) { if (NeitherNull(x, y, out comparisonResult)) { s_operatorPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence); s_operatorPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence); comparisonResult = xPrecedence - yPrecedence; } return comparisonResult == 0; } private static bool EqualParameterCount(BaseParameterListSyntax x, BaseParameterListSyntax y, out int comparisonResult) { var xParameterCount = x.Parameters.Count; var yParameterCount = y.Parameters.Count; comparisonResult = xParameterCount - yParameterCount; return comparisonResult == 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal class CSharpDeclarationComparer : IComparer<SyntaxNode> { private static readonly Dictionary<SyntaxKind, int> s_kindPrecedenceMap = new(SyntaxFacts.EqualityComparer) { { SyntaxKind.FieldDeclaration, 0 }, { SyntaxKind.ConstructorDeclaration, 1 }, { SyntaxKind.DestructorDeclaration, 2 }, { SyntaxKind.IndexerDeclaration, 3 }, { SyntaxKind.PropertyDeclaration, 4 }, { SyntaxKind.EventFieldDeclaration, 5 }, { SyntaxKind.EventDeclaration, 6 }, { SyntaxKind.MethodDeclaration, 7 }, { SyntaxKind.OperatorDeclaration, 8 }, { SyntaxKind.ConversionOperatorDeclaration, 9 }, { SyntaxKind.EnumDeclaration, 10 }, { SyntaxKind.InterfaceDeclaration, 11 }, { SyntaxKind.StructDeclaration, 12 }, { SyntaxKind.ClassDeclaration, 13 }, { SyntaxKind.RecordDeclaration, 14 }, { SyntaxKind.RecordStructDeclaration, 15 }, { SyntaxKind.DelegateDeclaration, 16 } }; private static readonly Dictionary<SyntaxKind, int> s_operatorPrecedenceMap = new(SyntaxFacts.EqualityComparer) { { SyntaxKind.PlusToken, 0 }, { SyntaxKind.MinusToken, 1 }, { SyntaxKind.ExclamationToken, 2 }, { SyntaxKind.TildeToken, 3 }, { SyntaxKind.PlusPlusToken, 4 }, { SyntaxKind.MinusMinusToken, 5 }, { SyntaxKind.AsteriskToken, 6 }, { SyntaxKind.SlashToken, 7 }, { SyntaxKind.PercentToken, 8 }, { SyntaxKind.AmpersandToken, 9 }, { SyntaxKind.BarToken, 10 }, { SyntaxKind.CaretToken, 11 }, { SyntaxKind.LessThanLessThanToken, 12 }, { SyntaxKind.GreaterThanGreaterThanToken, 13 }, { SyntaxKind.EqualsEqualsToken, 14 }, { SyntaxKind.ExclamationEqualsToken, 15 }, { SyntaxKind.LessThanToken, 16 }, { SyntaxKind.GreaterThanToken, 17 }, { SyntaxKind.LessThanEqualsToken, 18 }, { SyntaxKind.GreaterThanEqualsToken, 19 }, { SyntaxKind.TrueKeyword, 20 }, { SyntaxKind.FalseKeyword, 21 }, }; public static readonly CSharpDeclarationComparer WithNamesInstance = new(includeName: true); public static readonly CSharpDeclarationComparer WithoutNamesInstance = new(includeName: false); private readonly bool _includeName; private CSharpDeclarationComparer(bool includeName) => _includeName = includeName; public int Compare(SyntaxNode x, SyntaxNode y) { if (x.Kind() != y.Kind()) { if (!s_kindPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence) || !s_kindPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence)) { // The containing declaration is malformed and contains a node kind we did not expect. // Ignore comparisons with those unexpected nodes and sort them to the end of the declaration. return 1; } return xPrecedence < yPrecedence ? -1 : 1; } switch (x.Kind()) { case SyntaxKind.DelegateDeclaration: return Compare((DelegateDeclarationSyntax)x, (DelegateDeclarationSyntax)y); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return Compare((BaseFieldDeclarationSyntax)x, (BaseFieldDeclarationSyntax)y); case SyntaxKind.ConstructorDeclaration: return Compare((ConstructorDeclarationSyntax)x, (ConstructorDeclarationSyntax)y); case SyntaxKind.DestructorDeclaration: // All destructors are equal since there can only be one per named type return 0; case SyntaxKind.MethodDeclaration: return Compare((MethodDeclarationSyntax)x, (MethodDeclarationSyntax)y); case SyntaxKind.OperatorDeclaration: return Compare((OperatorDeclarationSyntax)x, (OperatorDeclarationSyntax)y); case SyntaxKind.EventDeclaration: return Compare((EventDeclarationSyntax)x, (EventDeclarationSyntax)y); case SyntaxKind.IndexerDeclaration: return Compare((IndexerDeclarationSyntax)x, (IndexerDeclarationSyntax)y); case SyntaxKind.PropertyDeclaration: return Compare((PropertyDeclarationSyntax)x, (PropertyDeclarationSyntax)y); case SyntaxKind.EnumDeclaration: return Compare((EnumDeclarationSyntax)x, (EnumDeclarationSyntax)y); case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return Compare((BaseTypeDeclarationSyntax)x, (BaseTypeDeclarationSyntax)y); case SyntaxKind.ConversionOperatorDeclaration: return Compare((ConversionOperatorDeclarationSyntax)x, (ConversionOperatorDeclarationSyntax)y); case SyntaxKind.IncompleteMember: // Since these are incomplete members they are considered to be equal return 0; case SyntaxKind.GlobalStatement: // for REPL, don't mess with order, just put new one at the end. return 1; default: throw ExceptionUtilities.UnexpectedValue(x.Kind()); } } private int Compare(DelegateDeclarationSyntax x, DelegateDeclarationSyntax y) { if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private int Compare(BaseFieldDeclarationSyntax x, BaseFieldDeclarationSyntax y) { if (EqualConstness(x.Modifiers, y.Modifiers, out var result) && EqualStaticness(x.Modifiers, y.Modifiers, out result) && EqualReadOnlyness(x.Modifiers, y.Modifiers, out result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (_includeName) { EqualIdentifierName( x.Declaration.Variables.FirstOrDefault().Identifier, y.Declaration.Variables.FirstOrDefault().Identifier, out result); } } return result; } private static int Compare(ConstructorDeclarationSyntax x, ConstructorDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { EqualParameterCount(x.ParameterList, y.ParameterList, out result); } return result; } private int Compare(MethodDeclarationSyntax x, MethodDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (!_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private static int Compare(ConversionOperatorDeclarationSyntax x, ConversionOperatorDeclarationSyntax y) { if (x.ImplicitOrExplicitKeyword.Kind() != y.ImplicitOrExplicitKeyword.Kind()) { return x.ImplicitOrExplicitKeyword.Kind() == SyntaxKind.ImplicitKeyword ? -1 : 1; } EqualParameterCount(x.ParameterList, y.ParameterList, out var result); return result; } private static int Compare(OperatorDeclarationSyntax x, OperatorDeclarationSyntax y) { if (EqualOperatorPrecedence(x.OperatorToken, y.OperatorToken, out var result)) { EqualParameterCount(x.ParameterList, y.ParameterList, out result); } return result; } private int Compare(EventDeclarationSyntax x, EventDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private static int Compare(IndexerDeclarationSyntax x, IndexerDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { EqualParameterCount(x.ParameterList, y.ParameterList, out result); } return result; } private int Compare(PropertyDeclarationSyntax x, PropertyDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private int Compare(EnumDeclarationSyntax x, EnumDeclarationSyntax y) { if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private int Compare(BaseTypeDeclarationSyntax x, BaseTypeDeclarationSyntax y) { if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) && EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result)) { if (_includeName) { EqualIdentifierName(x.Identifier, y.Identifier, out result); } } return result; } private static bool NeitherNull(object x, object y, out int comparisonResult) { if (x == null && y == null) { comparisonResult = 0; return false; } else if (x == null) { // x == null && y != null comparisonResult = -1; return false; } else if (y == null) { // x != null && y == null comparisonResult = 1; return false; } else { // x != null && y != null comparisonResult = 0; return true; } } private static bool ContainsToken(SyntaxTokenList list, SyntaxKind kind) => list.Contains(token => token.Kind() == kind); private enum Accessibility { Public, Protected, ProtectedInternal, Internal, PrivateProtected, Private } private static int GetAccessibilityPrecedence(SyntaxTokenList modifiers, SyntaxNode parent) { if (ContainsToken(modifiers, SyntaxKind.PublicKeyword)) { return (int)Accessibility.Public; } else if (ContainsToken(modifiers, SyntaxKind.ProtectedKeyword)) { if (ContainsToken(modifiers, SyntaxKind.InternalKeyword)) { return (int)Accessibility.ProtectedInternal; } if (ContainsToken(modifiers, SyntaxKind.PrivateKeyword)) { return (int)Accessibility.PrivateProtected; } return (int)Accessibility.Protected; } else if (ContainsToken(modifiers, SyntaxKind.InternalKeyword)) { return (int)Accessibility.Internal; } else if (ContainsToken(modifiers, SyntaxKind.PrivateKeyword)) { return (int)Accessibility.Private; } // Determine default accessibility: This declaration is internal if we traverse up // the syntax tree and don't find a containing named type. for (var node = parent; node != null; node = node.Parent) { if (node.Kind() == SyntaxKind.InterfaceDeclaration) { // All interface members are public return (int)Accessibility.Public; } else if (node.Kind() is SyntaxKind.StructDeclaration or SyntaxKind.ClassDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration) { // Members and nested types default to private return (int)Accessibility.Private; } } return (int)Accessibility.Internal; } private static bool BothHaveModifier(SyntaxTokenList x, SyntaxTokenList y, SyntaxKind modifierKind, out int comparisonResult) { var xHasModifier = ContainsToken(x, modifierKind); var yHasModifier = ContainsToken(y, modifierKind); if (xHasModifier == yHasModifier) { comparisonResult = 0; return true; } comparisonResult = xHasModifier ? -1 : 1; return false; } private static bool EqualStaticness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult) => BothHaveModifier(x, y, SyntaxKind.StaticKeyword, out comparisonResult); private static bool EqualConstness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult) => BothHaveModifier(x, y, SyntaxKind.ConstKeyword, out comparisonResult); private static bool EqualReadOnlyness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult) => BothHaveModifier(x, y, SyntaxKind.ReadOnlyKeyword, out comparisonResult); private static bool EqualAccessibility(SyntaxNode x, SyntaxTokenList xModifiers, SyntaxNode y, SyntaxTokenList yModifiers, out int comparisonResult) { var xAccessibility = GetAccessibilityPrecedence(xModifiers, x.Parent ?? y.Parent); var yAccessibility = GetAccessibilityPrecedence(yModifiers, y.Parent ?? x.Parent); comparisonResult = xAccessibility - yAccessibility; return comparisonResult == 0; } private static bool EqualIdentifierName(SyntaxToken x, SyntaxToken y, out int comparisonResult) { if (NeitherNull(x, y, out comparisonResult)) { comparisonResult = string.Compare(x.ValueText, y.ValueText, StringComparison.OrdinalIgnoreCase); } return comparisonResult == 0; } private static bool EqualOperatorPrecedence(SyntaxToken x, SyntaxToken y, out int comparisonResult) { if (NeitherNull(x, y, out comparisonResult)) { s_operatorPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence); s_operatorPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence); comparisonResult = xPrecedence - yPrecedence; } return comparisonResult == 0; } private static bool EqualParameterCount(BaseParameterListSyntax x, BaseParameterListSyntax y, out int comparisonResult) { var xParameterCount = x.Parameters.Count; var yParameterCount = y.Parameters.Count; comparisonResult = xParameterCount - yParameterCount; return comparisonResult == 0; } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Workspaces/Core/Portable/FindSymbols/ReferenceLocationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols { internal static class ReferenceLocationExtensions { public static async Task<Dictionary<ISymbol, List<Location>>> FindReferencingSymbolsAsync( this IEnumerable<ReferenceLocation> referenceLocations, CancellationToken cancellationToken) { var documentGroups = referenceLocations.GroupBy(loc => loc.Document); var projectGroups = documentGroups.GroupBy(g => g.Key.Project); var result = new Dictionary<ISymbol, List<Location>>(); foreach (var projectGroup in projectGroups) { cancellationToken.ThrowIfCancellationRequested(); var project = projectGroup.Key; if (project.SupportsCompilation) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var documentGroup in projectGroup) { var document = documentGroup.Key; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); AddSymbols(semanticModel, documentGroup, result); } // Keep compilation alive so that GetSemanticModelAsync remains cheap GC.KeepAlive(compilation); } } return result; } private static void AddSymbols( SemanticModel semanticModel, IEnumerable<ReferenceLocation> references, Dictionary<ISymbol, List<Location>> result) { foreach (var reference in references) { var containingSymbol = GetEnclosingMethodOrPropertyOrField(semanticModel, reference); if (containingSymbol != null) { if (!result.TryGetValue(containingSymbol, out var locations)) { locations = new List<Location>(); result.Add(containingSymbol, locations); } locations.Add(reference.Location); } } } private static ISymbol GetEnclosingMethodOrPropertyOrField( SemanticModel semanticModel, ReferenceLocation reference) { var enclosingSymbol = semanticModel.GetEnclosingSymbol(reference.Location.SourceSpan.Start); for (var current = enclosingSymbol; current != null; current = current.ContainingSymbol) { if (current.Kind == SymbolKind.Field) { return current; } if (current.Kind == SymbolKind.Property) { return current; } if (current.Kind == SymbolKind.Method) { var method = (IMethodSymbol)current; if (method.IsAccessor()) { return method.AssociatedSymbol; } if (method.MethodKind != MethodKind.AnonymousFunction) { return method; } } } 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.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols { internal static class ReferenceLocationExtensions { public static async Task<Dictionary<ISymbol, List<Location>>> FindReferencingSymbolsAsync( this IEnumerable<ReferenceLocation> referenceLocations, CancellationToken cancellationToken) { var documentGroups = referenceLocations.GroupBy(loc => loc.Document); var projectGroups = documentGroups.GroupBy(g => g.Key.Project); var result = new Dictionary<ISymbol, List<Location>>(); foreach (var projectGroup in projectGroups) { cancellationToken.ThrowIfCancellationRequested(); var project = projectGroup.Key; if (project.SupportsCompilation) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var documentGroup in projectGroup) { var document = documentGroup.Key; var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); AddSymbols(semanticModel, documentGroup, result); } // Keep compilation alive so that GetSemanticModelAsync remains cheap GC.KeepAlive(compilation); } } return result; } private static void AddSymbols( SemanticModel semanticModel, IEnumerable<ReferenceLocation> references, Dictionary<ISymbol, List<Location>> result) { foreach (var reference in references) { var containingSymbol = GetEnclosingMethodOrPropertyOrField(semanticModel, reference); if (containingSymbol != null) { if (!result.TryGetValue(containingSymbol, out var locations)) { locations = new List<Location>(); result.Add(containingSymbol, locations); } locations.Add(reference.Location); } } } private static ISymbol GetEnclosingMethodOrPropertyOrField( SemanticModel semanticModel, ReferenceLocation reference) { var enclosingSymbol = semanticModel.GetEnclosingSymbol(reference.Location.SourceSpan.Start); for (var current = enclosingSymbol; current != null; current = current.ContainingSymbol) { if (current.Kind == SymbolKind.Field) { return current; } if (current.Kind == SymbolKind.Property) { return current; } if (current.Kind == SymbolKind.Method) { var method = (IMethodSymbol)current; if (method.IsAccessor()) { return method.AssociatedSymbol; } if (method.MethodKind != MethodKind.AnonymousFunction) { return method; } } } return null; } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Tools/BuildBoss/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using Mono.Options; namespace BuildBoss { internal static class Program { internal static int Main(string[] args) { try { return MainCore(args) ? 0 : 1; } catch (Exception ex) { Console.WriteLine($"Unhandled exception: {ex.Message}"); Console.WriteLine(ex.StackTrace); return 1; } } private static bool MainCore(string[] args) { string repositoryDirectory = null; string configuration = "Debug"; string primarySolution = null; List<string> solutionFiles; var options = new OptionSet { { "r|root=", "The repository root", value => repositoryDirectory = value }, { "c|configuration=", "Build configuration", value => configuration = value }, { "p|primary=", "Primary solution file name (which contains all projects)", value => primarySolution = value }, }; if (configuration != "Debug" && configuration != "Release") { Console.Error.WriteLine($"Invalid configuration: '{configuration}'"); return false; } try { solutionFiles = options.Parse(args); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); options.WriteOptionDescriptions(Console.Error); return false; } if (string.IsNullOrEmpty(repositoryDirectory)) { repositoryDirectory = FindRepositoryRoot( (solutionFiles.Count > 0) ? Path.GetDirectoryName(solutionFiles[0]) : AppContext.BaseDirectory); if (repositoryDirectory == null) { Console.Error.WriteLine("Unable to find repository root"); return false; } } if (solutionFiles.Count == 0) { solutionFiles = Directory.EnumerateFiles(repositoryDirectory, "*.sln").ToList(); } return Go(repositoryDirectory, configuration, primarySolution, solutionFiles); } private static string FindRepositoryRoot(string startDirectory) { string dir = startDirectory; while (dir != null && !File.Exists(Path.Combine(dir, "global.json"))) { dir = Path.GetDirectoryName(dir); } return dir; } private static bool Go(string repositoryDirectory, string configuration, string primarySolution, List<string> solutionFileNames) { var allGood = true; foreach (var solutionFileName in solutionFileNames) { allGood &= ProcessSolution(Path.Combine(repositoryDirectory, solutionFileName), isPrimarySolution: solutionFileName == primarySolution); } var artifactsDirectory = Path.Combine(repositoryDirectory, "artifacts"); allGood &= ProcessTargets(repositoryDirectory); allGood &= ProcessPackages(repositoryDirectory, artifactsDirectory, configuration); allGood &= ProcessStructuredLog(artifactsDirectory, configuration); allGood &= ProcessOptProf(repositoryDirectory, artifactsDirectory, configuration); if (!allGood) { Console.WriteLine("Failed"); } return allGood; } private static bool CheckCore(ICheckerUtil util, string title) { Console.Write($"Processing {title} ... "); var textWriter = new StringWriter(); if (util.Check(textWriter)) { Console.WriteLine("passed"); return true; } else { Console.WriteLine("FAILED"); Console.WriteLine(textWriter.ToString()); return false; } } private static bool ProcessSolution(string solutionFilePath, bool isPrimarySolution) { var util = new SolutionCheckerUtil(solutionFilePath, isPrimarySolution); return CheckCore(util, $"Solution {solutionFilePath}"); } private static bool ProcessTargets(string repositoryDirectory) { var targetsDirectory = Path.Combine(repositoryDirectory, @"eng\targets"); var checker = new TargetsCheckerUtil(targetsDirectory); return CheckCore(checker, $"Targets {targetsDirectory}"); } private static bool ProcessStructuredLog(string artifactsDirectory, string configuration) { var logFilePath = Path.Combine(artifactsDirectory, $@"log\{configuration}\Build.binlog"); var util = new StructuredLoggerCheckerUtil(logFilePath); return CheckCore(util, $"Structured log {logFilePath}"); } private static bool ProcessPackages(string repositoryDirectory, string artifactsDirectory, string configuration) { var util = new PackageContentsChecker(repositoryDirectory, artifactsDirectory, configuration); return CheckCore(util, $"NuPkg and VSIX files"); } private static bool ProcessOptProf(string repositoryDirectory, string artifactsDirectory, string configuration) { var util = new OptProfCheckerUtil(repositoryDirectory, artifactsDirectory, configuration); return CheckCore(util, $"OptProf inputs"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Mono.Options; namespace BuildBoss { internal static class Program { internal static int Main(string[] args) { try { return MainCore(args) ? 0 : 1; } catch (Exception ex) { Console.WriteLine($"Unhandled exception: {ex.Message}"); Console.WriteLine(ex.StackTrace); return 1; } } private static bool MainCore(string[] args) { string repositoryDirectory = null; string configuration = "Debug"; string primarySolution = null; List<string> solutionFiles; var options = new OptionSet { { "r|root=", "The repository root", value => repositoryDirectory = value }, { "c|configuration=", "Build configuration", value => configuration = value }, { "p|primary=", "Primary solution file name (which contains all projects)", value => primarySolution = value }, }; if (configuration != "Debug" && configuration != "Release") { Console.Error.WriteLine($"Invalid configuration: '{configuration}'"); return false; } try { solutionFiles = options.Parse(args); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); options.WriteOptionDescriptions(Console.Error); return false; } if (string.IsNullOrEmpty(repositoryDirectory)) { repositoryDirectory = FindRepositoryRoot( (solutionFiles.Count > 0) ? Path.GetDirectoryName(solutionFiles[0]) : AppContext.BaseDirectory); if (repositoryDirectory == null) { Console.Error.WriteLine("Unable to find repository root"); return false; } } if (solutionFiles.Count == 0) { solutionFiles = Directory.EnumerateFiles(repositoryDirectory, "*.sln").ToList(); } return Go(repositoryDirectory, configuration, primarySolution, solutionFiles); } private static string FindRepositoryRoot(string startDirectory) { string dir = startDirectory; while (dir != null && !File.Exists(Path.Combine(dir, "global.json"))) { dir = Path.GetDirectoryName(dir); } return dir; } private static bool Go(string repositoryDirectory, string configuration, string primarySolution, List<string> solutionFileNames) { var allGood = true; foreach (var solutionFileName in solutionFileNames) { allGood &= ProcessSolution(Path.Combine(repositoryDirectory, solutionFileName), isPrimarySolution: solutionFileName == primarySolution); } var artifactsDirectory = Path.Combine(repositoryDirectory, "artifacts"); allGood &= ProcessTargets(repositoryDirectory); allGood &= ProcessPackages(repositoryDirectory, artifactsDirectory, configuration); allGood &= ProcessStructuredLog(artifactsDirectory, configuration); allGood &= ProcessOptProf(repositoryDirectory, artifactsDirectory, configuration); if (!allGood) { Console.WriteLine("Failed"); } return allGood; } private static bool CheckCore(ICheckerUtil util, string title) { Console.Write($"Processing {title} ... "); var textWriter = new StringWriter(); if (util.Check(textWriter)) { Console.WriteLine("passed"); return true; } else { Console.WriteLine("FAILED"); Console.WriteLine(textWriter.ToString()); return false; } } private static bool ProcessSolution(string solutionFilePath, bool isPrimarySolution) { var util = new SolutionCheckerUtil(solutionFilePath, isPrimarySolution); return CheckCore(util, $"Solution {solutionFilePath}"); } private static bool ProcessTargets(string repositoryDirectory) { var targetsDirectory = Path.Combine(repositoryDirectory, @"eng\targets"); var checker = new TargetsCheckerUtil(targetsDirectory); return CheckCore(checker, $"Targets {targetsDirectory}"); } private static bool ProcessStructuredLog(string artifactsDirectory, string configuration) { var logFilePath = Path.Combine(artifactsDirectory, $@"log\{configuration}\Build.binlog"); var util = new StructuredLoggerCheckerUtil(logFilePath); return CheckCore(util, $"Structured log {logFilePath}"); } private static bool ProcessPackages(string repositoryDirectory, string artifactsDirectory, string configuration) { var util = new PackageContentsChecker(repositoryDirectory, artifactsDirectory, configuration); return CheckCore(util, $"NuPkg and VSIX files"); } private static bool ProcessOptProf(string repositoryDirectory, string artifactsDirectory, string configuration) { var util = new OptProfCheckerUtil(repositoryDirectory, artifactsDirectory, configuration); return CheckCore(util, $"OptProf inputs"); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : AbstractStatelessRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : VSInternalDiagnosticReport { private readonly IXamlPullDiagnosticService _xamlDiagnosticService; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. /// </summary> protected abstract VSInternalDiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed. /// </summary> protected abstract ImmutableArray<Document> GetDocuments(RequestContext context); /// <summary> /// Creates the <see cref="VSInternalDiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); protected AbstractPullDiagnosticHandler(IXamlPullDiagnosticService xamlDiagnosticService) { _xamlDiagnosticService = xamlDiagnosticService; } public override async Task<TReport[]?> HandleRequestAsync(TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. var previousResults = GetPreviousResults(diagnosticsParams); var documentToPreviousResultId = new Dictionary<Document, string?>(); if (previousResults != null) { // Go through the previousResults and check if we need to remove diagnostic information for any documents foreach (var previousResult in previousResults) { if (previousResult.TextDocument != null) { var document = context.Solution.GetDocument(previousResult.TextDocument, context.ClientName); if (document == null) { // We can no longer get this document, return null for both diagnostics and resultId progress.Report(CreateReport(previousResult.TextDocument, diagnostics: null, resultId: null)); } else { // Cache the document to previousResultId mapping so we can easily retrieve the resultId later. documentToPreviousResultId[document] = previousResult.PreviousResultId; } } } } // Go through the documents that we need to process and call XamlPullDiagnosticService to get the diagnostic report foreach (var document in GetDocuments(context)) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var documentId = ProtocolConversions.DocumentToTextDocumentIdentifier(document); // If we can get a previousId of the document, use it, // otherwise use null as the previousId to pass into the XamlPullDiagnosticService var previousResultId = documentToPreviousResultId.TryGetValue(document, out var id) ? id : null; // Call XamlPullDiagnosticService to get the diagnostic report for this document. // We will compute what to report inside XamlPullDiagnosticService, for example, whether we should keep using the previousId or use a new resultId, // and the handler here just return the result get from XamlPullDiagnosticService. var diagnosticReport = await _xamlDiagnosticService.GetDiagnosticReportAsync(document, previousResultId, cancellationToken).ConfigureAwait(false); progress.Report(CreateReport( documentId, ConvertToVSDiagnostics(diagnosticReport.Diagnostics, document, text), diagnosticReport.ResultId)); } return progress.GetValues(); } /// <summary> /// Convert XamlDiagnostics to VSDiagnostics /// </summary> private static VSDiagnostic[]? ConvertToVSDiagnostics(ImmutableArray<XamlDiagnostic>? xamlDiagnostics, Document document, SourceText text) { if (xamlDiagnostics == null) { return null; } var project = document.Project; return xamlDiagnostics.Value.Select(d => new VSDiagnostic() { Code = d.Code, Message = d.Message ?? string.Empty, ExpandedMessage = d.ExtendedMessage, Severity = ConvertDiagnosticSeverity(d.Severity), Range = ProtocolConversions.TextSpanToRange(new TextSpan(d.Offset, d.Length), text), Tags = ConvertTags(d), Source = d.Tool, CodeDescription = ProtocolConversions.HelpLinkToCodeDescription(d.HelpLink), Projects = new[] { new VSDiagnosticProjectInformation { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }).ToArray(); } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(XamlDiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. XamlDiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, XamlDiagnosticSeverity.HintedSuggestion => LSP.DiagnosticSeverity.Hint, XamlDiagnosticSeverity.Message => LSP.DiagnosticSeverity.Information, XamlDiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, XamlDiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\Features\LanguageServer\Protocol\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> private static DiagnosticTag[] ConvertTags(XamlDiagnostic diagnostic) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); result.Add(VSDiagnosticTags.IntellisenseError); if (diagnostic.Severity == XamlDiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else if (diagnostic.Severity == XamlDiagnosticSeverity.HintedSuggestion) { result.Add(VSDiagnosticTags.HiddenInErrorList); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (diagnostic.CustomTags?.Contains(WellKnownDiagnosticTags.Unnecessary) == true) result.Add(DiagnosticTag.Unnecessary); return result.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. 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.Diagnostics; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : AbstractStatelessRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : VSInternalDiagnosticReport { private readonly IXamlPullDiagnosticService _xamlDiagnosticService; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. /// </summary> protected abstract VSInternalDiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed. /// </summary> protected abstract ImmutableArray<Document> GetDocuments(RequestContext context); /// <summary> /// Creates the <see cref="VSInternalDiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); protected AbstractPullDiagnosticHandler(IXamlPullDiagnosticService xamlDiagnosticService) { _xamlDiagnosticService = xamlDiagnosticService; } public override async Task<TReport[]?> HandleRequestAsync(TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { Contract.ThrowIfNull(context.Solution); using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. var previousResults = GetPreviousResults(diagnosticsParams); var documentToPreviousResultId = new Dictionary<Document, string?>(); if (previousResults != null) { // Go through the previousResults and check if we need to remove diagnostic information for any documents foreach (var previousResult in previousResults) { if (previousResult.TextDocument != null) { var document = context.Solution.GetDocument(previousResult.TextDocument, context.ClientName); if (document == null) { // We can no longer get this document, return null for both diagnostics and resultId progress.Report(CreateReport(previousResult.TextDocument, diagnostics: null, resultId: null)); } else { // Cache the document to previousResultId mapping so we can easily retrieve the resultId later. documentToPreviousResultId[document] = previousResult.PreviousResultId; } } } } // Go through the documents that we need to process and call XamlPullDiagnosticService to get the diagnostic report foreach (var document in GetDocuments(context)) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var documentId = ProtocolConversions.DocumentToTextDocumentIdentifier(document); // If we can get a previousId of the document, use it, // otherwise use null as the previousId to pass into the XamlPullDiagnosticService var previousResultId = documentToPreviousResultId.TryGetValue(document, out var id) ? id : null; // Call XamlPullDiagnosticService to get the diagnostic report for this document. // We will compute what to report inside XamlPullDiagnosticService, for example, whether we should keep using the previousId or use a new resultId, // and the handler here just return the result get from XamlPullDiagnosticService. var diagnosticReport = await _xamlDiagnosticService.GetDiagnosticReportAsync(document, previousResultId, cancellationToken).ConfigureAwait(false); progress.Report(CreateReport( documentId, ConvertToVSDiagnostics(diagnosticReport.Diagnostics, document, text), diagnosticReport.ResultId)); } return progress.GetValues(); } /// <summary> /// Convert XamlDiagnostics to VSDiagnostics /// </summary> private static VSDiagnostic[]? ConvertToVSDiagnostics(ImmutableArray<XamlDiagnostic>? xamlDiagnostics, Document document, SourceText text) { if (xamlDiagnostics == null) { return null; } var project = document.Project; return xamlDiagnostics.Value.Select(d => new VSDiagnostic() { Code = d.Code, Message = d.Message ?? string.Empty, ExpandedMessage = d.ExtendedMessage, Severity = ConvertDiagnosticSeverity(d.Severity), Range = ProtocolConversions.TextSpanToRange(new TextSpan(d.Offset, d.Length), text), Tags = ConvertTags(d), Source = d.Tool, CodeDescription = ProtocolConversions.HelpLinkToCodeDescription(d.HelpLink), Projects = new[] { new VSDiagnosticProjectInformation { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }).ToArray(); } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(XamlDiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. XamlDiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, XamlDiagnosticSeverity.HintedSuggestion => LSP.DiagnosticSeverity.Hint, XamlDiagnosticSeverity.Message => LSP.DiagnosticSeverity.Information, XamlDiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, XamlDiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\Features\LanguageServer\Protocol\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> private static DiagnosticTag[] ConvertTags(XamlDiagnostic diagnostic) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); result.Add(VSDiagnosticTags.IntellisenseError); if (diagnostic.Severity == XamlDiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else if (diagnostic.Severity == XamlDiagnosticSeverity.HintedSuggestion) { result.Add(VSDiagnosticTags.HiddenInErrorList); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (diagnostic.CustomTags?.Contains(WellKnownDiagnosticTags.Unnecessary) == true) result.Add(DiagnosticTag.Unnecessary); return result.ToArray(); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Analyzers/Core/Analyzers/AbstractParenthesesDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Precedence; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected AbstractParenthesesDiagnosticAnalyzer( string descriptorId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message, bool isUnnecessary = false) : base(descriptorId, enforceOnBuild, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.RelationalBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses), title, message, isUnnecessary: isUnnecessary) { } protected static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> GetLanguageOption(PrecedenceKind precedenceKind) { switch (precedenceKind) { case PrecedenceKind.Arithmetic: case PrecedenceKind.Shift: case PrecedenceKind.Bitwise: return CodeStyleOptions2.ArithmeticBinaryParentheses; case PrecedenceKind.Relational: case PrecedenceKind.Equality: return CodeStyleOptions2.RelationalBinaryParentheses; case PrecedenceKind.Logical: case PrecedenceKind.Coalesce: return CodeStyleOptions2.OtherBinaryParentheses; case PrecedenceKind.Other: return CodeStyleOptions2.OtherParentheses; } throw ExceptionUtilities.UnexpectedValue(precedenceKind); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Precedence; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected AbstractParenthesesDiagnosticAnalyzer( string descriptorId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message, bool isUnnecessary = false) : base(descriptorId, enforceOnBuild, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.RelationalBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses), title, message, isUnnecessary: isUnnecessary) { } protected static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> GetLanguageOption(PrecedenceKind precedenceKind) { switch (precedenceKind) { case PrecedenceKind.Arithmetic: case PrecedenceKind.Shift: case PrecedenceKind.Bitwise: return CodeStyleOptions2.ArithmeticBinaryParentheses; case PrecedenceKind.Relational: case PrecedenceKind.Equality: return CodeStyleOptions2.RelationalBinaryParentheses; case PrecedenceKind.Logical: case PrecedenceKind.Coalesce: return CodeStyleOptions2.OtherBinaryParentheses; case PrecedenceKind.Other: return CodeStyleOptions2.OtherParentheses; } throw ExceptionUtilities.UnexpectedValue(precedenceKind); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProjectReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class ProjectDependencyGraph { internal ProjectDependencyGraph WithProjectReferenceRemoved(ProjectId projectId, ProjectId referencedProjectId) { Contract.ThrowIfFalse(_projectIds.Contains(projectId)); Contract.ThrowIfFalse(_referencesMap[projectId].Contains(referencedProjectId)); // Removing a project reference doesn't change the set of projects var projectIds = _projectIds; // Incrementally update the graph var referencesMap = ComputeNewReferencesMapForRemovedProjectReference(_referencesMap, projectId, referencedProjectId); var reverseReferencesMap = ComputeNewReverseReferencesMapForRemovedProjectReference(_lazyReverseReferencesMap, projectId, referencedProjectId); var transitiveReferencesMap = ComputeNewTransitiveReferencesMapForRemovedProjectReference(_transitiveReferencesMap, projectId, referencedProjectId); var reverseTransitiveReferencesMap = ComputeNewReverseTransitiveReferencesMapForRemovedProjectReference(_reverseTransitiveReferencesMap, projectId, referencedProjectId); return new ProjectDependencyGraph( projectIds, referencesMap, reverseReferencesMap, transitiveReferencesMap, reverseTransitiveReferencesMap, topologicallySortedProjects: default, dependencySets: default); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingForwardReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { return existingForwardReferencesMap.MultiRemove(projectId, referencedProjectId); } /// <summary> /// Computes a new <see cref="_lazyReverseReferencesMap"/> for the removal of a project reference. /// </summary> /// <param name="existingReverseReferencesMap">The <see cref="_lazyReverseReferencesMap"/> prior to the removal, /// or <see langword="null"/> if the reverse references map was not computed for the prior graph.</param> /// <param name="projectId">The project ID from which a project reference is being removed.</param> /// <param name="referencedProjectId">The target of the project reference which is being removed.</param> /// <returns>The updated (complete) reverse references map, or <see langword="null"/> if the reverse references /// map could not be incrementally updated.</returns> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? ComputeNewReverseReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? existingReverseReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { if (existingReverseReferencesMap is null) { return null; } return existingReverseReferencesMap.MultiRemove(referencedProjectId, projectId); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewTransitiveReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingTransitiveReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { var builder = existingTransitiveReferencesMap.ToBuilder(); // Invalidate the transitive references from every project referencing the changed project (transitively) foreach (var (project, references) in existingTransitiveReferencesMap) { if (!references.Contains(projectId)) { // This is the forward-references-equivalent of the optimization in the update of reverse transitive // references. continue; } Debug.Assert(references.Contains(referencedProjectId)); builder.Remove(project); } // Invalidate the transitive references from the changed project builder.Remove(projectId); return builder.ToImmutable(); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReverseTransitiveReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingReverseTransitiveReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { var builder = existingReverseTransitiveReferencesMap.ToBuilder(); // Invalidate the transitive reverse references from every project previously referenced by the original // project (transitively), except for cases where the removed project reference could not impact the result. foreach (var (project, references) in existingReverseTransitiveReferencesMap) { if (!references.Contains(referencedProjectId)) { // If projectId references project, it isn't through referencedProjectId so the change doesn't // impact the dependency graph. // // Suppose we start with the following graph, and are removing the project reference A->B: // // A -> B -> C // \ // > D // // This case is not hit for project C. The reverse transitive references for C contains B, which is // the target project of the removed reference. We can see that project C is impacted by this // removal, and after the removal, project A will no longer be in the reverse transitive references // of C. // // This case is hit for project D. The reverse transitive references for D does not contain B, which // means project D cannot be "downstream" of the impact of removing the reference A->B. We can see // that project A will still be in the reverse transitive references of D. // // This optimization does not catch all cases. For example, consider the following graph where we // are removing the project reference A->B: // // A -> B -> D // \_______^ // // For this example, we do not hit this optimization because D contains project B in the set of // reverse transitive references. Without more complicated checks, we cannot rule out the // possibility that A may have been removed from the reverse transitive references of D by the // removal of the A->B reference. continue; } Debug.Assert(references.Contains(projectId)); builder.Remove(project); } // Invalidate the transitive references from the previously-referenced project builder.Remove(referencedProjectId); return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class ProjectDependencyGraph { internal ProjectDependencyGraph WithProjectReferenceRemoved(ProjectId projectId, ProjectId referencedProjectId) { Contract.ThrowIfFalse(_projectIds.Contains(projectId)); Contract.ThrowIfFalse(_referencesMap[projectId].Contains(referencedProjectId)); // Removing a project reference doesn't change the set of projects var projectIds = _projectIds; // Incrementally update the graph var referencesMap = ComputeNewReferencesMapForRemovedProjectReference(_referencesMap, projectId, referencedProjectId); var reverseReferencesMap = ComputeNewReverseReferencesMapForRemovedProjectReference(_lazyReverseReferencesMap, projectId, referencedProjectId); var transitiveReferencesMap = ComputeNewTransitiveReferencesMapForRemovedProjectReference(_transitiveReferencesMap, projectId, referencedProjectId); var reverseTransitiveReferencesMap = ComputeNewReverseTransitiveReferencesMapForRemovedProjectReference(_reverseTransitiveReferencesMap, projectId, referencedProjectId); return new ProjectDependencyGraph( projectIds, referencesMap, reverseReferencesMap, transitiveReferencesMap, reverseTransitiveReferencesMap, topologicallySortedProjects: default, dependencySets: default); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingForwardReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { return existingForwardReferencesMap.MultiRemove(projectId, referencedProjectId); } /// <summary> /// Computes a new <see cref="_lazyReverseReferencesMap"/> for the removal of a project reference. /// </summary> /// <param name="existingReverseReferencesMap">The <see cref="_lazyReverseReferencesMap"/> prior to the removal, /// or <see langword="null"/> if the reverse references map was not computed for the prior graph.</param> /// <param name="projectId">The project ID from which a project reference is being removed.</param> /// <param name="referencedProjectId">The target of the project reference which is being removed.</param> /// <returns>The updated (complete) reverse references map, or <see langword="null"/> if the reverse references /// map could not be incrementally updated.</returns> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? ComputeNewReverseReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? existingReverseReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { if (existingReverseReferencesMap is null) { return null; } return existingReverseReferencesMap.MultiRemove(referencedProjectId, projectId); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewTransitiveReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingTransitiveReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { var builder = existingTransitiveReferencesMap.ToBuilder(); // Invalidate the transitive references from every project referencing the changed project (transitively) foreach (var (project, references) in existingTransitiveReferencesMap) { if (!references.Contains(projectId)) { // This is the forward-references-equivalent of the optimization in the update of reverse transitive // references. continue; } Debug.Assert(references.Contains(referencedProjectId)); builder.Remove(project); } // Invalidate the transitive references from the changed project builder.Remove(projectId); return builder.ToImmutable(); } private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReverseTransitiveReferencesMapForRemovedProjectReference( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingReverseTransitiveReferencesMap, ProjectId projectId, ProjectId referencedProjectId) { var builder = existingReverseTransitiveReferencesMap.ToBuilder(); // Invalidate the transitive reverse references from every project previously referenced by the original // project (transitively), except for cases where the removed project reference could not impact the result. foreach (var (project, references) in existingReverseTransitiveReferencesMap) { if (!references.Contains(referencedProjectId)) { // If projectId references project, it isn't through referencedProjectId so the change doesn't // impact the dependency graph. // // Suppose we start with the following graph, and are removing the project reference A->B: // // A -> B -> C // \ // > D // // This case is not hit for project C. The reverse transitive references for C contains B, which is // the target project of the removed reference. We can see that project C is impacted by this // removal, and after the removal, project A will no longer be in the reverse transitive references // of C. // // This case is hit for project D. The reverse transitive references for D does not contain B, which // means project D cannot be "downstream" of the impact of removing the reference A->B. We can see // that project A will still be in the reverse transitive references of D. // // This optimization does not catch all cases. For example, consider the following graph where we // are removing the project reference A->B: // // A -> B -> D // \_______^ // // For this example, we do not hit this optimization because D contains project B in the set of // reverse transitive references. Without more complicated checks, we cannot rule out the // possibility that A may have been removed from the reverse transitive references of D by the // removal of the A->B reference. continue; } Debug.Assert(references.Contains(projectId)); builder.Remove(project); } // Invalidate the transitive references from the previously-referenced project builder.Remove(referencedProjectId); return builder.ToImmutable(); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Analyzers/Core/Analyzers/UseSystemHashCode/UseSystemHashCodeDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.UseSystemHashCode { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class UseSystemHashCodeDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public UseSystemHashCodeDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseSystemHashCode, EnforceOnBuildValues.UseSystemHashCode, CodeStyleOptions2.PreferSystemHashCode, new LocalizableResourceString(nameof(AnalyzersResources.Use_System_HashCode), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.GetHashCode_implementation_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(c => { // var hashCodeType = c.Compilation.GetTypeByMetadataName("System.HashCode"); if (Analyzer.TryGetAnalyzer(c.Compilation, out var analyzer)) { c.RegisterOperationBlockAction(ctx => AnalyzeOperationBlock(analyzer, ctx)); } }); } private void AnalyzeOperationBlock(Analyzer analyzer, OperationBlockAnalysisContext context) { if (context.OperationBlocks.Length != 1) return; var owningSymbol = context.OwningSymbol; var operation = context.OperationBlocks[0]; var (accessesBase, hashedMembers, statements) = analyzer.GetHashedMembers(owningSymbol, operation); var elementCount = (accessesBase ? 1 : 0) + (hashedMembers.IsDefaultOrEmpty ? 0 : hashedMembers.Length); // No members to call into HashCode.Combine with. Don't offer anything here. if (elementCount == 0) return; // Just one member to call into HashCode.Combine. Only offer this if we have multiple statements that we can // reduce to a single statement. It's not worth it to offer to replace: // // `return x.GetHashCode();` with `return HashCode.Combine(x);` // // But it is work it to offer to replace: // // `return (a, b).GetHashCode();` with `return HashCode.Combine(a, b);` if (elementCount == 1 && statements.Length < 2) return; // We've got multiple members to hash, or multiple statements that can be reduced at this point. Debug.Assert(elementCount >= 2 || statements.Length >= 2); var syntaxTree = operation.Syntax.SyntaxTree; var cancellationToken = context.CancellationToken; var option = context.Options.GetOption(CodeStyleOptions2.PreferSystemHashCode, operation.Language, syntaxTree, cancellationToken); if (option?.Value != true) return; var operationLocation = operation.Syntax.GetLocation(); var declarationLocation = context.OwningSymbol.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken).GetLocation(); context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, owningSymbol.Locations[0], option.Notification.Severity, new[] { operationLocation, declarationLocation }, ImmutableDictionary<string, string>.Empty)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.UseSystemHashCode { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal class UseSystemHashCodeDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public UseSystemHashCodeDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseSystemHashCode, EnforceOnBuildValues.UseSystemHashCode, CodeStyleOptions2.PreferSystemHashCode, new LocalizableResourceString(nameof(AnalyzersResources.Use_System_HashCode), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.GetHashCode_implementation_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(c => { // var hashCodeType = c.Compilation.GetTypeByMetadataName("System.HashCode"); if (Analyzer.TryGetAnalyzer(c.Compilation, out var analyzer)) { c.RegisterOperationBlockAction(ctx => AnalyzeOperationBlock(analyzer, ctx)); } }); } private void AnalyzeOperationBlock(Analyzer analyzer, OperationBlockAnalysisContext context) { if (context.OperationBlocks.Length != 1) return; var owningSymbol = context.OwningSymbol; var operation = context.OperationBlocks[0]; var (accessesBase, hashedMembers, statements) = analyzer.GetHashedMembers(owningSymbol, operation); var elementCount = (accessesBase ? 1 : 0) + (hashedMembers.IsDefaultOrEmpty ? 0 : hashedMembers.Length); // No members to call into HashCode.Combine with. Don't offer anything here. if (elementCount == 0) return; // Just one member to call into HashCode.Combine. Only offer this if we have multiple statements that we can // reduce to a single statement. It's not worth it to offer to replace: // // `return x.GetHashCode();` with `return HashCode.Combine(x);` // // But it is work it to offer to replace: // // `return (a, b).GetHashCode();` with `return HashCode.Combine(a, b);` if (elementCount == 1 && statements.Length < 2) return; // We've got multiple members to hash, or multiple statements that can be reduced at this point. Debug.Assert(elementCount >= 2 || statements.Length >= 2); var syntaxTree = operation.Syntax.SyntaxTree; var cancellationToken = context.CancellationToken; var option = context.Options.GetOption(CodeStyleOptions2.PreferSystemHashCode, operation.Language, syntaxTree, cancellationToken); if (option?.Value != true) return; var operationLocation = operation.Syntax.GetLocation(); var declarationLocation = context.OwningSymbol.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken).GetLocation(); context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, owningSymbol.Locations[0], option.Notification.Severity, new[] { operationLocation, declarationLocation }, ImmutableDictionary<string, string>.Empty)); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/ConditionalPreprocessorHighlighterTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class ConditionalPreprocessorHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(ConditionalPreprocessorHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_1() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 {|Cursor:[|#If|]|} Goo1 [|Then|] [|#ElseIf|] Goo2 [|Then|] [|#Else|] [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_2() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 {|Cursor:[|Then|]|} [|#ElseIf|] Goo2 [|Then|] [|#Else|] [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_3() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 [|Then|] {|Cursor:[|#ElseIf|]|} Goo2 [|Then|] [|#Else|] [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_4() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 [|Then|] [|#ElseIf|] Goo2 {|Cursor:[|Then|]|} [|#Else|] [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_5() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 [|Then|] [|#ElseIf|] Goo2 [|Then|] {|Cursor:[|#Else|]|} [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_6() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 [|Then|] [|#ElseIf|] Goo2 [|Then|] [|#Else|] {|Cursor:[|#End If|]|}</Text>) End Function <WorkItem(544469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544469")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalWithMissingIf1() As Task Await TestAsync(<Text> #Const goo = _ True : #If goo Then {|Cursor:[|#Else|]|} [|#End If|] ' #If should be the first one in sorted order Dim ifDirective = condDirectives.First() Contract.Assert(ifDirective.Kind = SyntaxKind.IfDirective) (ifDirective.Kind == ElseDirective)</Text>) End Function <WorkItem(544469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544469")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalWithMissingIf2() As Task Await TestAsync(<Text> #Const goo = _ True : #If goo Then [|#Else|] {|Cursor:[|#End If|]|} ' #If should be the first one in sorted order Dim ifDirective = condDirectives.First() Contract.Assert(ifDirective.Kind = SyntaxKind.IfDirective) (ifDirective.Kind == ElseDirective)</Text>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class ConditionalPreprocessorHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(ConditionalPreprocessorHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_1() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 {|Cursor:[|#If|]|} Goo1 [|Then|] [|#ElseIf|] Goo2 [|Then|] [|#Else|] [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_2() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 {|Cursor:[|Then|]|} [|#ElseIf|] Goo2 [|Then|] [|#Else|] [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_3() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 [|Then|] {|Cursor:[|#ElseIf|]|} Goo2 [|Then|] [|#Else|] [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_4() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 [|Then|] [|#ElseIf|] Goo2 {|Cursor:[|Then|]|} [|#Else|] [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_5() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 [|Then|] [|#ElseIf|] Goo2 [|Then|] {|Cursor:[|#Else|]|} [|#End If|]</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalPreprocessorSample1_6() As Task Await TestAsync(<Text> #Const Goo1 = 1 #Const Goo2 = 2 [|#If|] Goo1 [|Then|] [|#ElseIf|] Goo2 [|Then|] [|#Else|] {|Cursor:[|#End If|]|}</Text>) End Function <WorkItem(544469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544469")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalWithMissingIf1() As Task Await TestAsync(<Text> #Const goo = _ True : #If goo Then {|Cursor:[|#Else|]|} [|#End If|] ' #If should be the first one in sorted order Dim ifDirective = condDirectives.First() Contract.Assert(ifDirective.Kind = SyntaxKind.IfDirective) (ifDirective.Kind == ElseDirective)</Text>) End Function <WorkItem(544469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544469")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConditionalWithMissingIf2() As Task Await TestAsync(<Text> #Const goo = _ True : #If goo Then [|#Else|] {|Cursor:[|#End If|]|} ' #If should be the first one in sorted order Dim ifDirective = condDirectives.First() Contract.Assert(ifDirective.Kind = SyntaxKind.IfDirective) (ifDirective.Kind == ElseDirective)</Text>) End Function End Class End Namespace
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Compilers/VisualBasic/Portable/Compilation/DocumentationComments/DocumentationCommentCompiler.Field.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Globalization Imports System.IO Imports System.Text Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicCompilation Partial Friend Class DocumentationCommentCompiler Inherits VisualBasicSymbolVisitor Public Overrides Sub VisitField(symbol As FieldSymbol) Me._cancellationToken.ThrowIfCancellationRequested() If Not ShouldSkipSymbol(symbol) Then Dim sourceField = TryCast(symbol, SourceFieldSymbol) If sourceField IsNot Nothing Then WriteDocumentationCommentForField(sourceField) End If End If End Sub Private Sub WriteDocumentationCommentForField(field As SourceFieldSymbol) Dim docCommentTrivia As DocumentationCommentTriviaSyntax = TryGetDocCommentTriviaAndGenerateDiagnostics(field.DeclarationSyntax) If docCommentTrivia Is Nothing Then Return End If Dim wellKnownElementNodes As New Dictionary(Of WellKnownTag, ArrayBuilder(Of XmlNodeSyntax)) Dim docCommentXml As String = GetDocumentationCommentForSymbol(field, docCommentTrivia, wellKnownElementNodes) ' No further processing If docCommentXml Is Nothing Then FreeWellKnownElementNodes(wellKnownElementNodes) Return End If If docCommentTrivia.SyntaxTree.ReportDocumentationCommentDiagnostics OrElse _writer.IsSpecified Then Dim symbolName As String = GetSymbolName(field) ' Duplicate top-level well known tags ReportWarningsForDuplicatedTags(wellKnownElementNodes) ' <exception> ReportIllegalWellKnownTagIfAny(WellKnownTag.Exception, wellKnownElementNodes, symbolName) ' <returns> ReportIllegalWellKnownTagIfAny(WellKnownTag.Returns, wellKnownElementNodes, symbolName) ' <param> ReportIllegalWellKnownTagIfAny(WellKnownTag.Param, wellKnownElementNodes, symbolName) ' <paramref> ReportIllegalWellKnownTagIfAny(WellKnownTag.ParamRef, wellKnownElementNodes, symbolName) ' <value> ReportIllegalWellKnownTagIfAny(WellKnownTag.Value, wellKnownElementNodes, symbolName) ' <typeparam> ReportIllegalWellKnownTagIfAny(WellKnownTag.TypeParam, wellKnownElementNodes, symbolName) ' <typeparamref> ReportWarningsForTypeParamRefTags(wellKnownElementNodes, symbolName, field, docCommentTrivia.SyntaxTree) End If FreeWellKnownElementNodes(wellKnownElementNodes) WriteDocumentationCommentForSymbol(docCommentXml) End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports System.Globalization Imports System.IO Imports System.Text Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicCompilation Partial Friend Class DocumentationCommentCompiler Inherits VisualBasicSymbolVisitor Public Overrides Sub VisitField(symbol As FieldSymbol) Me._cancellationToken.ThrowIfCancellationRequested() If Not ShouldSkipSymbol(symbol) Then Dim sourceField = TryCast(symbol, SourceFieldSymbol) If sourceField IsNot Nothing Then WriteDocumentationCommentForField(sourceField) End If End If End Sub Private Sub WriteDocumentationCommentForField(field As SourceFieldSymbol) Dim docCommentTrivia As DocumentationCommentTriviaSyntax = TryGetDocCommentTriviaAndGenerateDiagnostics(field.DeclarationSyntax) If docCommentTrivia Is Nothing Then Return End If Dim wellKnownElementNodes As New Dictionary(Of WellKnownTag, ArrayBuilder(Of XmlNodeSyntax)) Dim docCommentXml As String = GetDocumentationCommentForSymbol(field, docCommentTrivia, wellKnownElementNodes) ' No further processing If docCommentXml Is Nothing Then FreeWellKnownElementNodes(wellKnownElementNodes) Return End If If docCommentTrivia.SyntaxTree.ReportDocumentationCommentDiagnostics OrElse _writer.IsSpecified Then Dim symbolName As String = GetSymbolName(field) ' Duplicate top-level well known tags ReportWarningsForDuplicatedTags(wellKnownElementNodes) ' <exception> ReportIllegalWellKnownTagIfAny(WellKnownTag.Exception, wellKnownElementNodes, symbolName) ' <returns> ReportIllegalWellKnownTagIfAny(WellKnownTag.Returns, wellKnownElementNodes, symbolName) ' <param> ReportIllegalWellKnownTagIfAny(WellKnownTag.Param, wellKnownElementNodes, symbolName) ' <paramref> ReportIllegalWellKnownTagIfAny(WellKnownTag.ParamRef, wellKnownElementNodes, symbolName) ' <value> ReportIllegalWellKnownTagIfAny(WellKnownTag.Value, wellKnownElementNodes, symbolName) ' <typeparam> ReportIllegalWellKnownTagIfAny(WellKnownTag.TypeParam, wellKnownElementNodes, symbolName) ' <typeparamref> ReportWarningsForTypeParamRefTags(wellKnownElementNodes, symbolName, field, docCommentTrivia.SyntaxTree) End If FreeWellKnownElementNodes(wellKnownElementNodes) WriteDocumentationCommentForSymbol(docCommentXml) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Tools/BuildValidator/xlf/BuildValidatorResources.de.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../BuildValidatorResources.resx"> <body> <trans-unit id="Assemblies_to_be_excluded_substring_match"> <source>Assemblies to be excluded (substring match)</source> <target state="new">Assemblies to be excluded (substring match)</target> <note /> </trans-unit> <trans-unit id="Do_not_output_log_information_to_console"> <source>Do not output log information to console</source> <target state="new">Do not output log information to console</target> <note /> </trans-unit> <trans-unit id="Output_debug_info_when_rebuild_is_not_equal_to_the_original"> <source>Output debug info when rebuild is not equal to the original</source> <target state="new">Output debug info when rebuild is not equal to the original</target> <note /> </trans-unit> <trans-unit id="Output_verbose_log_information"> <source>Output verbose log information</source> <target state="new">Output verbose log information</target> <note /> </trans-unit> <trans-unit id="Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times"> <source>Path to assemblies to rebuild (can be specified one or more times)</source> <target state="new">Path to assemblies to rebuild (can be specified one or more times)</target> <note /> </trans-unit> <trans-unit id="Path_to_output_debug_info"> <source>Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</source> <target state="new">Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</target> <note /> </trans-unit> <trans-unit id="Path_to_referenced_assemblies_can_be_specified_zero_or_more_times"> <source>Path to referenced assemblies (can be specified zero or more times)</source> <target state="new">Path to referenced assemblies (can be specified zero or more times)</target> <note /> </trans-unit> <trans-unit id="Path_to_sources_to_use_in_rebuild"> <source>Path to sources to use in rebuild</source> <target state="new">Path to sources to use in rebuild</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../BuildValidatorResources.resx"> <body> <trans-unit id="Assemblies_to_be_excluded_substring_match"> <source>Assemblies to be excluded (substring match)</source> <target state="new">Assemblies to be excluded (substring match)</target> <note /> </trans-unit> <trans-unit id="Do_not_output_log_information_to_console"> <source>Do not output log information to console</source> <target state="new">Do not output log information to console</target> <note /> </trans-unit> <trans-unit id="Output_debug_info_when_rebuild_is_not_equal_to_the_original"> <source>Output debug info when rebuild is not equal to the original</source> <target state="new">Output debug info when rebuild is not equal to the original</target> <note /> </trans-unit> <trans-unit id="Output_verbose_log_information"> <source>Output verbose log information</source> <target state="new">Output verbose log information</target> <note /> </trans-unit> <trans-unit id="Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times"> <source>Path to assemblies to rebuild (can be specified one or more times)</source> <target state="new">Path to assemblies to rebuild (can be specified one or more times)</target> <note /> </trans-unit> <trans-unit id="Path_to_output_debug_info"> <source>Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</source> <target state="new">Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</target> <note /> </trans-unit> <trans-unit id="Path_to_referenced_assemblies_can_be_specified_zero_or_more_times"> <source>Path to referenced assemblies (can be specified zero or more times)</source> <target state="new">Path to referenced assemblies (can be specified zero or more times)</target> <note /> </trans-unit> <trans-unit id="Path_to_sources_to_use_in_rebuild"> <source>Path to sources to use in rebuild</source> <target state="new">Path to sources to use in rebuild</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/ArgumentAnalysisResultKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 enum ArgumentAnalysisResultKind : byte { Normal, Expanded, NoCorrespondingParameter, FirstInvalid = NoCorrespondingParameter, NoCorrespondingNamedParameter, DuplicateNamedArgument, RequiredParameterMissing, NameUsedForPositional, BadNonTrailingNamedArgument // if a named argument refers to a different position, all following arguments must be named } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 enum ArgumentAnalysisResultKind : byte { Normal, Expanded, NoCorrespondingParameter, FirstInvalid = NoCorrespondingParameter, NoCorrespondingNamedParameter, DuplicateNamedArgument, RequiredParameterMissing, NameUsedForPositional, BadNonTrailingNamedArgument // if a named argument refers to a different position, all following arguments must be named } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Compilers/VisualBasic/Test/Semantic/Binding/BindingCollectionInitializerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class BindingCollectionInitializerTests Inherits BasicTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerList() Dim source = <compilation name="CollectionInitializerList"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim c As New List(Of String) From {"Hello World!"} 'BIND:"New List(Of String) From {"Hello World!"}" Console.WriteLine(c(0)) End Sub End Class </file> </compilation> CompileAndVerify(source, "Hello World!") Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello World!"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... lo World!"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerListEachElementAsCollectionInitializer() Dim source = <compilation name="CollectionInitializerListEachElementAsCollectionInitializer"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim c As New List(Of String) From {{"Hello"}, {" "}, {"World!"}}'BIND:"New List(Of String) From {{"Hello"}, {" "}, {"World!"}}" For each element in c Console.Write(element) next element End Sub End Class </file> </compilation> CompileAndVerify(source, "Hello World!") Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ... {"World!"}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {{"Hel ... {"World!"}}') Initializers(3): IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"Hello"}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... {"World!"}}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') 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) IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{" "}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... {"World!"}}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '" "') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "') 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) IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"World!"}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... {"World!"}}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World!") (Syntax: '"World!"') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerDictionary() Dim source = <compilation name="CollectionInitializerDictionary"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim c As New Dictionary(Of String, Integer) From {{"Hello", 23}, {"World", 42}}'BIND:"New Dictionary(Of String, Integer) From {{"Hello", 23}, {"World", 42}}" For Each keyValue In c Console.WriteLine(keyValue.Key + " " + keyValue.Value.ToString) Next End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Hello 23 World 42 ]]>) Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32)) (Syntax: 'New Diction ... orld", 42}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32)) (Syntax: 'From {{"Hel ... orld", 42}}') Initializers(2): IInvocationOperation ( Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32).Add(key As System.String, value As System.Int32)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"Hello", 23}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsImplicit) (Syntax: 'New Diction ... orld", 42}}') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '23') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 23) (Syntax: '23') 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) IInvocationOperation ( Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32).Add(key As System.String, value As System.Int32)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"World", 42}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsImplicit) (Syntax: 'New Diction ... orld", 42}}') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"World"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World") (Syntax: '"World"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerCustomCollection() Dim source = <compilation name="CollectionInitializerCustomCollection"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class Custom Private list As New List(Of String)() Public Function GetEnumerator() As CustomEnumerator Return New CustomEnumerator(list) End Function Public Sub add(p As String) list.Add(p) End Sub Public Class CustomEnumerator Private list As list(Of String) Private index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If Me.index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim c as Custom = New Custom() From {"Hello", " ", "World"}'BIND:"New Custom() From {"Hello", " ", "World"}" Output(c) End Sub Public Shared Sub Output(c as custom) For Each value In c Console.Write(value) Next End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Hello World ]]>).VerifyIL("C1.Main", <![CDATA[ { // Code size 44 (0x2c) .maxstack 3 IL_0000: newobj "Sub Custom..ctor()" IL_0005: dup IL_0006: ldstr "Hello" IL_000b: callvirt "Sub Custom.add(String)" IL_0010: dup IL_0011: ldstr " " IL_0016: callvirt "Sub Custom.add(String)" IL_001b: dup IL_001c: ldstr "World" IL_0021: callvirt "Sub Custom.add(String)" IL_0026: call "Sub C1.Output(Custom)" IL_002b: ret } ]]>.Value) Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub Custom..ctor()) (OperationKind.ObjectCreation, Type: Custom) (Syntax: 'New Custom( ... ", "World"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Custom) (Syntax: 'From {"Hell ... ", "World"}') Initializers(3): IInvocationOperation ( Sub Custom.add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... ", "World"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') 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) IInvocationOperation ( Sub Custom.add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '" "') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... ", "World"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '" "') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "') 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) IInvocationOperation ( Sub Custom.add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"World"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... ", "World"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"World"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World") (Syntax: '"World"') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerEmptyInitializers() Dim source = <![CDATA[ Option Strict On Imports System.Collections.Generic Class C2 End Class Class C1 Public Shared Sub Main() ' ok Dim a As New List(Of Integer) From {} ' not ok Dim b As New List(Of Integer) From {{}}'BIND:"New List(Of Integer) From {{}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.List(Of System.Int32)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.List(Of System.Int32), IsInvalid) (Syntax: 'New List(Of ... ) From {{}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List(Of System.Int32), IsInvalid) (Syntax: 'From {{}}') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{}') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36721: An aggregate collection initializer entry must contain at least one element. Dim b As New List(Of Integer) From {{}}'BIND:"New List(Of Integer) From {{}}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerNotACollection() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim c As New C1() From {"Hello World!"}'BIND:"New C1() From {"Hello World!"}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'New C1() Fr ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C1, IsInvalid) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36718: Cannot initialize the type 'C1' with a collection initializer because it is not a collection type. Dim c As New C1() From {"Hello World!"}'BIND:"New C1() From {"Hello World!"}" ~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerCannotCombineBothInitializers() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Public a As String Public Sub Add(p As String) End Sub End Class Class C1 Public a As String Public Shared Sub Main()'BIND:"Public Shared Sub Main()" Dim a As New C2() With {.a = "goo"} From {"Hello World!"} Dim b As New C2() From {"Hello World!"} With {.a = "goo"} Dim c As C2 = New C2() From {"Hello World!"} With {.a = "goo"} Dim d As C2 = New C2() With {.a = "goo"} From {"Hello World!"} End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (6 statements, 4 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: 'Public Shar ... End Sub') Locals: Local_1: a As C2 Local_2: b As C2 Local_3: c As C2 Local_4: d As C2 IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ne ... .a = "goo"}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As New C2 ... .a = "goo"}') Declarators: IVariableDeclaratorOperation (Symbol: a As C2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C2() ... .a = "goo"}') IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2) (Syntax: 'New C2() Wi ... .a = "goo"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2) (Syntax: 'With {.a = "goo"}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: '.a = "goo"') Left: IFieldReferenceOperation: C2.a As System.String (OperationKind.FieldReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsImplicit) (Syntax: 'New C2() Wi ... .a = "goo"}') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "goo") (Syntax: '"goo"') IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim b As Ne ... lo World!"}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b As New C2 ... lo World!"}') Declarators: IVariableDeclaratorOperation (Symbol: b As C2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C2() ... lo World!"}') IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvocationOperation ( Sub C2.Add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello World!"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsImplicit) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"') 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) IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim c As C2 ... lo World!"}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c As C2 = N ... lo World!"}') Declarators: IVariableDeclaratorOperation (Symbol: c As C2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New C2() ... lo World!"}') IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2, IsInvalid) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2, IsInvalid) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvocationOperation ( Sub C2.Add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsInvalid, IsImplicit) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"') 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) IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim d As C2 ... .a = "goo"}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'd As C2 = N ... .a = "goo"}') Declarators: IVariableDeclaratorOperation (Symbol: d As C2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New C2() ... .a = "goo"}') IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2, IsInvalid) (Syntax: 'New C2() Wi ... .a = "goo"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2, IsInvalid) (Syntax: 'With {.a = "goo"}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: '.a = "goo"') Left: IFieldReferenceOperation: C2.a As System.String (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsInvalid, IsImplicit) (Syntax: 'New C2() Wi ... .a = "goo"}') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "goo", IsInvalid) (Syntax: '"goo"') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization. Dim a As New C2() With {.a = "goo"} From {"Hello World!"} ~~~~ BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization. Dim b As New C2() From {"Hello World!"} With {.a = "goo"} ~~~~ BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization. Dim c As C2 = New C2() From {"Hello World!"} With {.a = "goo"} ~~~~~~~~~~~~~~~~~~~~~ BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization. Dim d As C2 = New C2() With {.a = "goo"} From {"Hello World!"} ~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerNoAddMethod() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Class C3 Inherits C2 Protected Sub Add() End Sub End Class Class C4 Inherits C2 Public Property Add() As String End Class Class C5 Inherits C2 Public Add As String End Class Class C1 Public a As String Public Shared Sub Main() Dim a As New C2() From {"Hello World!"}'BIND:"New C2() From {"Hello World!"}" Dim b As New C3() From {"Hello World!"} Dim c As New C4() From {"Hello World!"} Dim d As New C5() From {"Hello World!"} End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2, IsInvalid) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2, IsInvalid) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36719: Cannot initialize the type 'C2' with a collection initializer because it does not have an accessible 'Add' method. Dim a As New C2() From {"Hello World!"}'BIND:"New C2() From {"Hello World!"}" ~~~~~~~~~~~~~~~~~~~~~ BC36719: Cannot initialize the type 'C3' with a collection initializer because it does not have an accessible 'Add' method. Dim b As New C3() From {"Hello World!"} ~~~~~~~~~~~~~~~~~~~~~ BC36719: Cannot initialize the type 'C4' with a collection initializer because it does not have an accessible 'Add' method. Dim c As New C4() From {"Hello World!"} ~~~~~~~~~~~~~~~~~~~~~ BC36719: Cannot initialize the type 'C5' with a collection initializer because it does not have an accessible 'Add' method. Dim d As New C5() From {"Hello World!"} ~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerAddMethodIsFunction() Dim source = <compilation name="CollectionInitializerAddMethodIsFunction"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class C1 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Public Function Add(p As Integer) As String Console.WriteLine("What's the point of returning something here?") return "Boo!" End Function End Class Class C2 Public Shared Sub Main() Dim x As New C1() From {1}'BIND:"New C1() From {1}" End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ What's the point of returning something here? ]]>) Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'New C1() From {1}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C1) (Syntax: 'From {1}') Initializers(1): IInvocationOperation ( Function C1.Add(p As System.Int32) As System.String) (OperationKind.Invocation, Type: System.String, IsImplicit) (Syntax: '1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'New C1() From {1}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerOverloadResolutionErrors() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Public Sub Add() End Sub Protected Sub Add(p As String) End Sub End Class Class C3 Inherits C2 ' first argument matches Public Overloads Sub Add(p As String, q As Integer) End Sub End Class Class C4 Inherits C2 ' first argument does not match -> multiple candidates Public Overloads Sub Add(p As Integer, q As String) End Sub End Class Class C5 Inherits C2 ' first argument does not match -> multiple candidates Public Overloads Sub Add(p As Byte) End Sub End Class Class C1 Public a As String Public Shared Sub Main() Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}" Dim b As New C3() From {"Hello World!"} Dim c As New C4() From {"Hello World!"} Dim d As New C5() From {300%} End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2, IsInvalid) (Syntax: 'From {"Hell ... r element"}') Initializers(2): IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsInvalid, IsImplicit) (Syntax: 'New C2() Fr ... r element"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"') IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"Errors wil ... er element"') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '"Errors wil ... er element"') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsInvalid, IsImplicit) (Syntax: 'New C2() Fr ... r element"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Errors will be shown for each initializer element", IsInvalid) (Syntax: '"Errors wil ... er element"') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30057: Too many arguments to 'Public Sub Add()'. Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}" ~~~~~~~~~~~~~~ BC30057: Too many arguments to 'Public Sub Add()'. Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'Add' accepts this number of arguments. Dim b As New C3() From {"Hello World!"} ~~~~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'Add' accepts this number of arguments. Dim c As New C4() From {"Hello World!"} ~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Byte'. Dim d As New C5() From {300%} ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerWarningsWillBeKept() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Public Shared Sub Add(p As String) End Sub End Class Class C1 Public a As String Public Shared Sub Main() Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2) (Syntax: 'New C2() Fr ... r element"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2) (Syntax: 'From {"Hell ... r element"}') Initializers(2): IInvocationOperation (Sub C2.Add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello World!"') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"') 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) IInvocationOperation (Sub C2.Add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Errors wil ... er element"') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Errors wil ... er element"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Errors will be shown for each initializer element") (Syntax: '"Errors wil ... er element"') 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}" ~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact()> Public Sub CollectionInitializerExtensionMethodsAreSupported() Dim source = <compilation name="CollectionInitializerExtensionMethodsAreSupported"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Runtime.CompilerServices Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Class C1 public a as string Public Shared Sub Main() ' extensions for custom type Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"} ' extensions for predefined type Dim x0 As LinkedList(Of Integer) = New LinkedList(Of Integer) From {1, 2, 3} End Sub End Class Module C2Extensions &lt;Extension()&gt; Public Sub Add(this as C2, p as string) End Sub &lt;Extension()&gt; Public Sub ADD(ByRef x As LinkedList(Of Integer), ByVal y As Integer) x.AddLast(y) End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub CollectionInitializerExtensionMethodsAreSupportedForValueTypes() Dim source = <compilation name="CollectionInitializerExtensionMethodsAreSupportedForValueTypes"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Runtime.CompilerServices Structure C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Structure Class C1 public a as string Public Shared Sub Main() Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"} End Sub End Class Module C2Extensions &lt;Extension()&gt; Public Sub Add(this as C2, p as string) End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub CollectionInitializerTypeConstraintsAreSupported() Dim source = <compilation name="CollectionInitializerTypeConstraintsAreSupported"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Public Interface IAdd(Of T) Sub Add(p As T) End Interface Public Class C2 Public Sub Add() End Sub End Class Class C3 Implements IAdd(Of String), ICollection private mylist as new list(of String)() Public Sub New() End Sub Public Sub Add1(p As String) Implements IAdd(Of String).Add mylist.add(p) End Sub Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return False End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return mylist.getenumerator End Function End Class Class C1 Public Shared Sub DoStuff(Of T As {IAdd(Of String), ICollection, New})() Dim a As New T() From {"Hello", " ", "World!"} for each str as string in a Console.Write(str) next str End Sub Public Shared Sub Main() DoStuff(Of C3)() End Sub End Class </file> </compilation> CompileAndVerify(source, "Hello World!") End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerTypeConstraintsAndAmbiguity() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Public Interface IAdd(Of T) Sub Add(p As String) End Interface Class C1 Public Shared Sub DoStuff(Of T As {IAdd(Of String), IAdd(Of Integer), ICollection, New})() Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}" For Each str As String In a Console.Write(str) Next str End Sub Public Shared Sub Main() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeParameterObjectCreationOperation (OperationKind.TypeParameterObjectCreation, Type: T, IsInvalid) (Syntax: 'New T() Fro ... , "World!"}') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: 'From {"Hell ... , "World!"}') Initializers(3): IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"Hello"') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '"Hello"') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'New T() Fro ... , "World!"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello", IsInvalid) (Syntax: '"Hello"') IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '" "') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '" "') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'New T() Fro ... , "World!"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ", IsInvalid) (Syntax: '" "') IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"World!"') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '"World!"') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'New T() Fro ... , "World!"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World!", IsInvalid) (Syntax: '"World!"') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments: 'Sub IAdd(Of String).Add(p As String)': Not most specific. 'Sub IAdd(Of Integer).Add(p As String)': Not most specific. Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}" ~~~~~~~ BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments: 'Sub IAdd(Of String).Add(p As String)': Not most specific. 'Sub IAdd(Of Integer).Add(p As String)': Not most specific. Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}" ~~~ BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments: 'Sub IAdd(Of String).Add(p As String)': Not most specific. 'Sub IAdd(Of Integer).Add(p As String)': Not most specific. Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(529265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529265")> <Fact()> Public Sub CollectionInitializerCollectionInitializerArityCheck() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid) (Syntax: 'New Diction ... From {{1}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid) (Syntax: 'From {{1}}') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '{1}') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '{1}') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid, IsImplicit) (Syntax: 'New Diction ... From {{1}}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30455: Argument not specified for parameter 'value' of 'Public Overloads Sub Add(key As String, value As Integer)'. Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}" ~~~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact()> Public Sub CollectionInitializerReferencingItself() Dim source = <compilation name="CollectionInitializerReferencingItselfRefType"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Imports System.Collections Interface IMissingStuff Sub Add(p As String) Function Item() As String End Interface Structure Custom Implements IMissingStuff, IEnumerable(Of String) Public Shared list As New List(Of String)() Public Sub Add(p As String) Implements IMissingStuff.Add list.Add(p) End Sub Public Function Item() As String Implements IMissingStuff.Item Return Nothing End Function Public Structure CustomEnumerator Implements IEnumerator(Of String) Private list As List(Of String) Private Shared index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property Public ReadOnly Property Current1 As String Implements IEnumerator(Of String).Current Get Return Current End Get End Property Public ReadOnly Property Current2 As Object Implements IEnumerator.Current Get Return Current End Get End Property Public Function MoveNext1() As Boolean Implements IEnumerator.MoveNext Return MoveNext() End Function Public Sub Reset() Implements IEnumerator.Reset End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub end structure Public Function GetEnumerator1() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator Return New CustomEnumerator(list) End Function Public Function GetEnumerator2() As IEnumerator Implements IEnumerable.GetEnumerator Return New CustomEnumerator(list) End Function End Structure Structure CustomNonEmpty Implements IMissingStuff, IEnumerable(Of String) Public MakeItNonEmpty as String Public Shared list As New List(Of String)() Public Sub Add(p As String) Implements IMissingStuff.Add list.Add(p) End Sub Public Function Item() As String Implements IMissingStuff.Item Return Nothing End Function Public Structure CustomEnumerator Implements IEnumerator(Of String) Private list As List(Of String) Private Shared index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property Public ReadOnly Property Current1 As String Implements IEnumerator(Of String).Current Get Return Current End Get End Property Public ReadOnly Property Current2 As Object Implements IEnumerator.Current Get Return Current End Get End Property Public Function MoveNext1() As Boolean Implements IEnumerator.MoveNext Return MoveNext() End Function Public Sub Reset() Implements IEnumerator.Reset End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub end structure Public Function GetEnumerator1() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator Return New CustomEnumerator(list) End Function Public Function GetEnumerator2() As IEnumerator Implements IEnumerable.GetEnumerator Return New CustomEnumerator(list) End Function End Structure Class CBase(Of T) Public Overridable Sub TypeParameterValueTypeAsClassConstraint(Of U As {T, IEnumerable, IMissingStuff})() End Sub End Class Class CDerived Inherits CBase(Of Custom) Public Overrides Sub TypeParameterValueTypeAsClassConstraint(Of U As {Custom, IEnumerable, IMissingStuff})() Dim m As New U From {"Hello World!", m.Item(0)} ' temp used, m is uninitialized, show warning Dim n As U = New U() From {"Hello World!", n.Item(0)} ' temp used, h is uninitialized, show warning Dim o, p As New U() From {o.Item(0), p.Item(0)} ' temps used, show warnings (although o is initialized when initializing p) End Sub End Class Class C1 Public Sub TypeParameterNotDefined(Of T As {IEnumerable, IMissingStuff, New})() ' no warnings from type parameters as well Dim e As New T From {"Hello World!", e.Item(0)} ' Receiver type unknown, no warning Dim f As T = New T() From {"Hello World!", f.Item(0)} ' Receiver type unknown, no warning End Sub Public Sub TypeParameterAsStructure(Of T As {Structure, IEnumerable, IMissingStuff})() ' no warnings from type parameters as well Dim g As New T From {"Hello World!", g.Item(0)} ' temp used, g is uninitialized, show warning Dim h As T = New T() From {"Hello World!", h.Item(0)} ' temp used, h is uninitialized, show warning Dim i, j As New T() From {i.Item(0), j.Item(0)} ' temps used, show warnings (although i is initialized when initializing j) End Sub Public Sub TypeParameterAsRefType(Of T As {List(Of String), new})() Dim k As New T From {"Hello World!", k.Item(0)} ' temp used, k is uninitialized, show warning Dim l As T = New T() From {"Hello World!", l.Item(0)} ' temp used, l is uninitialized, show warning End Sub Public Shared Sub Main() Dim a As New Custom From {"Hello World!", a.Item(0)} ' empty, non trackable structure, no warning Dim b As Custom = New Custom() From {"Hello World!", b.Item(0)} ' empty, non trackable structure, no warning Dim q As New CustomNonEmpty From {"Hello World!", q.Item(0)} ' temp used, q is uninitialized, show warning Dim r As CustomNonEmpty = New CustomNonEmpty() From {"Hello World!", r.Item(0)} ' temp used, r is uninitialized, show warning ' reference types are not ok, they are still Nothing Dim c As New List(Of String) From {"Hello World!", c.Item(0)} ' show warning Dim d As List(Of String) = New List(Of String)() From {"Hello World!", d.Item(0)} ' show warning ' was already assigned, no warning again. c = New List(Of String)() From {"Hello World!", c.Item(0)} ' no warning End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) AssertTheseDiagnostics(compilation, <expected> BC42109: Variable 'm' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim m As New U From {"Hello World!", m.Item(0)} ' temp used, m is uninitialized, show warning ~ BC42109: Variable 'n' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim n As U = New U() From {"Hello World!", n.Item(0)} ' temp used, h is uninitialized, show warning ~ BC42109: Variable 'o' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim o, p As New U() From {o.Item(0), p.Item(0)} ' temps used, show warnings (although o is initialized when initializing p) ~ BC42109: Variable 'p' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim o, p As New U() From {o.Item(0), p.Item(0)} ' temps used, show warnings (although o is initialized when initializing p) ~ BC42109: Variable 'g' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim g As New T From {"Hello World!", g.Item(0)} ' temp used, g is uninitialized, show warning ~ BC42109: Variable 'h' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim h As T = New T() From {"Hello World!", h.Item(0)} ' temp used, h is uninitialized, show warning ~ BC42109: Variable 'i' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim i, j As New T() From {i.Item(0), j.Item(0)} ' temps used, show warnings (although i is initialized when initializing j) ~ BC42109: Variable 'j' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim i, j As New T() From {i.Item(0), j.Item(0)} ' temps used, show warnings (although i is initialized when initializing j) ~ BC42104: Variable 'k' is used before it has been assigned a value. A null reference exception could result at runtime. Dim k As New T From {"Hello World!", k.Item(0)} ' temp used, k is uninitialized, show warning ~ BC42104: Variable 'l' is used before it has been assigned a value. A null reference exception could result at runtime. Dim l As T = New T() From {"Hello World!", l.Item(0)} ' temp used, l is uninitialized, show warning ~ BC42109: Variable 'q' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim q As New CustomNonEmpty From {"Hello World!", q.Item(0)} ' temp used, q is uninitialized, show warning ~ BC42109: Variable 'r' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim r As CustomNonEmpty = New CustomNonEmpty() From {"Hello World!", r.Item(0)} ' temp used, r is uninitialized, show warning ~ BC42104: Variable 'c' is used before it has been assigned a value. A null reference exception could result at runtime. Dim c As New List(Of String) From {"Hello World!", c.Item(0)} ' show warning ~ BC42104: Variable 'd' is used before it has been assigned a value. A null reference exception could result at runtime. Dim d As List(Of String) = New List(Of String)() From {"Hello World!", d.Item(0)} ' show warning ~ </expected>) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerReferencingItself_2() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Module Program Sub Main(args As String()) Dim x, y As New List(Of String)() From {"1", x.Item(0)}'BIND:"New List(Of String)() From {"1", x.Item(0)}" Dim z As New List(Of String)() From {"1", z.Item(0)} End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ... x.Item(0)}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {"1", x.Item(0)}') Initializers(2): IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"1"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... x.Item(0)}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"1"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "1") (Syntax: '"1"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x.Item(0)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... x.Item(0)}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.Item(0)') IPropertyReferenceOperation: Property System.Collections.Generic.List(Of System.String).Item(index As System.Int32) As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'x.Item(0)') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'x') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Dim x, y As New List(Of String)() From {"1", x.Item(0)}'BIND:"New List(Of String)() From {"1", x.Item(0)}" ~ BC42104: Variable 'z' is used before it has been assigned a value. A null reference exception could result at runtime. Dim z As New List(Of String)() From {"1", z.Item(0)} ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerCustomCollectionOptionalParameter() Dim source = <compilation name="CollectionInitializerCustomCollection"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class Custom Private list As New List(Of String)() Public Function GetEnumerator() As CustomEnumerator Return New CustomEnumerator(list) End Function Public Sub add(p As String, optional p2 as String = " ") list.Add(p) list.Add(p2) End Sub Public Class CustomEnumerator Private list As list(Of String) Private index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If Me.index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim c as Custom = New Custom() From {"Hello", {"World", "!"}}'BIND:"New Custom() From {"Hello", {"World", "!"}}" Output(c) End Sub Public Shared Sub Output(c as custom) For Each value In c Console.Write(value) Next End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Hello World! ]]>) Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub Custom..ctor()) (OperationKind.ObjectCreation, Type: Custom) (Syntax: 'New Custom( ... rld", "!"}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Custom) (Syntax: 'From {"Hell ... rld", "!"}}') Initializers(2): IInvocationOperation ( Sub Custom.add(p As System.String, [p2 As System.String = " "])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... rld", "!"}}') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: p2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ", IsImplicit) (Syntax: '"Hello"') 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) IInvocationOperation ( Sub Custom.add(p As System.String, [p2 As System.String = " "])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"World", "!"}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... rld", "!"}}') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"World"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World") (Syntax: '"World"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "!") (Syntax: '"!"') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <Fact()> Public Sub CollectionInitializerCustomCollectionParamArray() Dim source = <compilation name="CollectionInitializerCustomCollection"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class Custom Private list As New List(Of String)() Public Function GetEnumerator() As CustomEnumerator Return New CustomEnumerator(list) End Function Public Sub add(paramarray p() As String) list.AddRange(p) End Sub Public Class CustomEnumerator Private list As list(Of String) Private index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If Me.index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim c as Custom = New Custom() From {"Hello", {" ", "World"}, ({"!", "!", "!"})} Output(c) End Sub Public Shared Sub Output(c as custom) For Each value In c Console.Write(value) Next End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Hello World!!! ]]>) End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_01() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic class X Inherits List(Of Integer) Sub Add(x As Integer) End Sub Sub Add(x As String) End Sub Shared Sub Main() Dim z = new X() From { String.Empty, 'BIND1:"String.Empty" 12} 'BIND2:"12" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo If True Then Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Sub X.Add(x As System.String)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End If If True Then Dim node2 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 2) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node2) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Sub X.Add(x As System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End If End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_02() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic class X Inherits List(Of Integer) Sub Add(x As X) End Sub Sub Add(x As List(Of Byte)) End Sub Shared Sub Main() Dim z = new X() From { String.Empty } 'BIND1:"String.Empty" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal({"Sub X.Add(x As System.Collections.Generic.List(Of System.Byte))", "Sub X.Add(x As X)"}, symbolInfo.CandidateSymbols.Select(Function(s) s.ToTestDisplayString()).Order().ToArray()) End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_03() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Class Base Implements IEnumerable(Of Integer) End Class class X Inherits Base Protected Sub Add(x As String) End Sub End Class class Y Shared Sub Main() Dim z = new X() From { String.Empty } 'BIND1:"String.Empty" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_04() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic class X Inherits List(Of Integer) Sub Add(x As String, y As Integer) End Sub Shared Sub Main() Dim z = new X() From { {String.Empty, 12} } 'BIND1:"{String.Empty, 12}" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Sub X.Add(x As System.String, y As System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_05() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic class X Inherits List(Of Integer) Sub Add(x As String, y As Integer) End Sub Shared Sub Main() Dim z = new X() From { {String.Empty, 'BIND1:"String.Empty" 12} } 'BIND2:"12" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo For i As Integer = 1 To 2 Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", i) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Next End Sub <Fact()> <WorkItem(12983, "https://github.com/dotnet/roslyn/issues/12983")> Public Sub GetCollectionInitializerSymbolInfo_06() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim list1 = new List(Of String) Dim list2 = new List(Of String)() Dim list3 = new List(Of String) With { .Count = 3 } Dim list4 = new List(Of String)() With { .Count = 3 } Dim list5 = new List(Of String) From { 1, 2, 3 } Dim list6 = new List(Of String)() From { 1, 2, 3 } End Sub End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees.Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of GenericNameSyntax)().ToArray() Assert.Equal(6, nodes.Length) For Each name In nodes Assert.Equal("List(Of String)", name.ToString()) Assert.Equal("System.Collections.Generic.List(Of System.String)", semanticModel.GetSymbolInfo(name).Symbol.ToTestDisplayString()) Assert.Null(semanticModel.GetTypeInfo(name).Type) Next End Sub <Fact()> <WorkItem(27034, "https://github.com/dotnet/roslyn/issues/27034")> Public Sub LateBoundCollectionInitializer() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections Imports System.Collections.Generic Module Mod1 Sub Main(args() As String) Dim c As New C() c.M(1) End Sub Class C Implements IEnumerable(Of Integer) Public Sub M(a As Object) Dim c = New C From {a} End Sub Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Public Sub Add(i As Integer) Console.WriteLine("Called Integer Add") End Sub Public Sub Add(l As Long) Console.WriteLine("Called Long Add") End Sub End Class End Module </file> </compilation> Dim verifier = CompileAndVerify(source, expectedOutput:="Called Integer Add") verifier.VerifyIL("Mod1.C.M", <![CDATA[ { // Code size 62 (0x3e) .maxstack 10 .locals init (Mod1.C V_0, Object() V_1, Boolean() V_2) IL_0000: newobj "Sub Mod1.C..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldnull IL_0008: ldstr "Add" IL_000d: ldc.i4.1 IL_000e: newarr "Object" IL_0013: dup IL_0014: ldc.i4.0 IL_0015: ldarg.1 IL_0016: stelem.ref IL_0017: dup IL_0018: stloc.1 IL_0019: ldnull IL_001a: ldnull IL_001b: ldc.i4.1 IL_001c: newarr "Boolean" IL_0021: dup IL_0022: ldc.i4.0 IL_0023: ldc.i4.1 IL_0024: stelem.i1 IL_0025: dup IL_0026: stloc.2 IL_0027: ldc.i4.1 IL_0028: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object" IL_002d: pop IL_002e: ldloc.2 IL_002f: ldc.i4.0 IL_0030: ldelem.u1 IL_0031: brfalse.s IL_003d IL_0033: ldloc.1 IL_0034: ldc.i4.0 IL_0035: ldelem.ref IL_0036: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_003b: starg.s V_1 IL_003d: ret } ]]>) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class BindingCollectionInitializerTests Inherits BasicTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerList() Dim source = <compilation name="CollectionInitializerList"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim c As New List(Of String) From {"Hello World!"} 'BIND:"New List(Of String) From {"Hello World!"}" Console.WriteLine(c(0)) End Sub End Class </file> </compilation> CompileAndVerify(source, "Hello World!") Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello World!"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... lo World!"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerListEachElementAsCollectionInitializer() Dim source = <compilation name="CollectionInitializerListEachElementAsCollectionInitializer"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim c As New List(Of String) From {{"Hello"}, {" "}, {"World!"}}'BIND:"New List(Of String) From {{"Hello"}, {" "}, {"World!"}}" For each element in c Console.Write(element) next element End Sub End Class </file> </compilation> CompileAndVerify(source, "Hello World!") Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ... {"World!"}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {{"Hel ... {"World!"}}') Initializers(3): IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"Hello"}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... {"World!"}}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') 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) IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{" "}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... {"World!"}}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '" "') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "') 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) IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"World!"}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... {"World!"}}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World!") (Syntax: '"World!"') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerDictionary() Dim source = <compilation name="CollectionInitializerDictionary"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim c As New Dictionary(Of String, Integer) From {{"Hello", 23}, {"World", 42}}'BIND:"New Dictionary(Of String, Integer) From {{"Hello", 23}, {"World", 42}}" For Each keyValue In c Console.WriteLine(keyValue.Key + " " + keyValue.Value.ToString) Next End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Hello 23 World 42 ]]>) Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32)) (Syntax: 'New Diction ... orld", 42}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32)) (Syntax: 'From {{"Hel ... orld", 42}}') Initializers(2): IInvocationOperation ( Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32).Add(key As System.String, value As System.Int32)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"Hello", 23}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsImplicit) (Syntax: 'New Diction ... orld", 42}}') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '23') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 23) (Syntax: '23') 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) IInvocationOperation ( Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32).Add(key As System.String, value As System.Int32)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"World", 42}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsImplicit) (Syntax: 'New Diction ... orld", 42}}') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: key) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"World"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World") (Syntax: '"World"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '42') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42) (Syntax: '42') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerCustomCollection() Dim source = <compilation name="CollectionInitializerCustomCollection"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class Custom Private list As New List(Of String)() Public Function GetEnumerator() As CustomEnumerator Return New CustomEnumerator(list) End Function Public Sub add(p As String) list.Add(p) End Sub Public Class CustomEnumerator Private list As list(Of String) Private index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If Me.index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim c as Custom = New Custom() From {"Hello", " ", "World"}'BIND:"New Custom() From {"Hello", " ", "World"}" Output(c) End Sub Public Shared Sub Output(c as custom) For Each value In c Console.Write(value) Next End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Hello World ]]>).VerifyIL("C1.Main", <![CDATA[ { // Code size 44 (0x2c) .maxstack 3 IL_0000: newobj "Sub Custom..ctor()" IL_0005: dup IL_0006: ldstr "Hello" IL_000b: callvirt "Sub Custom.add(String)" IL_0010: dup IL_0011: ldstr " " IL_0016: callvirt "Sub Custom.add(String)" IL_001b: dup IL_001c: ldstr "World" IL_0021: callvirt "Sub Custom.add(String)" IL_0026: call "Sub C1.Output(Custom)" IL_002b: ret } ]]>.Value) Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub Custom..ctor()) (OperationKind.ObjectCreation, Type: Custom) (Syntax: 'New Custom( ... ", "World"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Custom) (Syntax: 'From {"Hell ... ", "World"}') Initializers(3): IInvocationOperation ( Sub Custom.add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... ", "World"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') 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) IInvocationOperation ( Sub Custom.add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '" "') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... ", "World"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '" "') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "') 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) IInvocationOperation ( Sub Custom.add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"World"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... ", "World"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"World"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World") (Syntax: '"World"') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerEmptyInitializers() Dim source = <![CDATA[ Option Strict On Imports System.Collections.Generic Class C2 End Class Class C1 Public Shared Sub Main() ' ok Dim a As New List(Of Integer) From {} ' not ok Dim b As New List(Of Integer) From {{}}'BIND:"New List(Of Integer) From {{}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.List(Of System.Int32)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.List(Of System.Int32), IsInvalid) (Syntax: 'New List(Of ... ) From {{}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List(Of System.Int32), IsInvalid) (Syntax: 'From {{}}') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{}') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36721: An aggregate collection initializer entry must contain at least one element. Dim b As New List(Of Integer) From {{}}'BIND:"New List(Of Integer) From {{}}" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerNotACollection() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim c As New C1() From {"Hello World!"}'BIND:"New C1() From {"Hello World!"}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'New C1() Fr ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C1, IsInvalid) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36718: Cannot initialize the type 'C1' with a collection initializer because it is not a collection type. Dim c As New C1() From {"Hello World!"}'BIND:"New C1() From {"Hello World!"}" ~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerCannotCombineBothInitializers() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Public a As String Public Sub Add(p As String) End Sub End Class Class C1 Public a As String Public Shared Sub Main()'BIND:"Public Shared Sub Main()" Dim a As New C2() With {.a = "goo"} From {"Hello World!"} Dim b As New C2() From {"Hello World!"} With {.a = "goo"} Dim c As C2 = New C2() From {"Hello World!"} With {.a = "goo"} Dim d As C2 = New C2() With {.a = "goo"} From {"Hello World!"} End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IBlockOperation (6 statements, 4 locals) (OperationKind.Block, Type: null, IsInvalid) (Syntax: 'Public Shar ... End Sub') Locals: Local_1: a As C2 Local_2: b As C2 Local_3: c As C2 Local_4: d As C2 IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ne ... .a = "goo"}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As New C2 ... .a = "goo"}') Declarators: IVariableDeclaratorOperation (Symbol: a As C2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C2() ... .a = "goo"}') IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2) (Syntax: 'New C2() Wi ... .a = "goo"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2) (Syntax: 'With {.a = "goo"}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: '.a = "goo"') Left: IFieldReferenceOperation: C2.a As System.String (OperationKind.FieldReference, Type: System.String) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsImplicit) (Syntax: 'New C2() Wi ... .a = "goo"}') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "goo") (Syntax: '"goo"') IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim b As Ne ... lo World!"}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'b As New C2 ... lo World!"}') Declarators: IVariableDeclaratorOperation (Symbol: b As C2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'b') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: 'As New C2() ... lo World!"}') IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvocationOperation ( Sub C2.Add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello World!"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsImplicit) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"') 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) IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim c As C2 ... lo World!"}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'c As C2 = N ... lo World!"}') Declarators: IVariableDeclaratorOperation (Symbol: c As C2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'c') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New C2() ... lo World!"}') IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2, IsInvalid) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2, IsInvalid) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvocationOperation ( Sub C2.Add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsInvalid, IsImplicit) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"') 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) IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim d As C2 ... .a = "goo"}') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'd As C2 = N ... .a = "goo"}') Declarators: IVariableDeclaratorOperation (Symbol: d As C2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'd') Initializer: null Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New C2() ... .a = "goo"}') IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2, IsInvalid) (Syntax: 'New C2() Wi ... .a = "goo"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2, IsInvalid) (Syntax: 'With {.a = "goo"}') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsInvalid) (Syntax: '.a = "goo"') Left: IFieldReferenceOperation: C2.a As System.String (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'a') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsInvalid, IsImplicit) (Syntax: 'New C2() Wi ... .a = "goo"}') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "goo", IsInvalid) (Syntax: '"goo"') ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub') Statement: null IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub') ReturnedValue: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization. Dim a As New C2() With {.a = "goo"} From {"Hello World!"} ~~~~ BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization. Dim b As New C2() From {"Hello World!"} With {.a = "goo"} ~~~~ BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization. Dim c As C2 = New C2() From {"Hello World!"} With {.a = "goo"} ~~~~~~~~~~~~~~~~~~~~~ BC36720: An Object Initializer and a Collection Initializer cannot be combined in the same initialization. Dim d As C2 = New C2() With {.a = "goo"} From {"Hello World!"} ~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerNoAddMethod() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Class C3 Inherits C2 Protected Sub Add() End Sub End Class Class C4 Inherits C2 Public Property Add() As String End Class Class C5 Inherits C2 Public Add As String End Class Class C1 Public a As String Public Shared Sub Main() Dim a As New C2() From {"Hello World!"}'BIND:"New C2() From {"Hello World!"}" Dim b As New C3() From {"Hello World!"} Dim c As New C4() From {"Hello World!"} Dim d As New C5() From {"Hello World!"} End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2, IsInvalid) (Syntax: 'New C2() Fr ... lo World!"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2, IsInvalid) (Syntax: 'From {"Hello World!"}') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC36719: Cannot initialize the type 'C2' with a collection initializer because it does not have an accessible 'Add' method. Dim a As New C2() From {"Hello World!"}'BIND:"New C2() From {"Hello World!"}" ~~~~~~~~~~~~~~~~~~~~~ BC36719: Cannot initialize the type 'C3' with a collection initializer because it does not have an accessible 'Add' method. Dim b As New C3() From {"Hello World!"} ~~~~~~~~~~~~~~~~~~~~~ BC36719: Cannot initialize the type 'C4' with a collection initializer because it does not have an accessible 'Add' method. Dim c As New C4() From {"Hello World!"} ~~~~~~~~~~~~~~~~~~~~~ BC36719: Cannot initialize the type 'C5' with a collection initializer because it does not have an accessible 'Add' method. Dim d As New C5() From {"Hello World!"} ~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerAddMethodIsFunction() Dim source = <compilation name="CollectionInitializerAddMethodIsFunction"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class C1 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Public Function Add(p As Integer) As String Console.WriteLine("What's the point of returning something here?") return "Boo!" End Function End Class Class C2 Public Shared Sub Main() Dim x As New C1() From {1}'BIND:"New C1() From {1}" End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ What's the point of returning something here? ]]>) Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub C1..ctor()) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'New C1() From {1}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C1) (Syntax: 'From {1}') Initializers(1): IInvocationOperation ( Function C1.Add(p As System.Int32) As System.String) (OperationKind.Invocation, Type: System.String, IsImplicit) (Syntax: '1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'New C1() From {1}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerOverloadResolutionErrors() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Public Sub Add() End Sub Protected Sub Add(p As String) End Sub End Class Class C3 Inherits C2 ' first argument matches Public Overloads Sub Add(p As String, q As Integer) End Sub End Class Class C4 Inherits C2 ' first argument does not match -> multiple candidates Public Overloads Sub Add(p As Integer, q As String) End Sub End Class Class C5 Inherits C2 ' first argument does not match -> multiple candidates Public Overloads Sub Add(p As Byte) End Sub End Class Class C1 Public a As String Public Shared Sub Main() Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}" Dim b As New C3() From {"Hello World!"} Dim c As New C4() From {"Hello World!"} Dim d As New C5() From {300%} End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2, IsInvalid) (Syntax: 'From {"Hell ... r element"}') Initializers(2): IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '"Hello World!"') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsInvalid, IsImplicit) (Syntax: 'New C2() Fr ... r element"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!", IsInvalid) (Syntax: '"Hello World!"') IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"Errors wil ... er element"') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '"Errors wil ... er element"') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C2, IsInvalid, IsImplicit) (Syntax: 'New C2() Fr ... r element"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Errors will be shown for each initializer element", IsInvalid) (Syntax: '"Errors wil ... er element"') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30057: Too many arguments to 'Public Sub Add()'. Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}" ~~~~~~~~~~~~~~ BC30057: Too many arguments to 'Public Sub Add()'. Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"From {"Hello World!", "Errors will be shown for each initializer element"}" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'Add' accepts this number of arguments. Dim b As New C3() From {"Hello World!"} ~~~~~~~~~~~~~~ BC30516: Overload resolution failed because no accessible 'Add' accepts this number of arguments. Dim c As New C4() From {"Hello World!"} ~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Byte'. Dim d As New C5() From {300%} ~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCollectionInitializerSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerWarningsWillBeKept() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function Public Shared Sub Add(p As String) End Sub End Class Class C1 Public a As String Public Shared Sub Main() Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub C2..ctor()) (OperationKind.ObjectCreation, Type: C2) (Syntax: 'New C2() Fr ... r element"}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C2) (Syntax: 'From {"Hell ... r element"}') Initializers(2): IInvocationOperation (Sub C2.Add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello World!"') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello World!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World!") (Syntax: '"Hello World!"') 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) IInvocationOperation (Sub C2.Add(p As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Errors wil ... er element"') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Errors wil ... er element"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Errors will be shown for each initializer element") (Syntax: '"Errors wil ... er element"') 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}" ~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"}'BIND:"New C2() From {"Hello World!", "Errors will be shown for each initializer element"}" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact()> Public Sub CollectionInitializerExtensionMethodsAreSupported() Dim source = <compilation name="CollectionInitializerExtensionMethodsAreSupported"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Runtime.CompilerServices Class C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Class Class C1 public a as string Public Shared Sub Main() ' extensions for custom type Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"} ' extensions for predefined type Dim x0 As LinkedList(Of Integer) = New LinkedList(Of Integer) From {1, 2, 3} End Sub End Class Module C2Extensions &lt;Extension()&gt; Public Sub Add(this as C2, p as string) End Sub &lt;Extension()&gt; Public Sub ADD(ByRef x As LinkedList(Of Integer), ByVal y As Integer) x.AddLast(y) End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub CollectionInitializerExtensionMethodsAreSupportedForValueTypes() Dim source = <compilation name="CollectionInitializerExtensionMethodsAreSupportedForValueTypes"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Runtime.CompilerServices Structure C2 Implements ICollection Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return Nothing End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return Nothing End Function End Structure Class C1 public a as string Public Shared Sub Main() Dim a As New C2() From {"Hello World!", "Errors will be shown for each initializer element"} End Sub End Class Module C2Extensions &lt;Extension()&gt; Public Sub Add(this as C2, p as string) End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) AssertTheseDiagnostics(compilation, <expected> </expected>) End Sub <Fact()> Public Sub CollectionInitializerTypeConstraintsAreSupported() Dim source = <compilation name="CollectionInitializerTypeConstraintsAreSupported"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Public Interface IAdd(Of T) Sub Add(p As T) End Interface Public Class C2 Public Sub Add() End Sub End Class Class C3 Implements IAdd(Of String), ICollection private mylist as new list(of String)() Public Sub New() End Sub Public Sub Add1(p As String) Implements IAdd(Of String).Add mylist.add(p) End Sub Public Sub CopyTo(array As Array, index As Integer) Implements ICollection.CopyTo End Sub Public ReadOnly Property Count As Integer Implements ICollection.Count Get Return 0 End Get End Property Public ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized Get Return False End Get End Property Public ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot Get Return False End Get End Property Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return mylist.getenumerator End Function End Class Class C1 Public Shared Sub DoStuff(Of T As {IAdd(Of String), ICollection, New})() Dim a As New T() From {"Hello", " ", "World!"} for each str as string in a Console.Write(str) next str End Sub Public Shared Sub Main() DoStuff(Of C3)() End Sub End Class </file> </compilation> CompileAndVerify(source, "Hello World!") End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerTypeConstraintsAndAmbiguity() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections Imports System.Collections.Generic Public Interface IAdd(Of T) Sub Add(p As String) End Interface Class C1 Public Shared Sub DoStuff(Of T As {IAdd(Of String), IAdd(Of Integer), ICollection, New})() Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}" For Each str As String In a Console.Write(str) Next str End Sub Public Shared Sub Main() End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeParameterObjectCreationOperation (OperationKind.TypeParameterObjectCreation, Type: T, IsInvalid) (Syntax: 'New T() Fro ... , "World!"}') Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: T, IsInvalid) (Syntax: 'From {"Hell ... , "World!"}') Initializers(3): IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"Hello"') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '"Hello"') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'New T() Fro ... , "World!"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello", IsInvalid) (Syntax: '"Hello"') IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '" "') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '" "') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'New T() Fro ... , "World!"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ", IsInvalid) (Syntax: '" "') IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '"World!"') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '"World!"') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: T, IsInvalid, IsImplicit) (Syntax: 'New T() Fro ... , "World!"}') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World!", IsInvalid) (Syntax: '"World!"') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments: 'Sub IAdd(Of String).Add(p As String)': Not most specific. 'Sub IAdd(Of Integer).Add(p As String)': Not most specific. Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}" ~~~~~~~ BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments: 'Sub IAdd(Of String).Add(p As String)': Not most specific. 'Sub IAdd(Of Integer).Add(p As String)': Not most specific. Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}" ~~~ BC30521: Overload resolution failed because no accessible 'Add' is most specific for these arguments: 'Sub IAdd(Of String).Add(p As String)': Not most specific. 'Sub IAdd(Of Integer).Add(p As String)': Not most specific. Dim a As New T() From {"Hello", " ", "World!"}'BIND:"New T() From {"Hello", " ", "World!"}" ~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <WorkItem(529265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529265")> <Fact()> Public Sub CollectionInitializerCollectionInitializerArityCheck() Dim source = <![CDATA[ Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.Dictionary(Of System.String, System.Int32)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid) (Syntax: 'New Diction ... From {{1}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid) (Syntax: 'From {{1}}') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: '{1}') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: '{1}') Children(1): IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.Dictionary(Of System.String, System.Int32), IsInvalid, IsImplicit) (Syntax: 'New Diction ... From {{1}}') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30455: Argument not specified for parameter 'value' of 'Public Overloads Sub Add(key As String, value As Integer)'. Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}" ~~~ BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'. Dim x As New Dictionary(Of String, Integer) From {{1}}'BIND:"New Dictionary(Of String, Integer) From {{1}}" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <Fact()> Public Sub CollectionInitializerReferencingItself() Dim source = <compilation name="CollectionInitializerReferencingItselfRefType"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Imports System.Collections Interface IMissingStuff Sub Add(p As String) Function Item() As String End Interface Structure Custom Implements IMissingStuff, IEnumerable(Of String) Public Shared list As New List(Of String)() Public Sub Add(p As String) Implements IMissingStuff.Add list.Add(p) End Sub Public Function Item() As String Implements IMissingStuff.Item Return Nothing End Function Public Structure CustomEnumerator Implements IEnumerator(Of String) Private list As List(Of String) Private Shared index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property Public ReadOnly Property Current1 As String Implements IEnumerator(Of String).Current Get Return Current End Get End Property Public ReadOnly Property Current2 As Object Implements IEnumerator.Current Get Return Current End Get End Property Public Function MoveNext1() As Boolean Implements IEnumerator.MoveNext Return MoveNext() End Function Public Sub Reset() Implements IEnumerator.Reset End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub end structure Public Function GetEnumerator1() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator Return New CustomEnumerator(list) End Function Public Function GetEnumerator2() As IEnumerator Implements IEnumerable.GetEnumerator Return New CustomEnumerator(list) End Function End Structure Structure CustomNonEmpty Implements IMissingStuff, IEnumerable(Of String) Public MakeItNonEmpty as String Public Shared list As New List(Of String)() Public Sub Add(p As String) Implements IMissingStuff.Add list.Add(p) End Sub Public Function Item() As String Implements IMissingStuff.Item Return Nothing End Function Public Structure CustomEnumerator Implements IEnumerator(Of String) Private list As List(Of String) Private Shared index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property Public ReadOnly Property Current1 As String Implements IEnumerator(Of String).Current Get Return Current End Get End Property Public ReadOnly Property Current2 As Object Implements IEnumerator.Current Get Return Current End Get End Property Public Function MoveNext1() As Boolean Implements IEnumerator.MoveNext Return MoveNext() End Function Public Sub Reset() Implements IEnumerator.Reset End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub end structure Public Function GetEnumerator1() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator Return New CustomEnumerator(list) End Function Public Function GetEnumerator2() As IEnumerator Implements IEnumerable.GetEnumerator Return New CustomEnumerator(list) End Function End Structure Class CBase(Of T) Public Overridable Sub TypeParameterValueTypeAsClassConstraint(Of U As {T, IEnumerable, IMissingStuff})() End Sub End Class Class CDerived Inherits CBase(Of Custom) Public Overrides Sub TypeParameterValueTypeAsClassConstraint(Of U As {Custom, IEnumerable, IMissingStuff})() Dim m As New U From {"Hello World!", m.Item(0)} ' temp used, m is uninitialized, show warning Dim n As U = New U() From {"Hello World!", n.Item(0)} ' temp used, h is uninitialized, show warning Dim o, p As New U() From {o.Item(0), p.Item(0)} ' temps used, show warnings (although o is initialized when initializing p) End Sub End Class Class C1 Public Sub TypeParameterNotDefined(Of T As {IEnumerable, IMissingStuff, New})() ' no warnings from type parameters as well Dim e As New T From {"Hello World!", e.Item(0)} ' Receiver type unknown, no warning Dim f As T = New T() From {"Hello World!", f.Item(0)} ' Receiver type unknown, no warning End Sub Public Sub TypeParameterAsStructure(Of T As {Structure, IEnumerable, IMissingStuff})() ' no warnings from type parameters as well Dim g As New T From {"Hello World!", g.Item(0)} ' temp used, g is uninitialized, show warning Dim h As T = New T() From {"Hello World!", h.Item(0)} ' temp used, h is uninitialized, show warning Dim i, j As New T() From {i.Item(0), j.Item(0)} ' temps used, show warnings (although i is initialized when initializing j) End Sub Public Sub TypeParameterAsRefType(Of T As {List(Of String), new})() Dim k As New T From {"Hello World!", k.Item(0)} ' temp used, k is uninitialized, show warning Dim l As T = New T() From {"Hello World!", l.Item(0)} ' temp used, l is uninitialized, show warning End Sub Public Shared Sub Main() Dim a As New Custom From {"Hello World!", a.Item(0)} ' empty, non trackable structure, no warning Dim b As Custom = New Custom() From {"Hello World!", b.Item(0)} ' empty, non trackable structure, no warning Dim q As New CustomNonEmpty From {"Hello World!", q.Item(0)} ' temp used, q is uninitialized, show warning Dim r As CustomNonEmpty = New CustomNonEmpty() From {"Hello World!", r.Item(0)} ' temp used, r is uninitialized, show warning ' reference types are not ok, they are still Nothing Dim c As New List(Of String) From {"Hello World!", c.Item(0)} ' show warning Dim d As List(Of String) = New List(Of String)() From {"Hello World!", d.Item(0)} ' show warning ' was already assigned, no warning again. c = New List(Of String)() From {"Hello World!", c.Item(0)} ' no warning End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) AssertTheseDiagnostics(compilation, <expected> BC42109: Variable 'm' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim m As New U From {"Hello World!", m.Item(0)} ' temp used, m is uninitialized, show warning ~ BC42109: Variable 'n' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim n As U = New U() From {"Hello World!", n.Item(0)} ' temp used, h is uninitialized, show warning ~ BC42109: Variable 'o' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim o, p As New U() From {o.Item(0), p.Item(0)} ' temps used, show warnings (although o is initialized when initializing p) ~ BC42109: Variable 'p' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim o, p As New U() From {o.Item(0), p.Item(0)} ' temps used, show warnings (although o is initialized when initializing p) ~ BC42109: Variable 'g' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim g As New T From {"Hello World!", g.Item(0)} ' temp used, g is uninitialized, show warning ~ BC42109: Variable 'h' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim h As T = New T() From {"Hello World!", h.Item(0)} ' temp used, h is uninitialized, show warning ~ BC42109: Variable 'i' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim i, j As New T() From {i.Item(0), j.Item(0)} ' temps used, show warnings (although i is initialized when initializing j) ~ BC42109: Variable 'j' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim i, j As New T() From {i.Item(0), j.Item(0)} ' temps used, show warnings (although i is initialized when initializing j) ~ BC42104: Variable 'k' is used before it has been assigned a value. A null reference exception could result at runtime. Dim k As New T From {"Hello World!", k.Item(0)} ' temp used, k is uninitialized, show warning ~ BC42104: Variable 'l' is used before it has been assigned a value. A null reference exception could result at runtime. Dim l As T = New T() From {"Hello World!", l.Item(0)} ' temp used, l is uninitialized, show warning ~ BC42109: Variable 'q' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim q As New CustomNonEmpty From {"Hello World!", q.Item(0)} ' temp used, q is uninitialized, show warning ~ BC42109: Variable 'r' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use Dim r As CustomNonEmpty = New CustomNonEmpty() From {"Hello World!", r.Item(0)} ' temp used, r is uninitialized, show warning ~ BC42104: Variable 'c' is used before it has been assigned a value. A null reference exception could result at runtime. Dim c As New List(Of String) From {"Hello World!", c.Item(0)} ' show warning ~ BC42104: Variable 'd' is used before it has been assigned a value. A null reference exception could result at runtime. Dim d As List(Of String) = New List(Of String)() From {"Hello World!", d.Item(0)} ' show warning ~ </expected>) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerReferencingItself_2() Dim source = <![CDATA[ Imports System Imports System.Collections.Generic Module Program Sub Main(args As String()) Dim x, y As New List(Of String)() From {"1", x.Item(0)}'BIND:"New List(Of String)() From {"1", x.Item(0)}" Dim z As New List(Of String)() From {"1", z.Item(0)} End Sub End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub System.Collections.Generic.List(Of System.String)..ctor()) (OperationKind.ObjectCreation, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'New List(Of ... x.Item(0)}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'From {"1", x.Item(0)}') Initializers(2): IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"1"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... x.Item(0)}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"1"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "1") (Syntax: '"1"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IInvocationOperation ( Sub System.Collections.Generic.List(Of System.String).Add(item As System.String)) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x.Item(0)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: System.Collections.Generic.List(Of System.String), IsImplicit) (Syntax: 'New List(Of ... x.Item(0)}') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.Item(0)') IPropertyReferenceOperation: Property System.Collections.Generic.List(Of System.String).Item(index As System.Int32) As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'x.Item(0)') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'x') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: index) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) 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) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime. Dim x, y As New List(Of String)() From {"1", x.Item(0)}'BIND:"New List(Of String)() From {"1", x.Item(0)}" ~ BC42104: Variable 'z' is used before it has been assigned a value. A null reference exception could result at runtime. Dim z As New List(Of String)() From {"1", z.Item(0)} ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub CollectionInitializerCustomCollectionOptionalParameter() Dim source = <compilation name="CollectionInitializerCustomCollection"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class Custom Private list As New List(Of String)() Public Function GetEnumerator() As CustomEnumerator Return New CustomEnumerator(list) End Function Public Sub add(p As String, optional p2 as String = " ") list.Add(p) list.Add(p2) End Sub Public Class CustomEnumerator Private list As list(Of String) Private index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If Me.index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim c as Custom = New Custom() From {"Hello", {"World", "!"}}'BIND:"New Custom() From {"Hello", {"World", "!"}}" Output(c) End Sub Public Shared Sub Output(c as custom) For Each value In c Console.Write(value) Next End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Hello World! ]]>) Dim expectedOperationTree = <![CDATA[ IObjectCreationOperation (Constructor: Sub Custom..ctor()) (OperationKind.ObjectCreation, Type: Custom) (Syntax: 'New Custom( ... rld", "!"}}') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: Custom) (Syntax: 'From {"Hell ... rld", "!"}}') Initializers(2): IInvocationOperation ( Sub Custom.add(p As System.String, [p2 As System.String = " "])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '"Hello"') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... rld", "!"}}') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello") (Syntax: '"Hello"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: p2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"Hello"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ", IsImplicit) (Syntax: '"Hello"') 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) IInvocationOperation ( Sub Custom.add(p As System.String, [p2 As System.String = " "])) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: '{"World", "!"}') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: Custom, IsImplicit) (Syntax: 'New Custom( ... rld", "!"}}') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"World"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "World") (Syntax: '"World"') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '"!"') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "!") (Syntax: '"!"') 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) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source.Value, expectedOperationTree, expectedDiagnostics) End Sub <Fact()> Public Sub CollectionInitializerCustomCollectionParamArray() Dim source = <compilation name="CollectionInitializerCustomCollection"> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class Custom Private list As New List(Of String)() Public Function GetEnumerator() As CustomEnumerator Return New CustomEnumerator(list) End Function Public Sub add(paramarray p() As String) list.AddRange(p) End Sub Public Class CustomEnumerator Private list As list(Of String) Private index As Integer = -1 Public Sub New(list As List(Of String)) Me.list = list End Sub Public Function MoveNext() As Boolean If Me.index &lt; Me.list.Count - 1 Then index = index + 1 Return True End If Return False End function Public ReadOnly Property Current As String Get Return Me.list(index) End Get End Property End Class End Class Class C1 Public Shared Sub Main() Dim c as Custom = New Custom() From {"Hello", {" ", "World"}, ({"!", "!", "!"})} Output(c) End Sub Public Shared Sub Output(c as custom) For Each value In c Console.Write(value) Next End Sub End Class </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ Hello World!!! ]]>) End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_01() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic class X Inherits List(Of Integer) Sub Add(x As Integer) End Sub Sub Add(x As String) End Sub Shared Sub Main() Dim z = new X() From { String.Empty, 'BIND1:"String.Empty" 12} 'BIND2:"12" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo If True Then Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Sub X.Add(x As System.String)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End If If True Then Dim node2 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 2) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node2) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Sub X.Add(x As System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End If End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_02() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic class X Inherits List(Of Integer) Sub Add(x As X) End Sub Sub Add(x As List(Of Byte)) End Sub Shared Sub Main() Dim z = new X() From { String.Empty } 'BIND1:"String.Empty" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) Assert.Equal(2, symbolInfo.CandidateSymbols.Length) Assert.Equal({"Sub X.Add(x As System.Collections.Generic.List(Of System.Byte))", "Sub X.Add(x As X)"}, symbolInfo.CandidateSymbols.Select(Function(s) s.ToTestDisplayString()).Order().ToArray()) End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_03() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Class Base Implements IEnumerable(Of Integer) End Class class X Inherits Base Protected Sub Add(x As String) End Sub End Class class Y Shared Sub Main() Dim z = new X() From { String.Empty } 'BIND1:"String.Empty" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_04() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic class X Inherits List(Of Integer) Sub Add(x As String, y As Integer) End Sub Shared Sub Main() Dim z = new X() From { {String.Empty, 12} } 'BIND1:"{String.Empty, 12}" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 1) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Sub X.Add(x As System.String, y As System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact(), WorkItem(529787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529787")> Public Sub GetCollectionInitializerSymbolInfo_05() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic class X Inherits List(Of Integer) Sub Add(x As String, y As Integer) End Sub Shared Sub Main() Dim z = new X() From { {String.Empty, 'BIND1:"String.Empty" 12} } 'BIND2:"12" End Sub End Class ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary = Nothing Dim semanticModel = compilation.GetSemanticModel(tree) Dim symbolInfo As SymbolInfo For i As Integer = 1 To 2 Dim node1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", i) symbolInfo = semanticModel.GetCollectionInitializerSymbolInfo(node1) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Next End Sub <Fact()> <WorkItem(12983, "https://github.com/dotnet/roslyn/issues/12983")> Public Sub GetCollectionInitializerSymbolInfo_06() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections.Generic Class C1 Public Shared Sub Main() Dim list1 = new List(Of String) Dim list2 = new List(Of String)() Dim list3 = new List(Of String) With { .Count = 3 } Dim list4 = new List(Of String)() With { .Count = 3 } Dim list5 = new List(Of String) From { 1, 2, 3 } Dim list6 = new List(Of String)() From { 1, 2, 3 } End Sub End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees.Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = tree.GetRoot().DescendantNodes().OfType(Of GenericNameSyntax)().ToArray() Assert.Equal(6, nodes.Length) For Each name In nodes Assert.Equal("List(Of String)", name.ToString()) Assert.Equal("System.Collections.Generic.List(Of System.String)", semanticModel.GetSymbolInfo(name).Symbol.ToTestDisplayString()) Assert.Null(semanticModel.GetTypeInfo(name).Type) Next End Sub <Fact()> <WorkItem(27034, "https://github.com/dotnet/roslyn/issues/27034")> Public Sub LateBoundCollectionInitializer() Dim source = <compilation> <file name="a.vb"> Imports System Imports System.Collections Imports System.Collections.Generic Module Mod1 Sub Main(args() As String) Dim c As New C() c.M(1) End Sub Class C Implements IEnumerable(Of Integer) Public Sub M(a As Object) Dim c = New C From {a} End Sub Public Function GetEnumerator() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator Throw New NotImplementedException() End Function Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Public Sub Add(i As Integer) Console.WriteLine("Called Integer Add") End Sub Public Sub Add(l As Long) Console.WriteLine("Called Long Add") End Sub End Class End Module </file> </compilation> Dim verifier = CompileAndVerify(source, expectedOutput:="Called Integer Add") verifier.VerifyIL("Mod1.C.M", <![CDATA[ { // Code size 62 (0x3e) .maxstack 10 .locals init (Mod1.C V_0, Object() V_1, Boolean() V_2) IL_0000: newobj "Sub Mod1.C..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldnull IL_0008: ldstr "Add" IL_000d: ldc.i4.1 IL_000e: newarr "Object" IL_0013: dup IL_0014: ldc.i4.0 IL_0015: ldarg.1 IL_0016: stelem.ref IL_0017: dup IL_0018: stloc.1 IL_0019: ldnull IL_001a: ldnull IL_001b: ldc.i4.1 IL_001c: newarr "Boolean" IL_0021: dup IL_0022: ldc.i4.0 IL_0023: ldc.i4.1 IL_0024: stelem.i1 IL_0025: dup IL_0026: stloc.2 IL_0027: ldc.i4.1 IL_0028: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object" IL_002d: pop IL_002e: ldloc.2 IL_002f: ldc.i4.0 IL_0030: ldelem.u1 IL_0031: brfalse.s IL_003d IL_0033: ldloc.1 IL_0034: ldc.i4.0 IL_0035: ldelem.ref IL_0036: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_003b: starg.s V_1 IL_003d: ret } ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Tools/IdeBenchmarks/SQLitePersistentStorageBenchmark.cs
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SQLite.v2; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Test.Utilities; namespace IdeBenchmarks { public class SQLitePersistentStorageBenchmarks { private readonly UseExportProviderAttribute _useExportProviderAttribute = new UseExportProviderAttribute(); // Run the test with different ratios of reads/writes. [Params(0, 25, 50, 75, 100)] public int ReadPercentage { get; set; } private TestWorkspace _workspace; private SQLitePersistentStorageService _storageService; private IChecksummedPersistentStorage _storage; private Document _document; private Random _random; public SQLitePersistentStorageBenchmarks() { _document = null!; _storage = null!; _storageService = null!; _workspace = null!; _random = null!; } [GlobalSetup] public void GlobalSetup() { _useExportProviderAttribute.Before(null); if (_workspace != null) { throw new InvalidOperationException(); } _workspace = TestWorkspace.Create( @"<Workspace> <Project Language=""NoCompilation"" CommonReferences=""false""> <Document> // a no-compilation document </Document> </Project> </Workspace>"); // Explicitly choose the sqlite db to test. _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite) .WithChangedOption(StorageOptions.DatabaseMustSucceed, true))); var connectionPoolService = _workspace.ExportProvider.GetExportedValue<SQLiteConnectionPoolService>(); _storageService = new SQLitePersistentStorageService( _workspace.Options, connectionPoolService, new LocationService(), _workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>().GetListener(FeatureAttribute.PersistentStorage)); var solution = _workspace.CurrentSolution; _storage = _storageService.GetStorageWorkerAsync(_workspace, SolutionKey.ToSolutionKey(solution), solution, CancellationToken.None).AsTask().GetAwaiter().GetResult(); Console.WriteLine("Storage type: " + _storage.GetType()); _document = _workspace.CurrentSolution.Projects.Single().Documents.Single(); _random = new Random(0); } [GlobalCleanup] public void GlobalCleanup() { if (_workspace == null) { throw new InvalidOperationException(); } _document = null!; _storage.Dispose(); _storage = null!; _storageService = null!; _workspace.Dispose(); _workspace = null!; _useExportProviderAttribute.After(null); } private static readonly byte[] s_bytes = new byte[1000]; [Benchmark(Baseline = true)] public Task PerfAsync() { const int capacity = 1000; var tasks = new List<Task>(capacity); // Create a lot of overlapping reads and writes to the DB to several different keys. The // percentage of reads and writes is parameterized above, allowing us to validate // performance with several different usage patterns. for (var i = 0; i < capacity; i++) { var name = _random.Next(0, 4).ToString(); if (_random.Next(0, 100) < ReadPercentage) { tasks.Add(Task.Run(async () => { using var stream = await _storage.ReadStreamAsync(_document, name); })); } else { tasks.Add(Task.Run(async () => { using var stream = new MemoryStream(s_bytes); await _storage.WriteStreamAsync(_document, name, stream); })); } } return Task.WhenAll(tasks); } private class LocationService : IPersistentStorageLocationService { public bool IsSupported(Workspace workspace) => true; public string TryGetStorageLocation(Solution _) { // Store the db in a different random temp dir. var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Console.WriteLine("Creating: " + tempDir); Directory.CreateDirectory(tempDir); return tempDir; } } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SQLite.v2; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Test.Utilities; namespace IdeBenchmarks { public class SQLitePersistentStorageBenchmarks { private readonly UseExportProviderAttribute _useExportProviderAttribute = new UseExportProviderAttribute(); // Run the test with different ratios of reads/writes. [Params(0, 25, 50, 75, 100)] public int ReadPercentage { get; set; } private TestWorkspace _workspace; private SQLitePersistentStorageService _storageService; private IChecksummedPersistentStorage _storage; private Document _document; private Random _random; public SQLitePersistentStorageBenchmarks() { _document = null!; _storage = null!; _storageService = null!; _workspace = null!; _random = null!; } [GlobalSetup] public void GlobalSetup() { _useExportProviderAttribute.Before(null); if (_workspace != null) { throw new InvalidOperationException(); } _workspace = TestWorkspace.Create( @"<Workspace> <Project Language=""NoCompilation"" CommonReferences=""false""> <Document> // a no-compilation document </Document> </Project> </Workspace>"); // Explicitly choose the sqlite db to test. _workspace.TryApplyChanges(_workspace.CurrentSolution.WithOptions(_workspace.Options .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite) .WithChangedOption(StorageOptions.DatabaseMustSucceed, true))); var connectionPoolService = _workspace.ExportProvider.GetExportedValue<SQLiteConnectionPoolService>(); _storageService = new SQLitePersistentStorageService( _workspace.Options, connectionPoolService, new LocationService(), _workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>().GetListener(FeatureAttribute.PersistentStorage)); var solution = _workspace.CurrentSolution; _storage = _storageService.GetStorageWorkerAsync(_workspace, SolutionKey.ToSolutionKey(solution), solution, CancellationToken.None).AsTask().GetAwaiter().GetResult(); Console.WriteLine("Storage type: " + _storage.GetType()); _document = _workspace.CurrentSolution.Projects.Single().Documents.Single(); _random = new Random(0); } [GlobalCleanup] public void GlobalCleanup() { if (_workspace == null) { throw new InvalidOperationException(); } _document = null!; _storage.Dispose(); _storage = null!; _storageService = null!; _workspace.Dispose(); _workspace = null!; _useExportProviderAttribute.After(null); } private static readonly byte[] s_bytes = new byte[1000]; [Benchmark(Baseline = true)] public Task PerfAsync() { const int capacity = 1000; var tasks = new List<Task>(capacity); // Create a lot of overlapping reads and writes to the DB to several different keys. The // percentage of reads and writes is parameterized above, allowing us to validate // performance with several different usage patterns. for (var i = 0; i < capacity; i++) { var name = _random.Next(0, 4).ToString(); if (_random.Next(0, 100) < ReadPercentage) { tasks.Add(Task.Run(async () => { using var stream = await _storage.ReadStreamAsync(_document, name); })); } else { tasks.Add(Task.Run(async () => { using var stream = new MemoryStream(s_bytes); await _storage.WriteStreamAsync(_document, name, stream); })); } } return Task.WhenAll(tasks); } private class LocationService : IPersistentStorageLocationService { public bool IsSupported(Workspace workspace) => true; public string TryGetStorageLocation(Solution _) { // Store the db in a different random temp dir. var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Console.WriteLine("Creating: " + tempDir); Directory.CreateDirectory(tempDir); return tempDir; } } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/SuppressWrappingData.cs
// Licensed to the .NET Foundation under one or more 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.Text; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// data that will be used in an interval tree related to suppressing wrapping operations. /// </summary> internal class SuppressWrappingData { public SuppressWrappingData(TextSpan textSpan, bool ignoreElastic) { this.TextSpan = textSpan; this.IgnoreElastic = ignoreElastic; } public TextSpan TextSpan { get; } public bool IgnoreElastic { get; } #if DEBUG public override string ToString() => $"Suppress wrapping on '{TextSpan}' with IgnoreElastic={IgnoreElastic}"; #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// data that will be used in an interval tree related to suppressing wrapping operations. /// </summary> internal class SuppressWrappingData { public SuppressWrappingData(TextSpan textSpan, bool ignoreElastic) { this.TextSpan = textSpan; this.IgnoreElastic = ignoreElastic; } public TextSpan TextSpan { get; } public bool IgnoreElastic { get; } #if DEBUG public override string ToString() => $"Suppress wrapping on '{TextSpan}' with IgnoreElastic={IgnoreElastic}"; #endif } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/UsingAliasTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public class UsingAliasTests : SemanticModelTestBase { [Fact] public void GetSemanticInfo() { var text = @"using O = System.Object; partial class A : O {} partial class A : object {} partial class A : System.Object {} partial class A : Object {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var a1 = root.Members[0] as TypeDeclarationSyntax; var a2 = root.Members[1] as TypeDeclarationSyntax; var a3 = root.Members[2] as TypeDeclarationSyntax; var a4 = root.Members[3] as TypeDeclarationSyntax; var base1 = a1.BaseList.Types[0].Type as TypeSyntax; var base2 = a2.BaseList.Types[0].Type as TypeSyntax; var base3 = a3.BaseList.Types[0].Type as TypeSyntax; var base4 = a4.BaseList.Types[0].Type as TypeSyntax; var model = comp.GetSemanticModel(tree); var info1 = model.GetSemanticInfoSummary(base1); Assert.NotNull(info1.Symbol); var alias1 = model.GetAliasInfo((IdentifierNameSyntax)base1); Assert.NotNull(alias1); Assert.Equal(SymbolKind.Alias, alias1.Kind); Assert.Equal("O", alias1.ToDisplayString()); Assert.Equal("O=System.Object", alias1.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal(info1.Symbol, alias1.Target); var info2 = model.GetSemanticInfoSummary(base2); Assert.NotNull(info2.Symbol); var b2 = info2.Symbol; Assert.Equal("System.Object", b2.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info2.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info3 = model.GetSemanticInfoSummary(base3); Assert.NotNull(info3.Symbol); var b3 = info3.Symbol; Assert.Equal("System.Object", b3.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info3.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info4 = model.GetSemanticInfoSummary(base4); Assert.Null(info4.Symbol); // no "using System;" Assert.Equal(0, info4.CandidateSymbols.Length); var alias4 = model.GetAliasInfo((IdentifierNameSyntax)base4); Assert.Null(alias4); } [Fact] public void GetSymbolInfoInParent() { var text = @"using O = System.Object; partial class A : O {} partial class A : object {} partial class A : System.Object {} partial class A : Object {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var a1 = root.Members[0] as TypeDeclarationSyntax; var a2 = root.Members[1] as TypeDeclarationSyntax; var a3 = root.Members[2] as TypeDeclarationSyntax; var a4 = root.Members[3] as TypeDeclarationSyntax; var base1 = a1.BaseList.Types[0].Type as TypeSyntax; var base2 = a2.BaseList.Types[0].Type as TypeSyntax; var base3 = a3.BaseList.Types[0].Type as TypeSyntax; var base4 = a4.BaseList.Types[0].Type as TypeSyntax; var model = comp.GetSemanticModel(tree); var info1 = model.GetSemanticInfoSummary(base1); Assert.Equal("System.Object", info1.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var alias1 = model.GetAliasInfo((IdentifierNameSyntax)base1); Assert.NotNull(alias1); Assert.Equal(SymbolKind.Alias, alias1.Kind); Assert.Equal("O=System.Object", alias1.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info2 = model.GetSemanticInfoSummary(base2); Assert.NotNull(info2.Symbol); var b2 = info2.Symbol; Assert.Equal("System.Object", b2.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info2.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info3 = model.GetSemanticInfoSummary(base3); Assert.NotNull(info3.Symbol); var b3 = info3.Symbol; Assert.Equal("System.Object", b3.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info3.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info4 = model.GetSemanticInfoSummary(base4); Assert.Null(info4.Symbol); // no "using System;" Assert.Equal(0, info4.CandidateSymbols.Length); var alias4 = model.GetAliasInfo((IdentifierNameSyntax)base4); Assert.Null(alias4); } [Fact] public void BindType() { var text = @"using O = System.Object; partial class A : O {} partial class A : object {} partial class A : System.Object {} partial class A : Object {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var a1 = root.Members[0] as TypeDeclarationSyntax; var a2 = root.Members[1] as TypeDeclarationSyntax; var a3 = root.Members[2] as TypeDeclarationSyntax; var a4 = root.Members[3] as TypeDeclarationSyntax; var base1 = a1.BaseList.Types[0].Type as TypeSyntax; var base2 = a2.BaseList.Types[0].Type as TypeSyntax; var base3 = a3.BaseList.Types[0].Type as TypeSyntax; var base4 = a4.BaseList.Types[0].Type as TypeSyntax; var model = comp.GetSemanticModel(tree); var symbolInfo = model.GetSpeculativeSymbolInfo(base2.SpanStart, base2, SpeculativeBindingOption.BindAsTypeOrNamespace); var info2 = symbolInfo.Symbol as ITypeSymbol; Assert.NotNull(info2); Assert.Equal("System.Object", info2.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info2.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); symbolInfo = model.GetSpeculativeSymbolInfo(base3.SpanStart, base3, SpeculativeBindingOption.BindAsTypeOrNamespace); var info3 = symbolInfo.Symbol as ITypeSymbol; Assert.NotNull(info3); Assert.Equal("System.Object", info3.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info3.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); symbolInfo = model.GetSpeculativeSymbolInfo(base4.SpanStart, base4, SpeculativeBindingOption.BindAsTypeOrNamespace); var info4 = symbolInfo.Symbol as ITypeSymbol; Assert.Null(info4); // no "using System;" } [Fact] public void GetDeclaredSymbol01() { var text = @"using O = System.Object; "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var model = comp.GetSemanticModel(tree); var alias = model.GetDeclaredSymbol(usingAlias); Assert.Equal("O", alias.ToDisplayString()); Assert.Equal("O=System.Object", alias.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var global = (INamespaceSymbol)alias.ContainingSymbol; Assert.Equal(NamespaceKind.Module, global.NamespaceKind); } [Fact] public void GetDeclaredSymbol02() { var text = "using System;"; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var model = comp.GetSemanticModel(tree); var alias = model.GetDeclaredSymbol(usingAlias); Assert.Null(alias); } [Fact] public void LookupNames() { var text = @"using O = System.Object; class C {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var model = comp.GetSemanticModel(tree); var names = model.LookupNames(root.Members[0].SpanStart); Assert.Contains("O", names); } [Fact] public void LookupSymbols() { var text = @"using O = System.Object; class C {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var model = comp.GetSemanticModel(tree); var symbols = model.LookupSymbols(root.Members[0].SpanStart, name: "O"); Assert.Equal(1, symbols.Length); Assert.Equal(SymbolKind.Alias, symbols[0].Kind); Assert.Equal("O=System.Object", symbols[0].ToDisplayString(format: SymbolDisplayFormat.TestFormat)); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void EventEscapedIdentifier() { var text = @" using @for = @foreach; namespace @foreach { } "; SyntaxTree syntaxTree = Parse(text); CSharpCompilation comp = CreateCompilation(syntaxTree); UsingDirectiveSyntax usingAlias = (syntaxTree.GetCompilationUnitRoot() as CompilationUnitSyntax).Usings.First(); var alias = comp.GetSemanticModel(syntaxTree).GetDeclaredSymbol(usingAlias); Assert.Equal("for", alias.Name); Assert.Equal("@for", alias.ToString()); } [WorkItem(541937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541937")] [Fact] public void LocalDeclaration() { var text = @" using GIBBERISH = System.Int32; class Program { static void Main() { /*<bind>*/GIBBERISH/*</bind>*/ x; } }"; SyntaxTree syntaxTree = Parse(text); CSharpCompilation comp = CreateCompilation(syntaxTree); var model = comp.GetSemanticModel(syntaxTree); IdentifierNameSyntax exprSyntaxToBind = (IdentifierNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(syntaxTree)); Assert.Equal(SymbolKind.Alias, model.GetAliasInfo(exprSyntaxToBind).Kind); } [WorkItem(576809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576809")] [Fact] public void AsClause() { var text = @" using N = System.Nullable<int>; class Program { static void Main() { object x = 1; var y = x as /*<bind>*/N/*</bind>*/ + 1; } } "; SyntaxTree syntaxTree = Parse(text); CSharpCompilation comp = CreateCompilation(syntaxTree); var model = comp.GetSemanticModel(syntaxTree); IdentifierNameSyntax exprSyntaxToBind = (IdentifierNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(syntaxTree)); Assert.Equal("System.Int32?", model.GetAliasInfo(exprSyntaxToBind).Target.ToTestDisplayString()); } [WorkItem(542552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542552")] [Fact] public void IncompleteDuplicateAlias() { var text = @"namespace namespace1 { } namespace namespace2 { } namespace prog { using ns = namespace1; using ns ="; SyntaxTree syntaxTree = Parse(text); CSharpCompilation comp = CreateCompilation(syntaxTree); var discarded = comp.GetDiagnostics(); } [ClrOnlyFact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")] public void AliasWithAnError() { var text = @" namespace NS { using Short = LongNamespace; class Test { public object Method1() { return (new Short.MyClass()).Prop; } } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'LongNamespace' could not be found (are you missing a using directive or an assembly reference?) // using Short = LongNamespace; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "LongNamespace").WithArguments("LongNamespace").WithLocation(4, 19) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Short").Skip(1).Single(); Assert.Equal("Short.MyClass", node.Parent.ToString()); var model = compilation.GetSemanticModel(tree); var alias = model.GetAliasInfo(node); Assert.Equal("Short=LongNamespace", alias.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, alias.Target.Kind); Assert.Equal("LongNamespace", alias.Target.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(node); Assert.Null(symbolInfo.Symbol); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } [ClrOnlyFact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")] public void AliasWithAnErrorFileScopedNamespace() { var text = @" namespace NS; using Short = LongNamespace; class Test { public object Method1() { return (new Short.MyClass()).Prop; } } "; var compilation = CreateCompilation(text, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); compilation.VerifyDiagnostics( // (3,15): error CS0246: The type or namespace name 'LongNamespace' could not be found (are you missing a using directive or an assembly reference?) // using Short = LongNamespace; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "LongNamespace").WithArguments("LongNamespace").WithLocation(3, 15)); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Short").Skip(1).Single(); Assert.Equal("Short.MyClass", node.Parent.ToString()); var model = compilation.GetSemanticModel(tree); var alias = model.GetAliasInfo(node); Assert.Equal("Short=LongNamespace", alias.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, alias.Target.Kind); Assert.Equal("LongNamespace", alias.Target.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(node); Assert.Null(symbolInfo.Symbol); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public class UsingAliasTests : SemanticModelTestBase { [Fact] public void GetSemanticInfo() { var text = @"using O = System.Object; partial class A : O {} partial class A : object {} partial class A : System.Object {} partial class A : Object {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var a1 = root.Members[0] as TypeDeclarationSyntax; var a2 = root.Members[1] as TypeDeclarationSyntax; var a3 = root.Members[2] as TypeDeclarationSyntax; var a4 = root.Members[3] as TypeDeclarationSyntax; var base1 = a1.BaseList.Types[0].Type as TypeSyntax; var base2 = a2.BaseList.Types[0].Type as TypeSyntax; var base3 = a3.BaseList.Types[0].Type as TypeSyntax; var base4 = a4.BaseList.Types[0].Type as TypeSyntax; var model = comp.GetSemanticModel(tree); var info1 = model.GetSemanticInfoSummary(base1); Assert.NotNull(info1.Symbol); var alias1 = model.GetAliasInfo((IdentifierNameSyntax)base1); Assert.NotNull(alias1); Assert.Equal(SymbolKind.Alias, alias1.Kind); Assert.Equal("O", alias1.ToDisplayString()); Assert.Equal("O=System.Object", alias1.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal(info1.Symbol, alias1.Target); var info2 = model.GetSemanticInfoSummary(base2); Assert.NotNull(info2.Symbol); var b2 = info2.Symbol; Assert.Equal("System.Object", b2.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info2.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info3 = model.GetSemanticInfoSummary(base3); Assert.NotNull(info3.Symbol); var b3 = info3.Symbol; Assert.Equal("System.Object", b3.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info3.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info4 = model.GetSemanticInfoSummary(base4); Assert.Null(info4.Symbol); // no "using System;" Assert.Equal(0, info4.CandidateSymbols.Length); var alias4 = model.GetAliasInfo((IdentifierNameSyntax)base4); Assert.Null(alias4); } [Fact] public void GetSymbolInfoInParent() { var text = @"using O = System.Object; partial class A : O {} partial class A : object {} partial class A : System.Object {} partial class A : Object {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var a1 = root.Members[0] as TypeDeclarationSyntax; var a2 = root.Members[1] as TypeDeclarationSyntax; var a3 = root.Members[2] as TypeDeclarationSyntax; var a4 = root.Members[3] as TypeDeclarationSyntax; var base1 = a1.BaseList.Types[0].Type as TypeSyntax; var base2 = a2.BaseList.Types[0].Type as TypeSyntax; var base3 = a3.BaseList.Types[0].Type as TypeSyntax; var base4 = a4.BaseList.Types[0].Type as TypeSyntax; var model = comp.GetSemanticModel(tree); var info1 = model.GetSemanticInfoSummary(base1); Assert.Equal("System.Object", info1.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var alias1 = model.GetAliasInfo((IdentifierNameSyntax)base1); Assert.NotNull(alias1); Assert.Equal(SymbolKind.Alias, alias1.Kind); Assert.Equal("O=System.Object", alias1.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info2 = model.GetSemanticInfoSummary(base2); Assert.NotNull(info2.Symbol); var b2 = info2.Symbol; Assert.Equal("System.Object", b2.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info2.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info3 = model.GetSemanticInfoSummary(base3); Assert.NotNull(info3.Symbol); var b3 = info3.Symbol; Assert.Equal("System.Object", b3.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info3.Type.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var info4 = model.GetSemanticInfoSummary(base4); Assert.Null(info4.Symbol); // no "using System;" Assert.Equal(0, info4.CandidateSymbols.Length); var alias4 = model.GetAliasInfo((IdentifierNameSyntax)base4); Assert.Null(alias4); } [Fact] public void BindType() { var text = @"using O = System.Object; partial class A : O {} partial class A : object {} partial class A : System.Object {} partial class A : Object {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var a1 = root.Members[0] as TypeDeclarationSyntax; var a2 = root.Members[1] as TypeDeclarationSyntax; var a3 = root.Members[2] as TypeDeclarationSyntax; var a4 = root.Members[3] as TypeDeclarationSyntax; var base1 = a1.BaseList.Types[0].Type as TypeSyntax; var base2 = a2.BaseList.Types[0].Type as TypeSyntax; var base3 = a3.BaseList.Types[0].Type as TypeSyntax; var base4 = a4.BaseList.Types[0].Type as TypeSyntax; var model = comp.GetSemanticModel(tree); var symbolInfo = model.GetSpeculativeSymbolInfo(base2.SpanStart, base2, SpeculativeBindingOption.BindAsTypeOrNamespace); var info2 = symbolInfo.Symbol as ITypeSymbol; Assert.NotNull(info2); Assert.Equal("System.Object", info2.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info2.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); symbolInfo = model.GetSpeculativeSymbolInfo(base3.SpanStart, base3, SpeculativeBindingOption.BindAsTypeOrNamespace); var info3 = symbolInfo.Symbol as ITypeSymbol; Assert.NotNull(info3); Assert.Equal("System.Object", info3.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); Assert.Equal("System.Object", info3.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); symbolInfo = model.GetSpeculativeSymbolInfo(base4.SpanStart, base4, SpeculativeBindingOption.BindAsTypeOrNamespace); var info4 = symbolInfo.Symbol as ITypeSymbol; Assert.Null(info4); // no "using System;" } [Fact] public void GetDeclaredSymbol01() { var text = @"using O = System.Object; "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var model = comp.GetSemanticModel(tree); var alias = model.GetDeclaredSymbol(usingAlias); Assert.Equal("O", alias.ToDisplayString()); Assert.Equal("O=System.Object", alias.ToDisplayString(format: SymbolDisplayFormat.TestFormat)); var global = (INamespaceSymbol)alias.ContainingSymbol; Assert.Equal(NamespaceKind.Module, global.NamespaceKind); } [Fact] public void GetDeclaredSymbol02() { var text = "using System;"; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var model = comp.GetSemanticModel(tree); var alias = model.GetDeclaredSymbol(usingAlias); Assert.Null(alias); } [Fact] public void LookupNames() { var text = @"using O = System.Object; class C {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var model = comp.GetSemanticModel(tree); var names = model.LookupNames(root.Members[0].SpanStart); Assert.Contains("O", names); } [Fact] public void LookupSymbols() { var text = @"using O = System.Object; class C {} "; var tree = Parse(text); var root = tree.GetCompilationUnitRoot() as CompilationUnitSyntax; var comp = CreateCompilation(tree); var usingAlias = root.Usings[0]; var model = comp.GetSemanticModel(tree); var symbols = model.LookupSymbols(root.Members[0].SpanStart, name: "O"); Assert.Equal(1, symbols.Length); Assert.Equal(SymbolKind.Alias, symbols[0].Kind); Assert.Equal("O=System.Object", symbols[0].ToDisplayString(format: SymbolDisplayFormat.TestFormat)); } [WorkItem(537401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537401")] [Fact] public void EventEscapedIdentifier() { var text = @" using @for = @foreach; namespace @foreach { } "; SyntaxTree syntaxTree = Parse(text); CSharpCompilation comp = CreateCompilation(syntaxTree); UsingDirectiveSyntax usingAlias = (syntaxTree.GetCompilationUnitRoot() as CompilationUnitSyntax).Usings.First(); var alias = comp.GetSemanticModel(syntaxTree).GetDeclaredSymbol(usingAlias); Assert.Equal("for", alias.Name); Assert.Equal("@for", alias.ToString()); } [WorkItem(541937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541937")] [Fact] public void LocalDeclaration() { var text = @" using GIBBERISH = System.Int32; class Program { static void Main() { /*<bind>*/GIBBERISH/*</bind>*/ x; } }"; SyntaxTree syntaxTree = Parse(text); CSharpCompilation comp = CreateCompilation(syntaxTree); var model = comp.GetSemanticModel(syntaxTree); IdentifierNameSyntax exprSyntaxToBind = (IdentifierNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(syntaxTree)); Assert.Equal(SymbolKind.Alias, model.GetAliasInfo(exprSyntaxToBind).Kind); } [WorkItem(576809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576809")] [Fact] public void AsClause() { var text = @" using N = System.Nullable<int>; class Program { static void Main() { object x = 1; var y = x as /*<bind>*/N/*</bind>*/ + 1; } } "; SyntaxTree syntaxTree = Parse(text); CSharpCompilation comp = CreateCompilation(syntaxTree); var model = comp.GetSemanticModel(syntaxTree); IdentifierNameSyntax exprSyntaxToBind = (IdentifierNameSyntax)GetExprSyntaxForBinding(GetExprSyntaxList(syntaxTree)); Assert.Equal("System.Int32?", model.GetAliasInfo(exprSyntaxToBind).Target.ToTestDisplayString()); } [WorkItem(542552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542552")] [Fact] public void IncompleteDuplicateAlias() { var text = @"namespace namespace1 { } namespace namespace2 { } namespace prog { using ns = namespace1; using ns ="; SyntaxTree syntaxTree = Parse(text); CSharpCompilation comp = CreateCompilation(syntaxTree); var discarded = comp.GetDiagnostics(); } [ClrOnlyFact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")] public void AliasWithAnError() { var text = @" namespace NS { using Short = LongNamespace; class Test { public object Method1() { return (new Short.MyClass()).Prop; } } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (4,19): error CS0246: The type or namespace name 'LongNamespace' could not be found (are you missing a using directive or an assembly reference?) // using Short = LongNamespace; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "LongNamespace").WithArguments("LongNamespace").WithLocation(4, 19) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Short").Skip(1).Single(); Assert.Equal("Short.MyClass", node.Parent.ToString()); var model = compilation.GetSemanticModel(tree); var alias = model.GetAliasInfo(node); Assert.Equal("Short=LongNamespace", alias.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, alias.Target.Kind); Assert.Equal("LongNamespace", alias.Target.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(node); Assert.Null(symbolInfo.Symbol); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } [ClrOnlyFact, WorkItem(2805, "https://github.com/dotnet/roslyn/issues/2805")] public void AliasWithAnErrorFileScopedNamespace() { var text = @" namespace NS; using Short = LongNamespace; class Test { public object Method1() { return (new Short.MyClass()).Prop; } } "; var compilation = CreateCompilation(text, parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); compilation.VerifyDiagnostics( // (3,15): error CS0246: The type or namespace name 'LongNamespace' could not be found (are you missing a using directive or an assembly reference?) // using Short = LongNamespace; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "LongNamespace").WithArguments("LongNamespace").WithLocation(3, 15)); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Short").Skip(1).Single(); Assert.Equal("Short.MyClass", node.Parent.ToString()); var model = compilation.GetSemanticModel(tree); var alias = model.GetAliasInfo(node); Assert.Equal("Short=LongNamespace", alias.ToTestDisplayString()); Assert.Equal(SymbolKind.ErrorType, alias.Target.Kind); Assert.Equal("LongNamespace", alias.Target.ToTestDisplayString()); var symbolInfo = model.GetSymbolInfo(node); Assert.Null(symbolInfo.Symbol); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests_Razor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests_Razor : AbstractAddUsingTests { [Theory, CombinatorialData] public async Task TestAddIntoHiddenRegionWithModernSpanMapper(TestHost host) { await TestAsync( @"#line hidden using System.Collections.Generic; #line default class Program { void Main() { [|DateTime|] d; } }", @"#line hidden using System; using System.Collections.Generic; #line default class Program { void Main() { DateTime d; } }", host); } private protected override IDocumentServiceProvider GetDocumentServiceProvider() { return new TestDocumentServiceProvider(supportsMappingImportDirectives: 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.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { [Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public partial class AddUsingTests_Razor : AbstractAddUsingTests { [Theory, CombinatorialData] public async Task TestAddIntoHiddenRegionWithModernSpanMapper(TestHost host) { await TestAsync( @"#line hidden using System.Collections.Generic; #line default class Program { void Main() { [|DateTime|] d; } }", @"#line hidden using System; using System.Collections.Generic; #line default class Program { void Main() { DateTime d; } }", host); } private protected override IDocumentServiceProvider GetDocumentServiceProvider() { return new TestDocumentServiceProvider(supportsMappingImportDirectives: true); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamespaceSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class NamespaceSymbolReferenceFinder : AbstractReferenceFinder<INamespaceSymbol> { private static readonly SymbolDisplayFormat s_globalNamespaceFormat = new(SymbolDisplayGlobalNamespaceStyle.Included); protected override bool CanFind(INamespaceSymbol symbol) => true; protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( INamespaceSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, GetNamespaceIdentifierName(symbol)).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithGlobalAttributes.Concat(documentsWithName); } private static string GetNamespaceIdentifierName(INamespaceSymbol symbol) { return symbol.IsGlobalNamespace ? symbol.ToDisplayString(s_globalNamespaceFormat) : symbol.Name; } protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( INamespaceSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var identifierName = GetNamespaceIdentifierName(symbol); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var tokens = await GetIdentifierOrGlobalNamespaceTokensWithTextAsync( document, semanticModel, identifierName, cancellationToken).ConfigureAwait(false); var nonAliasReferences = await FindReferencesInTokensAsync( symbol, document, semanticModel, tokens, t => syntaxFacts.TextMatch(t.ValueText, identifierName), cancellationToken).ConfigureAwait(false); var aliasReferences = await FindAliasReferencesAsync(nonAliasReferences, symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false); return nonAliasReferences.Concat(aliasReferences, suppressionReferences); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class NamespaceSymbolReferenceFinder : AbstractReferenceFinder<INamespaceSymbol> { private static readonly SymbolDisplayFormat s_globalNamespaceFormat = new(SymbolDisplayGlobalNamespaceStyle.Included); protected override bool CanFind(INamespaceSymbol symbol) => true; protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( INamespaceSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, GetNamespaceIdentifierName(symbol)).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithGlobalAttributes.Concat(documentsWithName); } private static string GetNamespaceIdentifierName(INamespaceSymbol symbol) { return symbol.IsGlobalNamespace ? symbol.ToDisplayString(s_globalNamespaceFormat) : symbol.Name; } protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( INamespaceSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var identifierName = GetNamespaceIdentifierName(symbol); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var tokens = await GetIdentifierOrGlobalNamespaceTokensWithTextAsync( document, semanticModel, identifierName, cancellationToken).ConfigureAwait(false); var nonAliasReferences = await FindReferencesInTokensAsync( symbol, document, semanticModel, tokens, t => syntaxFacts.TextMatch(t.ValueText, identifierName), cancellationToken).ConfigureAwait(false); var aliasReferences = await FindAliasReferencesAsync(nonAliasReferences, symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false); return nonAliasReferences.Concat(aliasReferences, suppressionReferences); } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/Features/Core/Portable/SolutionCrawler/SolutionCrawlerProgressReporter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { /// <summary> /// Progress reporter /// /// this progress reporter is a best effort implementation. it doesn't stop world to find out accurate data /// /// what this reporter care is we show start/stop background work and show things are moving or paused /// without too much cost. /// /// due to how solution cralwer calls Start/Stop (see caller of those 2), those 2 can't have a race /// and that is all we care for this reporter /// </summary> internal sealed class SolutionCrawlerProgressReporter : ISolutionCrawlerProgressReporter { // we use ref count here since solution crawler has multiple queues per priority // where an item can be enqueued and dequeued independently. // first item added in any of those queues will cause the "start" event to be sent // and the very last item processed from those queues will cause "stop" event to be sent // evaluating and paused is also ref counted since work in the lower priority queue can // be canceled due to new higher priority work item enqueued to higher queue. // but before lower priority work actually exit due to cancellation, higher work could // start processing. causing an overlap. the ref count make sure that exiting lower // work doesn't flip evaluating state to paused state. private int _progressStartCount = 0; private int _progressEvaluateCount = 0; public event EventHandler<ProgressData>? ProgressChanged; public bool InProgress => _progressStartCount > 0; public void Start() => ChangeProgressStatus(ref _progressStartCount, ProgressStatus.Started); public void Stop() => ChangeProgressStatus(ref _progressStartCount, ProgressStatus.Stopped); private void Evaluate() => ChangeProgressStatus(ref _progressEvaluateCount, ProgressStatus.Evaluating); private void Pause() => ChangeProgressStatus(ref _progressEvaluateCount, ProgressStatus.Paused); public void UpdatePendingItemCount(int pendingItemCount) { if (_progressStartCount > 0) { var progressData = new ProgressData(ProgressStatus.PendingItemCountUpdated, pendingItemCount); OnProgressChanged(progressData); } } /// <summary> /// Allows the solution crawler to start evaluating work enqueued to it. /// Returns an IDisposable that the caller must dispose of to indicate that it no longer needs the crawler to continue evaluating. /// Multiple callers can call into this simultaneously. /// Only when the last one actually disposes the scope-object will the crawler /// actually revert back to the paused state where no work proceeds. /// </summary> public IDisposable GetEvaluatingScope() => new ProgressStatusRAII(this); private void ChangeProgressStatus(ref int referenceCount, ProgressStatus status) { var start = status is ProgressStatus.Started or ProgressStatus.Evaluating; if (start ? (Interlocked.Increment(ref referenceCount) == 1) : (Interlocked.Decrement(ref referenceCount) == 0)) { var progressData = new ProgressData(status, pendingItemCount: null); OnProgressChanged(progressData); } } private void OnProgressChanged(ProgressData progressData) => ProgressChanged?.Invoke(this, progressData); private struct ProgressStatusRAII : IDisposable { private readonly SolutionCrawlerProgressReporter _owner; public ProgressStatusRAII(SolutionCrawlerProgressReporter owner) { _owner = owner; _owner.Evaluate(); } public void Dispose() => _owner.Pause(); } } /// <summary> /// reporter that doesn't do anything /// </summary> private class NullReporter : ISolutionCrawlerProgressReporter { public static readonly NullReporter Instance = new(); public bool InProgress => false; public event EventHandler<ProgressData> ProgressChanged { add { } remove { } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { /// <summary> /// Progress reporter /// /// this progress reporter is a best effort implementation. it doesn't stop world to find out accurate data /// /// what this reporter care is we show start/stop background work and show things are moving or paused /// without too much cost. /// /// due to how solution cralwer calls Start/Stop (see caller of those 2), those 2 can't have a race /// and that is all we care for this reporter /// </summary> internal sealed class SolutionCrawlerProgressReporter : ISolutionCrawlerProgressReporter { // we use ref count here since solution crawler has multiple queues per priority // where an item can be enqueued and dequeued independently. // first item added in any of those queues will cause the "start" event to be sent // and the very last item processed from those queues will cause "stop" event to be sent // evaluating and paused is also ref counted since work in the lower priority queue can // be canceled due to new higher priority work item enqueued to higher queue. // but before lower priority work actually exit due to cancellation, higher work could // start processing. causing an overlap. the ref count make sure that exiting lower // work doesn't flip evaluating state to paused state. private int _progressStartCount = 0; private int _progressEvaluateCount = 0; public event EventHandler<ProgressData>? ProgressChanged; public bool InProgress => _progressStartCount > 0; public void Start() => ChangeProgressStatus(ref _progressStartCount, ProgressStatus.Started); public void Stop() => ChangeProgressStatus(ref _progressStartCount, ProgressStatus.Stopped); private void Evaluate() => ChangeProgressStatus(ref _progressEvaluateCount, ProgressStatus.Evaluating); private void Pause() => ChangeProgressStatus(ref _progressEvaluateCount, ProgressStatus.Paused); public void UpdatePendingItemCount(int pendingItemCount) { if (_progressStartCount > 0) { var progressData = new ProgressData(ProgressStatus.PendingItemCountUpdated, pendingItemCount); OnProgressChanged(progressData); } } /// <summary> /// Allows the solution crawler to start evaluating work enqueued to it. /// Returns an IDisposable that the caller must dispose of to indicate that it no longer needs the crawler to continue evaluating. /// Multiple callers can call into this simultaneously. /// Only when the last one actually disposes the scope-object will the crawler /// actually revert back to the paused state where no work proceeds. /// </summary> public IDisposable GetEvaluatingScope() => new ProgressStatusRAII(this); private void ChangeProgressStatus(ref int referenceCount, ProgressStatus status) { var start = status is ProgressStatus.Started or ProgressStatus.Evaluating; if (start ? (Interlocked.Increment(ref referenceCount) == 1) : (Interlocked.Decrement(ref referenceCount) == 0)) { var progressData = new ProgressData(status, pendingItemCount: null); OnProgressChanged(progressData); } } private void OnProgressChanged(ProgressData progressData) => ProgressChanged?.Invoke(this, progressData); private struct ProgressStatusRAII : IDisposable { private readonly SolutionCrawlerProgressReporter _owner; public ProgressStatusRAII(SolutionCrawlerProgressReporter owner) { _owner = owner; _owner.Evaluate(); } public void Dispose() => _owner.Pause(); } } /// <summary> /// reporter that doesn't do anything /// </summary> private class NullReporter : ISolutionCrawlerProgressReporter { public static readonly NullReporter Instance = new(); public bool InProgress => false; public event EventHandler<ProgressData> ProgressChanged { add { } remove { } } } } }
-1
dotnet/roslyn
55,828
Report an error for a misplaced `::` token.
Fixes #53021.
AlekseyTs
2021-08-23T22:49:32Z
2021-08-24T17:39:44Z
c083dae9fcb112d82c18b89687b9af65e7ef77b7
94cb8ed5ccc3c4b1d843acd9efa5629953f7607a
Report an error for a misplaced `::` token.. Fixes #53021.
./src/EditorFeatures/VisualBasicTest/Structure/ExternalMethodDeclarationStructureTests.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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class ExternalMethodDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of DeclareStatementSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New ExternalMethodDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestExternalMethodDeclarationWithComments() As Task Const code = " Class C {|span:'Hello 'World|} Declare Ansi Sub $$ExternSub Lib ""ExternDll"" () End Class " Await VerifyBlockSpansAsync(code, Region("span", "' Hello ...", autoCollapse:=True)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class ExternalMethodDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of DeclareStatementSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New ExternalMethodDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestExternalMethodDeclarationWithComments() As Task Const code = " Class C {|span:'Hello 'World|} Declare Ansi Sub $$ExternSub Lib ""ExternDll"" () End Class " Await VerifyBlockSpansAsync(code, Region("span", "' Hello ...", autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/EditorFeatures/Core.Wpf/CodeAnalysisColors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.Shared.Utilities { internal static class CodeAnalysisColors { private static object s_systemCaptionTextColorKey = "SystemCaptionTextColor"; private static object s_checkBoxTextBrushKey = "CheckboxTextBrush"; private static object s_systemCaptionTextBrushKey = "SystemCaptionTextBrush"; private static object s_backgroundBrushKey = "BackgroundBrush"; private static object s_buttonStyleKey = "ButtonStyle"; private static object s_accentBarColorKey = "AccentBarBrush"; public static object SystemCaptionTextColorKey { get { return s_systemCaptionTextColorKey; } set { s_systemCaptionTextColorKey = value; } } public static object SystemCaptionTextBrushKey { get { return s_systemCaptionTextBrushKey; } set { s_systemCaptionTextBrushKey = value; } } public static object CheckBoxTextBrushKey { get { return s_checkBoxTextBrushKey; } set { s_checkBoxTextBrushKey = value; } } public static object BackgroundBrushKey { get { return s_backgroundBrushKey; } set { s_backgroundBrushKey = value; } } public static object ButtonStyleKey { get { return s_buttonStyleKey; } set { s_buttonStyleKey = value; } } public static object AccentBarColorKey { get { return s_accentBarColorKey; } set { s_accentBarColorKey = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { internal static class CodeAnalysisColors { // Use VS color keys in order to support theming. public static object SystemCaptionTextColorKey => EnvironmentColors.SystemWindowTextColorKey; public static object CheckBoxTextBrushKey => EnvironmentColors.SystemWindowTextBrushKey; public static object SystemCaptionTextBrushKey => EnvironmentColors.SystemWindowTextBrushKey; public static object BackgroundBrushKey => VsBrushes.CommandBarGradientBeginKey; public static object ButtonStyleKey => VsResourceKeys.ButtonStyleKey; public static object AccentBarColorKey => EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey; } }
1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Editor</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <ApplyNgenOptimization>partial</ApplyNgenOptimization> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageDescription> .NET Compiler Platform ("Roslyn") support for WPF-dependent editor features inside the Visual Studio editor. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj"> <Aliases>InteractiveHost</Aliases> </ProjectReference> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj"> <Aliases>global,Scripting</Aliases> </ProjectReference> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CodeAnalysis.Elfie" Version="$(MicrosoftCodeAnalysisElfieVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.InteractiveWindow" Version="$(MicrosoftVisualStudioInteractiveWindowVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Interop" Version="$(MicrosoftVisualStudioInteropVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.NavigateTo.Interfaces" Version="$(MicrosoftVisualStudioLanguageNavigateToInterfacesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.StandardClassification" Version="$(MicrosoftVisualStudioLanguageStandardClassificationVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.Intellisense" Version="$(MicrosoftVisualStudioLanguageIntellisenseVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI.Wpf" Version="$(MicrosoftVisualStudioTextUIWpfVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CodeLens" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="Roslyn.Services.Test.Utilities" /> </ItemGroup> <ItemGroup> <Resource Include="InlineRename\Dashboard\Images\ErrorIcon.png" /> <Resource Include="InlineRename\Dashboard\Images\InfoIcon.png" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="EditorFeaturesWpfResources.resx" GenerateSource="true" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Editor</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <ApplyNgenOptimization>partial</ApplyNgenOptimization> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageDescription> .NET Compiler Platform ("Roslyn") support for WPF-dependent editor features inside the Visual Studio editor. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj"> <Aliases>InteractiveHost</Aliases> </ProjectReference> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj"> <Aliases>global,Scripting</Aliases> </ProjectReference> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.CodeAnalysis.Elfie" Version="$(MicrosoftCodeAnalysisElfieVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging" Version="$(MicrosoftVisualStudioImagingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.InteractiveWindow" Version="$(MicrosoftVisualStudioInteractiveWindowVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Interop" Version="$(MicrosoftVisualStudioInteropVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.NavigateTo.Interfaces" Version="$(MicrosoftVisualStudioLanguageNavigateToInterfacesVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.StandardClassification" Version="$(MicrosoftVisualStudioLanguageStandardClassificationVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Language.Intellisense" Version="$(MicrosoftVisualStudioLanguageIntellisenseVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Shell.15.0" Version="$(MicrosoftVisualStudioShell150Version)" /> <PackageReference Include="Microsoft.VisualStudio.Text.UI.Wpf" Version="$(MicrosoftVisualStudioTextUIWpfVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CodeLens" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.ServiceHub" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="Roslyn.Services.Test.Utilities" /> </ItemGroup> <ItemGroup> <Resource Include="InlineRename\Dashboard\Images\ErrorIcon.png" /> <Resource Include="InlineRename\Dashboard\Images\InfoIcon.png" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="EditorFeaturesWpfResources.resx" GenerateSource="true" /> </ItemGroup> </Project>
1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/VisualStudio/Core/Def/RoslynPackage.cs
// Licensed to the .NET Foundation under one or more 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.Design; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.ColorSchemes; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings; using Microsoft.VisualStudio.LanguageServices.Experimentation; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Diagnostics; using Microsoft.VisualStudio.LanguageServices.Implementation.Interactive; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets; using Microsoft.VisualStudio.LanguageServices.Implementation.SyncNamespaces; using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource; using Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences; using Microsoft.VisualStudio.LanguageServices.Telemetry; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TaskStatusCenter; using Microsoft.VisualStudio.Telemetry; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Setup { [Guid(Guids.RoslynPackageIdString)] // The option page configuration is duplicated in PackageRegistration.pkgdef [ProvideToolWindow(typeof(ValueTracking.ValueTrackingToolWindow))] internal sealed class RoslynPackage : AbstractPackage { // The randomly-generated key name is used for serializing the Background Analysis Scope preference to the .SUO // file. It doesn't have any semantic meaning, but is intended to not conflict with any other extension that // might be saving an "AnalysisScope" named stream to the same file. // note: must be <= 31 characters long private const string BackgroundAnalysisScopeOptionKey = "AnalysisScope-DCE33A29A768"; private const byte BackgroundAnalysisScopeOptionVersion = 1; private static RoslynPackage? _lazyInstance; private VisualStudioWorkspace? _workspace; private IComponentModel? _componentModel; private RuleSetEventHandler? _ruleSetEventHandler; private ColorSchemeApplier? _colorSchemeApplier; private IDisposable? _solutionEventMonitor; private BackgroundAnalysisScope? _analysisScope; public RoslynPackage() { // We need to register an option in order for OnLoadOptions/OnSaveOptions to be called AddOptionKey(BackgroundAnalysisScopeOptionKey); } public BackgroundAnalysisScope? AnalysisScope { get { return _analysisScope; } set { if (_analysisScope == value) return; _analysisScope = value; AnalysisScopeChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler? AnalysisScopeChanged; internal static async ValueTask<RoslynPackage?> GetOrLoadAsync(IThreadingContext threadingContext, IAsyncServiceProvider serviceProvider, CancellationToken cancellationToken) { if (_lazyInstance is null) { await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var shell = (IVsShell7?)await serviceProvider.GetServiceAsync(typeof(SVsShell)).ConfigureAwait(true); Assumes.Present(shell); await shell.LoadPackageAsync(typeof(RoslynPackage).GUID); if (ErrorHandler.Succeeded(((IVsShell)shell).IsPackageLoaded(typeof(RoslynPackage).GUID, out var package))) { _lazyInstance = (RoslynPackage)package; } } return _lazyInstance; } protected override void OnLoadOptions(string key, Stream stream) { if (key == BackgroundAnalysisScopeOptionKey) { if (stream.ReadByte() == BackgroundAnalysisScopeOptionVersion) { var hasValue = stream.ReadByte() == 1; AnalysisScope = hasValue ? (BackgroundAnalysisScope)stream.ReadByte() : null; } else { AnalysisScope = null; } } base.OnLoadOptions(key, stream); } protected override void OnSaveOptions(string key, Stream stream) { if (key == BackgroundAnalysisScopeOptionKey) { stream.WriteByte(BackgroundAnalysisScopeOptionVersion); stream.WriteByte(AnalysisScope.HasValue ? (byte)1 : (byte)0); stream.WriteByte((byte)AnalysisScope.GetValueOrDefault()); } base.OnSaveOptions(key, stream); } protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _componentModel = (IComponentModel)await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true); cancellationToken.ThrowIfCancellationRequested(); Assumes.Present(_componentModel); // Ensure the options persisters are loaded since we have to fetch options from the shell LoadOptionPersistersAsync(_componentModel, cancellationToken).Forget(); _workspace = _componentModel.GetService<VisualStudioWorkspace>(); _workspace.Services.GetService<IExperimentationService>(); // Fetch the session synchronously on the UI thread; if this doesn't happen before we try using this on // the background thread then we will experience hangs like we see in this bug: // https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=190808 or // https://devdiv.visualstudio.com/DevDiv/_workitems?id=296981&_a=edit var telemetryService = (VisualStudioWorkspaceTelemetryService)_workspace.Services.GetRequiredService<IWorkspaceTelemetryService>(); telemetryService.InitializeTelemetrySession(TelemetryService.DefaultSession); Logger.Log(FunctionId.Run_Environment, KeyValueLogMessage.Create(m => m["Version"] = FileVersionInfo.GetVersionInfo(typeof(VisualStudioWorkspace).Assembly.Location).FileVersion)); InitializeColors(); // load some services that have to be loaded in UI thread LoadComponentsInUIContextOnceSolutionFullyLoadedAsync(cancellationToken).Forget(); _solutionEventMonitor = new SolutionEventMonitor(_workspace); TrackBulkFileOperations(); var settingsEditorFactory = _componentModel.GetService<SettingsEditorFactory>(); RegisterEditorFactory(settingsEditorFactory); } private async Task LoadOptionPersistersAsync(IComponentModel componentModel, CancellationToken cancellationToken) { var listenerProvider = componentModel.GetService<IAsynchronousOperationListenerProvider>(); using var token = listenerProvider.GetListener(FeatureAttribute.Workspace).BeginAsyncOperation(nameof(LoadOptionPersistersAsync)); // Switch to a background thread to ensure assembly loads don't show up as UI delays attributed to // InitializeAsync. await TaskScheduler.Default; var persisterProviders = componentModel.GetExtensions<IOptionPersisterProvider>().ToImmutableArray(); foreach (var provider in persisterProviders) { _ = await provider.GetOrCreatePersisterAsync(cancellationToken).ConfigureAwait(true); } } private void InitializeColors() { // Use VS color keys in order to support theming. CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey; CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey; CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey; CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey; CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey; CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey; // Initialize ColorScheme support _colorSchemeApplier = ComponentModel.GetService<ColorSchemeApplier>(); _colorSchemeApplier.Initialize(); } protected override async Task LoadComponentsAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await GetServiceAsync(typeof(SVsTaskStatusCenterService)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsErrorList)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsSolution)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsShell)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsRunningDocumentTable)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsTextManager)).ConfigureAwait(true); // we need to load it as early as possible since we can have errors from // package from each language very early this.ComponentModel.GetService<TaskCenterSolutionAnalysisProgressReporter>(); this.ComponentModel.GetService<VisualStudioDiagnosticListTableCommandHandler>().Initialize(this); this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>(); // The misc files workspace needs to be loaded on the UI thread. This way it will have // the appropriate task scheduler to report events on. this.ComponentModel.GetService<MiscellaneousFilesWorkspace>(); // Load and initialize the add solution item service so ConfigurationUpdater can use it to create editorconfig files. this.ComponentModel.GetService<VisualStudioAddSolutionItemService>().Initialize(this); this.ComponentModel.GetService<IVisualStudioDiagnosticAnalyzerService>().Initialize(this); this.ComponentModel.GetService<RemoveUnusedReferencesCommandHandler>().Initialize(this); this.ComponentModel.GetService<SyncNamespacesCommandHandler>().Initialize(this); LoadAnalyzerNodeComponents(); LoadComponentsBackgroundAsync(cancellationToken).Forget(); } // Overrides for VSSDK003 fix // See https://github.com/Microsoft/VSSDK-Analyzers/blob/main/doc/VSSDK003.md public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWindowType) => toolWindowType == typeof(ValueTracking.ValueTrackingToolWindow).GUID ? this : base.GetAsyncToolWindowFactory(toolWindowType); protected override string GetToolWindowTitle(Type toolWindowType, int id) => base.GetToolWindowTitle(toolWindowType, id); protected override Task<object?> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) => Task.FromResult((object?)null); private async Task LoadComponentsBackgroundAsync(CancellationToken cancellationToken) { await TaskScheduler.Default; await LoadInteractiveMenusAsync(cancellationToken).ConfigureAwait(true); // Initialize any experiments async var experiments = this.ComponentModel.DefaultExportProvider.GetExportedValues<IExperiment>(); foreach (var experiment in experiments) { await experiment.InitializeAsync().ConfigureAwait(true); } } private async Task LoadInteractiveMenusAsync(CancellationToken cancellationToken) { // Obtain services and QueryInterface from the main thread await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var menuCommandService = (OleMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true); var monitorSelectionService = (IVsMonitorSelection)await GetServiceAsync(typeof(SVsShellMonitorSelection)).ConfigureAwait(true); // Switch to the background object for constructing commands await TaskScheduler.Default; await new CSharpResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel) .InitializeResetInteractiveFromProjectCommandAsync() .ConfigureAwait(true); await new VisualBasicResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel) .InitializeResetInteractiveFromProjectCommandAsync() .ConfigureAwait(true); } internal IComponentModel ComponentModel { get { return _componentModel ?? throw new InvalidOperationException($"Cannot use {nameof(RoslynPackage)}.{nameof(ComponentModel)} prior to initialization."); } } protected override void Dispose(bool disposing) { DisposeVisualStudioServices(); UnregisterAnalyzerTracker(); UnregisterRuleSetEventHandler(); ReportSessionWideTelemetry(); if (_solutionEventMonitor != null) { _solutionEventMonitor.Dispose(); _solutionEventMonitor = null; } base.Dispose(disposing); } private void ReportSessionWideTelemetry() { SolutionLogger.ReportTelemetry(); AsyncCompletionLogger.ReportTelemetry(); CompletionProvidersLogger.ReportTelemetry(); ChangeSignatureLogger.ReportTelemetry(); } private void DisposeVisualStudioServices() { if (_workspace != null) { _workspace.Services.GetRequiredService<VisualStudioMetadataReferenceManager>().DisconnectFromVisualStudioNativeServices(); } } private void LoadAnalyzerNodeComponents() { this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this); _ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>(); if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Register(); } } private void UnregisterAnalyzerTracker() => this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister(); private void UnregisterRuleSetEventHandler() { if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Unregister(); _ruleSetEventHandler = null; } } private void TrackBulkFileOperations() { RoslynDebug.AssertNotNull(_workspace); // we will pause whatever ambient work loads we have that are tied to IGlobalOperationNotificationService // such as solution crawler, pre-emptive remote host synchronization and etc. any background work users didn't // explicitly asked for. // // this should give all resources to BulkFileOperation. we do same for things like build, // debugging, wait dialog and etc. BulkFileOperation is used for things like git branch switching and etc. var globalNotificationService = _workspace.Services.GetRequiredService<IGlobalOperationNotificationService>(); // BulkFileOperation can't have nested events. there will be ever only 1 events (Begin/End) // so we only need simple tracking. var gate = new object(); GlobalOperationRegistration? localRegistration = null; BulkFileOperation.End += (s, a) => { StopBulkFileOperationNotification(); }; BulkFileOperation.Begin += (s, a) => { StartBulkFileOperationNotification(); }; void StartBulkFileOperationNotification() { RoslynDebug.Assert(gate != null); RoslynDebug.Assert(globalNotificationService != null); lock (gate) { // this shouldn't happen, but we are using external component // so guarding us from them if (localRegistration != null) { FatalError.ReportAndCatch(new InvalidOperationException("BulkFileOperation already exist")); return; } localRegistration = globalNotificationService.Start("BulkFileOperation"); } } void StopBulkFileOperationNotification() { RoslynDebug.Assert(gate != null); lock (gate) { // this can happen if BulkFileOperation was already in the middle // of running. to make things simpler, decide to not use IsInProgress // which we need to worry about race case. if (localRegistration == null) { return; } localRegistration.Dispose(); localRegistration = null; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.ComponentModel.Design; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.CodeAnalysis.Completion.Log; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.ColorSchemes; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings; using Microsoft.VisualStudio.LanguageServices.Experimentation; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Diagnostics; using Microsoft.VisualStudio.LanguageServices.Implementation.Interactive; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets; using Microsoft.VisualStudio.LanguageServices.Implementation.SyncNamespaces; using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource; using Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences; using Microsoft.VisualStudio.LanguageServices.Telemetry; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TaskStatusCenter; using Microsoft.VisualStudio.Telemetry; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Setup { [Guid(Guids.RoslynPackageIdString)] // The option page configuration is duplicated in PackageRegistration.pkgdef [ProvideToolWindow(typeof(ValueTracking.ValueTrackingToolWindow))] internal sealed class RoslynPackage : AbstractPackage { // The randomly-generated key name is used for serializing the Background Analysis Scope preference to the .SUO // file. It doesn't have any semantic meaning, but is intended to not conflict with any other extension that // might be saving an "AnalysisScope" named stream to the same file. // note: must be <= 31 characters long private const string BackgroundAnalysisScopeOptionKey = "AnalysisScope-DCE33A29A768"; private const byte BackgroundAnalysisScopeOptionVersion = 1; private static RoslynPackage? _lazyInstance; private VisualStudioWorkspace? _workspace; private IComponentModel? _componentModel; private RuleSetEventHandler? _ruleSetEventHandler; private ColorSchemeApplier? _colorSchemeApplier; private IDisposable? _solutionEventMonitor; private BackgroundAnalysisScope? _analysisScope; public RoslynPackage() { // We need to register an option in order for OnLoadOptions/OnSaveOptions to be called AddOptionKey(BackgroundAnalysisScopeOptionKey); } public BackgroundAnalysisScope? AnalysisScope { get { return _analysisScope; } set { if (_analysisScope == value) return; _analysisScope = value; AnalysisScopeChanged?.Invoke(this, EventArgs.Empty); } } public event EventHandler? AnalysisScopeChanged; internal static async ValueTask<RoslynPackage?> GetOrLoadAsync(IThreadingContext threadingContext, IAsyncServiceProvider serviceProvider, CancellationToken cancellationToken) { if (_lazyInstance is null) { await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var shell = (IVsShell7?)await serviceProvider.GetServiceAsync(typeof(SVsShell)).ConfigureAwait(true); Assumes.Present(shell); await shell.LoadPackageAsync(typeof(RoslynPackage).GUID); if (ErrorHandler.Succeeded(((IVsShell)shell).IsPackageLoaded(typeof(RoslynPackage).GUID, out var package))) { _lazyInstance = (RoslynPackage)package; } } return _lazyInstance; } protected override void OnLoadOptions(string key, Stream stream) { if (key == BackgroundAnalysisScopeOptionKey) { if (stream.ReadByte() == BackgroundAnalysisScopeOptionVersion) { var hasValue = stream.ReadByte() == 1; AnalysisScope = hasValue ? (BackgroundAnalysisScope)stream.ReadByte() : null; } else { AnalysisScope = null; } } base.OnLoadOptions(key, stream); } protected override void OnSaveOptions(string key, Stream stream) { if (key == BackgroundAnalysisScopeOptionKey) { stream.WriteByte(BackgroundAnalysisScopeOptionVersion); stream.WriteByte(AnalysisScope.HasValue ? (byte)1 : (byte)0); stream.WriteByte((byte)AnalysisScope.GetValueOrDefault()); } base.OnSaveOptions(key, stream); } protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _componentModel = (IComponentModel)await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true); cancellationToken.ThrowIfCancellationRequested(); Assumes.Present(_componentModel); // Ensure the options persisters are loaded since we have to fetch options from the shell LoadOptionPersistersAsync(_componentModel, cancellationToken).Forget(); _workspace = _componentModel.GetService<VisualStudioWorkspace>(); _workspace.Services.GetService<IExperimentationService>(); // Fetch the session synchronously on the UI thread; if this doesn't happen before we try using this on // the background thread then we will experience hangs like we see in this bug: // https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=190808 or // https://devdiv.visualstudio.com/DevDiv/_workitems?id=296981&_a=edit var telemetryService = (VisualStudioWorkspaceTelemetryService)_workspace.Services.GetRequiredService<IWorkspaceTelemetryService>(); telemetryService.InitializeTelemetrySession(TelemetryService.DefaultSession); Logger.Log(FunctionId.Run_Environment, KeyValueLogMessage.Create(m => m["Version"] = FileVersionInfo.GetVersionInfo(typeof(VisualStudioWorkspace).Assembly.Location).FileVersion)); InitializeColors(); // load some services that have to be loaded in UI thread LoadComponentsInUIContextOnceSolutionFullyLoadedAsync(cancellationToken).Forget(); _solutionEventMonitor = new SolutionEventMonitor(_workspace); TrackBulkFileOperations(); var settingsEditorFactory = _componentModel.GetService<SettingsEditorFactory>(); RegisterEditorFactory(settingsEditorFactory); } private async Task LoadOptionPersistersAsync(IComponentModel componentModel, CancellationToken cancellationToken) { var listenerProvider = componentModel.GetService<IAsynchronousOperationListenerProvider>(); using var token = listenerProvider.GetListener(FeatureAttribute.Workspace).BeginAsyncOperation(nameof(LoadOptionPersistersAsync)); // Switch to a background thread to ensure assembly loads don't show up as UI delays attributed to // InitializeAsync. await TaskScheduler.Default; var persisterProviders = componentModel.GetExtensions<IOptionPersisterProvider>().ToImmutableArray(); foreach (var provider in persisterProviders) { _ = await provider.GetOrCreatePersisterAsync(cancellationToken).ConfigureAwait(true); } } private void InitializeColors() { // Initialize ColorScheme support _colorSchemeApplier = ComponentModel.GetService<ColorSchemeApplier>(); _colorSchemeApplier.Initialize(); } protected override async Task LoadComponentsAsync(CancellationToken cancellationToken) { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); await GetServiceAsync(typeof(SVsTaskStatusCenterService)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsErrorList)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsSolution)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsShell)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsRunningDocumentTable)).ConfigureAwait(true); await GetServiceAsync(typeof(SVsTextManager)).ConfigureAwait(true); // we need to load it as early as possible since we can have errors from // package from each language very early this.ComponentModel.GetService<TaskCenterSolutionAnalysisProgressReporter>(); this.ComponentModel.GetService<VisualStudioDiagnosticListTableCommandHandler>().Initialize(this); this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>(); // The misc files workspace needs to be loaded on the UI thread. This way it will have // the appropriate task scheduler to report events on. this.ComponentModel.GetService<MiscellaneousFilesWorkspace>(); // Load and initialize the add solution item service so ConfigurationUpdater can use it to create editorconfig files. this.ComponentModel.GetService<VisualStudioAddSolutionItemService>().Initialize(this); this.ComponentModel.GetService<IVisualStudioDiagnosticAnalyzerService>().Initialize(this); this.ComponentModel.GetService<RemoveUnusedReferencesCommandHandler>().Initialize(this); this.ComponentModel.GetService<SyncNamespacesCommandHandler>().Initialize(this); LoadAnalyzerNodeComponents(); LoadComponentsBackgroundAsync(cancellationToken).Forget(); } // Overrides for VSSDK003 fix // See https://github.com/Microsoft/VSSDK-Analyzers/blob/main/doc/VSSDK003.md public override IVsAsyncToolWindowFactory GetAsyncToolWindowFactory(Guid toolWindowType) => toolWindowType == typeof(ValueTracking.ValueTrackingToolWindow).GUID ? this : base.GetAsyncToolWindowFactory(toolWindowType); protected override string GetToolWindowTitle(Type toolWindowType, int id) => base.GetToolWindowTitle(toolWindowType, id); protected override Task<object?> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken) => Task.FromResult((object?)null); private async Task LoadComponentsBackgroundAsync(CancellationToken cancellationToken) { await TaskScheduler.Default; await LoadInteractiveMenusAsync(cancellationToken).ConfigureAwait(true); // Initialize any experiments async var experiments = this.ComponentModel.DefaultExportProvider.GetExportedValues<IExperiment>(); foreach (var experiment in experiments) { await experiment.InitializeAsync().ConfigureAwait(true); } } private async Task LoadInteractiveMenusAsync(CancellationToken cancellationToken) { // Obtain services and QueryInterface from the main thread await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var menuCommandService = (OleMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true); var monitorSelectionService = (IVsMonitorSelection)await GetServiceAsync(typeof(SVsShellMonitorSelection)).ConfigureAwait(true); // Switch to the background object for constructing commands await TaskScheduler.Default; await new CSharpResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel) .InitializeResetInteractiveFromProjectCommandAsync() .ConfigureAwait(true); await new VisualBasicResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel) .InitializeResetInteractiveFromProjectCommandAsync() .ConfigureAwait(true); } internal IComponentModel ComponentModel { get { return _componentModel ?? throw new InvalidOperationException($"Cannot use {nameof(RoslynPackage)}.{nameof(ComponentModel)} prior to initialization."); } } protected override void Dispose(bool disposing) { DisposeVisualStudioServices(); UnregisterAnalyzerTracker(); UnregisterRuleSetEventHandler(); ReportSessionWideTelemetry(); if (_solutionEventMonitor != null) { _solutionEventMonitor.Dispose(); _solutionEventMonitor = null; } base.Dispose(disposing); } private void ReportSessionWideTelemetry() { SolutionLogger.ReportTelemetry(); AsyncCompletionLogger.ReportTelemetry(); CompletionProvidersLogger.ReportTelemetry(); ChangeSignatureLogger.ReportTelemetry(); } private void DisposeVisualStudioServices() { if (_workspace != null) { _workspace.Services.GetRequiredService<VisualStudioMetadataReferenceManager>().DisconnectFromVisualStudioNativeServices(); } } private void LoadAnalyzerNodeComponents() { this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this); _ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>(); if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Register(); } } private void UnregisterAnalyzerTracker() => this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister(); private void UnregisterRuleSetEventHandler() { if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Unregister(); _ruleSetEventHandler = null; } } private void TrackBulkFileOperations() { RoslynDebug.AssertNotNull(_workspace); // we will pause whatever ambient work loads we have that are tied to IGlobalOperationNotificationService // such as solution crawler, pre-emptive remote host synchronization and etc. any background work users didn't // explicitly asked for. // // this should give all resources to BulkFileOperation. we do same for things like build, // debugging, wait dialog and etc. BulkFileOperation is used for things like git branch switching and etc. var globalNotificationService = _workspace.Services.GetRequiredService<IGlobalOperationNotificationService>(); // BulkFileOperation can't have nested events. there will be ever only 1 events (Begin/End) // so we only need simple tracking. var gate = new object(); GlobalOperationRegistration? localRegistration = null; BulkFileOperation.End += (s, a) => { StopBulkFileOperationNotification(); }; BulkFileOperation.Begin += (s, a) => { StartBulkFileOperationNotification(); }; void StartBulkFileOperationNotification() { RoslynDebug.Assert(gate != null); RoslynDebug.Assert(globalNotificationService != null); lock (gate) { // this shouldn't happen, but we are using external component // so guarding us from them if (localRegistration != null) { FatalError.ReportAndCatch(new InvalidOperationException("BulkFileOperation already exist")); return; } localRegistration = globalNotificationService.Start("BulkFileOperation"); } } void StopBulkFileOperationNotification() { RoslynDebug.Assert(gate != null); lock (gate) { // this can happen if BulkFileOperation was already in the middle // of running. to make things simpler, decide to not use IsInProgress // which we need to worry about race case. if (localRegistration == null) { return; } localRegistration.Dispose(); localRegistration = null; } } } } }
1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/Core/Portable/Diagnostic/FileLinePositionSpan.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a span of text in a source code file in terms of file name, line number, and offset within line. /// However, the file is actually whatever was passed in when asked to parse; there may not really be a file. /// </summary> public readonly struct FileLinePositionSpan : IEquatable<FileLinePositionSpan> { /// <summary> /// Path, or null if the span represents an invalid value. /// </summary> /// <remarks> /// Path may be <see cref="string.Empty"/> if not available. /// </remarks> public string Path { get; } /// <summary> /// True if the <see cref="Path"/> is a mapped path. /// </summary> /// <remarks> /// A mapped path is a path specified in source via <c>#line</c> (C#) or <c>#ExternalSource</c> (VB) directives. /// </remarks> public bool HasMappedPath { get; } /// <summary> /// Gets the span. /// </summary> public LinePositionSpan Span { get; } /// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="start">The start line position.</param> /// <param name="end">The end line position.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePosition start, LinePosition end) : this(path, new LinePositionSpan(start, end)) { } /// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="span">The span.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePositionSpan span) { Path = path ?? throw new ArgumentNullException(nameof(path)); Span = span; HasMappedPath = false; } internal FileLinePositionSpan(string path, LinePositionSpan span, bool hasMappedPath) { Path = path; Span = span; HasMappedPath = hasMappedPath; } /// <summary> /// Gets the <see cref="LinePosition"/> of the start of the span. /// </summary> /// <returns></returns> public LinePosition StartLinePosition => Span.Start; /// <summary> /// Gets the <see cref="LinePosition"/> of the end of the span. /// </summary> /// <returns></returns> public LinePosition EndLinePosition => Span.End; /// <summary> /// Returns true if the span represents a valid location. /// </summary> public bool IsValid => Path != null; // invalid span can be constructed by new FileLinePositionSpan() /// <summary> /// Determines if two FileLinePositionSpan objects are equal. /// </summary> /// <remarks> /// The path is treated as an opaque string, i.e. a case-sensitive comparison is used. /// </remarks> public bool Equals(FileLinePositionSpan other) => Span.Equals(other.Span) && HasMappedPath == other.HasMappedPath && string.Equals(Path, other.Path, StringComparison.Ordinal); /// <summary> /// Determines if two FileLinePositionSpan objects are equal. /// </summary> public override bool Equals(object? other) => other is FileLinePositionSpan span && Equals(span); /// <summary> /// Serves as a hash function for FileLinePositionSpan. /// </summary> /// <returns>The hash code.</returns> /// <remarks> /// The path is treated as an opaque string, i.e. a case-sensitive hash is calculated. /// </remarks> public override int GetHashCode() => Hash.Combine(Path, Hash.Combine(HasMappedPath, Span.GetHashCode())); /// <summary> /// Returns a <see cref="string"/> that represents <see cref="FileLinePositionSpan"/>. /// </summary> /// <returns>The string representation of <see cref="FileLinePositionSpan"/>.</returns> /// <example>Path: (0,0)-(5,6)</example> public override string ToString() => Path + ": " + Span; public static bool operator ==(FileLinePositionSpan left, FileLinePositionSpan right) => left.Equals(right); public static bool operator !=(FileLinePositionSpan left, FileLinePositionSpan right) => !(left == right); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a span of text in a source code file in terms of file name, line number, and offset within line. /// However, the file is actually whatever was passed in when asked to parse; there may not really be a file. /// </summary> public readonly struct FileLinePositionSpan : IEquatable<FileLinePositionSpan> { /// <summary> /// Path, or null if the span represents an invalid value. /// </summary> /// <remarks> /// Path may be <see cref="string.Empty"/> if not available. /// </remarks> public string Path { get; } /// <summary> /// True if the <see cref="Path"/> is a mapped path. /// </summary> /// <remarks> /// A mapped path is a path specified in source via <c>#line</c> (C#) or <c>#ExternalSource</c> (VB) directives. /// </remarks> public bool HasMappedPath { get; } /// <summary> /// Gets the span. /// </summary> public LinePositionSpan Span { get; } /// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="start">The start line position.</param> /// <param name="end">The end line position.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePosition start, LinePosition end) : this(path, new LinePositionSpan(start, end)) { } /// <summary> /// Initializes the <see cref="FileLinePositionSpan"/> instance. /// </summary> /// <param name="path">The file identifier - typically a relative or absolute path.</param> /// <param name="span">The span.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> public FileLinePositionSpan(string path, LinePositionSpan span) { Path = path ?? throw new ArgumentNullException(nameof(path)); Span = span; HasMappedPath = false; } internal FileLinePositionSpan(string path, LinePositionSpan span, bool hasMappedPath) { Path = path; Span = span; HasMappedPath = hasMappedPath; } /// <summary> /// Gets the <see cref="LinePosition"/> of the start of the span. /// </summary> /// <returns></returns> public LinePosition StartLinePosition => Span.Start; /// <summary> /// Gets the <see cref="LinePosition"/> of the end of the span. /// </summary> /// <returns></returns> public LinePosition EndLinePosition => Span.End; /// <summary> /// Returns true if the span represents a valid location. /// </summary> public bool IsValid => Path != null; // invalid span can be constructed by new FileLinePositionSpan() /// <summary> /// Determines if two FileLinePositionSpan objects are equal. /// </summary> /// <remarks> /// The path is treated as an opaque string, i.e. a case-sensitive comparison is used. /// </remarks> public bool Equals(FileLinePositionSpan other) => Span.Equals(other.Span) && HasMappedPath == other.HasMappedPath && string.Equals(Path, other.Path, StringComparison.Ordinal); /// <summary> /// Determines if two FileLinePositionSpan objects are equal. /// </summary> public override bool Equals(object? other) => other is FileLinePositionSpan span && Equals(span); /// <summary> /// Serves as a hash function for FileLinePositionSpan. /// </summary> /// <returns>The hash code.</returns> /// <remarks> /// The path is treated as an opaque string, i.e. a case-sensitive hash is calculated. /// </remarks> public override int GetHashCode() => Hash.Combine(Path, Hash.Combine(HasMappedPath, Span.GetHashCode())); /// <summary> /// Returns a <see cref="string"/> that represents <see cref="FileLinePositionSpan"/>. /// </summary> /// <returns>The string representation of <see cref="FileLinePositionSpan"/>.</returns> /// <example>Path: (0,0)-(5,6)</example> public override string ToString() => Path + ": " + Span; public static bool operator ==(FileLinePositionSpan left, FileLinePositionSpan right) => left.Equals(right); public static bool operator !=(FileLinePositionSpan left, FileLinePositionSpan right) => !(left == right); } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/IndentUserSettingsFormattingRule.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal sealed class IndentUserSettingsFormattingRule : BaseFormattingRule { private readonly CachedOptions _options; public IndentUserSettingsFormattingRule() : this(new CachedOptions(null)) { } private IndentUserSettingsFormattingRule(CachedOptions options) { _options = options; } public override AbstractFormattingRule WithOptions(AnalyzerConfigOptions options) { var cachedOptions = new CachedOptions(options); if (cachedOptions == _options) { return this; } return new IndentUserSettingsFormattingRule(cachedOptions); } public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) { nextOperation.Invoke(); var bracePair = node.GetBracePair(); // don't put block indentation operation if the block only contains lambda expression body block if (node.IsLambdaBodyBlock() || !bracePair.IsValidBracePair()) { return; } if (_options.IndentBraces) { AddIndentBlockOperation(list, bracePair.Item1, bracePair.Item1, bracePair.Item1.Span); AddIndentBlockOperation(list, bracePair.Item2, bracePair.Item2, bracePair.Item2.Span); } } private readonly struct CachedOptions : IEquatable<CachedOptions> { public readonly bool IndentBraces; public CachedOptions(AnalyzerConfigOptions? options) { IndentBraces = GetOptionOrDefault(options, CSharpFormattingOptions2.IndentBraces); } public static bool operator ==(CachedOptions left, CachedOptions right) => left.Equals(right); public static bool operator !=(CachedOptions left, CachedOptions right) => !(left == right); private static T GetOptionOrDefault<T>(AnalyzerConfigOptions? options, Option2<T> option) { if (options is null) return option.DefaultValue; return options.GetOption(option); } public override bool Equals(object? obj) => obj is CachedOptions options && Equals(options); public bool Equals(CachedOptions other) { return IndentBraces == other.IndentBraces; } public override int GetHashCode() { var hashCode = 0; hashCode = (hashCode << 1) + (IndentBraces ? 1 : 0); return hashCode; } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal sealed class IndentUserSettingsFormattingRule : BaseFormattingRule { private readonly CachedOptions _options; public IndentUserSettingsFormattingRule() : this(new CachedOptions(null)) { } private IndentUserSettingsFormattingRule(CachedOptions options) { _options = options; } public override AbstractFormattingRule WithOptions(AnalyzerConfigOptions options) { var cachedOptions = new CachedOptions(options); if (cachedOptions == _options) { return this; } return new IndentUserSettingsFormattingRule(cachedOptions); } public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) { nextOperation.Invoke(); var bracePair = node.GetBracePair(); // don't put block indentation operation if the block only contains lambda expression body block if (node.IsLambdaBodyBlock() || !bracePair.IsValidBracePair()) { return; } if (_options.IndentBraces) { AddIndentBlockOperation(list, bracePair.Item1, bracePair.Item1, bracePair.Item1.Span); AddIndentBlockOperation(list, bracePair.Item2, bracePair.Item2, bracePair.Item2.Span); } } private readonly struct CachedOptions : IEquatable<CachedOptions> { public readonly bool IndentBraces; public CachedOptions(AnalyzerConfigOptions? options) { IndentBraces = GetOptionOrDefault(options, CSharpFormattingOptions2.IndentBraces); } public static bool operator ==(CachedOptions left, CachedOptions right) => left.Equals(right); public static bool operator !=(CachedOptions left, CachedOptions right) => !(left == right); private static T GetOptionOrDefault<T>(AnalyzerConfigOptions? options, Option2<T> option) { if (options is null) return option.DefaultValue; return options.GetOption(option); } public override bool Equals(object? obj) => obj is CachedOptions options && Equals(options); public bool Equals(CachedOptions other) { return IndentBraces == other.IndentBraces; } public override int GetHashCode() { var hashCode = 0; hashCode = (hashCode << 1) + (IndentBraces ? 1 : 0); return hashCode; } } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Features/Core/Portable/ExtractMethod/MethodExtractor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected readonly SelectionResult OriginalSelectionResult; protected readonly bool LocalFunction; public MethodExtractor(SelectionResult selectionResult, bool localFunction) { Contract.ThrowIfNull(selectionResult); OriginalSelectionResult = selectionResult; LocalFunction = localFunction; } protected abstract Task<AnalyzerResult> AnalyzeAsync(SelectionResult selectionResult, bool localFunction, CancellationToken cancellationToken); protected abstract Task<InsertionPoint> GetInsertionPointAsync(SemanticDocument document, CancellationToken cancellationToken); protected abstract Task<TriviaResult> PreserveTriviaAsync(SelectionResult selectionResult, CancellationToken cancellationToken); protected abstract Task<SemanticDocument> ExpandAsync(SelectionResult selection, CancellationToken cancellationToken); protected abstract Task<GeneratedCode> GenerateCodeAsync(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzeResult, OptionSet options, CancellationToken cancellationToken); protected abstract SyntaxToken GetMethodNameAtInvocation(IEnumerable<SyntaxNodeOrToken> methodNames); protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document); protected abstract Task<OperationStatus> CheckTypeAsync(Document document, SyntaxNode contextNode, Location location, ITypeSymbol type, CancellationToken cancellationToken); protected abstract Task<(Document document, SyntaxToken methodName, SyntaxNode methodDefinition)> InsertNewLineBeforeLocalFunctionIfNecessaryAsync(Document document, SyntaxToken methodName, SyntaxNode methodDefinition, CancellationToken cancellationToken); public async Task<ExtractMethodResult> ExtractMethodAsync(CancellationToken cancellationToken) { var operationStatus = OriginalSelectionResult.Status; var analyzeResult = await AnalyzeAsync(OriginalSelectionResult, LocalFunction, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); operationStatus = await CheckVariableTypesAsync(analyzeResult.Status.With(operationStatus), analyzeResult, cancellationToken).ConfigureAwait(false); if (operationStatus.FailedWithNoBestEffortSuggestion()) { return new FailedExtractMethodResult(operationStatus); } var insertionPoint = await GetInsertionPointAsync(analyzeResult.SemanticDocument, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var triviaResult = await PreserveTriviaAsync(OriginalSelectionResult.With(insertionPoint.SemanticDocument), cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var expandedDocument = await ExpandAsync(OriginalSelectionResult.With(triviaResult.SemanticDocument), cancellationToken).ConfigureAwait(false); var options = await analyzeResult.SemanticDocument.Document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var generatedCode = await GenerateCodeAsync( insertionPoint.With(expandedDocument), OriginalSelectionResult.With(expandedDocument), analyzeResult.With(expandedDocument), options, cancellationToken).ConfigureAwait(false); var applied = await triviaResult.ApplyAsync(generatedCode, cancellationToken).ConfigureAwait(false); var afterTriviaRestored = applied.With(operationStatus); cancellationToken.ThrowIfCancellationRequested(); if (afterTriviaRestored.Status.FailedWithNoBestEffortSuggestion()) { return await CreateExtractMethodResultAsync( operationStatus, generatedCode.SemanticDocument, generatedCode.MethodNameAnnotation, generatedCode.MethodDefinitionAnnotation, cancellationToken).ConfigureAwait(false); } var finalDocument = afterTriviaRestored.Data.Document; finalDocument = await Formatter.FormatAsync( finalDocument, Formatter.Annotation, options: null, rules: GetFormattingRules(finalDocument), cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); return await CreateExtractMethodResultAsync( operationStatus.With(generatedCode.Status), await SemanticDocument.CreateAsync(finalDocument, cancellationToken).ConfigureAwait(false), generatedCode.MethodNameAnnotation, generatedCode.MethodDefinitionAnnotation, cancellationToken).ConfigureAwait(false); } private async Task<ExtractMethodResult> CreateExtractMethodResultAsync( OperationStatus status, SemanticDocument semanticDocument, SyntaxAnnotation invocationAnnotation, SyntaxAnnotation methodAnnotation, CancellationToken cancellationToken) { var newRoot = semanticDocument.Root; var methodName = GetMethodNameAtInvocation(newRoot.GetAnnotatedNodesAndTokens(invocationAnnotation)); var methodDefinition = newRoot.GetAnnotatedNodesAndTokens(methodAnnotation).FirstOrDefault().AsNode(); if (LocalFunction && status.Succeeded()) { var result = await InsertNewLineBeforeLocalFunctionIfNecessaryAsync(semanticDocument.Document, methodName, methodDefinition, cancellationToken).ConfigureAwait(false); return new SimpleExtractMethodResult(status, result.document, result.methodName, result.methodDefinition); } return new SimpleExtractMethodResult(status, semanticDocument.Document, methodName, methodDefinition); } private async Task<OperationStatus> CheckVariableTypesAsync( OperationStatus status, AnalyzerResult analyzeResult, CancellationToken cancellationToken) { var document = analyzeResult.SemanticDocument; // sync selection result to same semantic data as analyzeResult var firstToken = OriginalSelectionResult.With(document).GetFirstTokenInSelection(); var context = firstToken.Parent; var result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), status, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.MethodParameters, result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToMoveOutToCallSite(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { return result.Item2; } } } } } status = result.Item2; var checkedStatus = await CheckTypeAsync(document.Document, context, context.GetLocation(), analyzeResult.ReturnType, cancellationToken).ConfigureAwait(false); return checkedStatus.With(status); } private async Task<Tuple<bool, OperationStatus>> TryCheckVariableTypeAsync( SemanticDocument document, SyntaxNode contextNode, IEnumerable<VariableInfo> variables, OperationStatus status, CancellationToken cancellationToken) { if (status.FailedWithNoBestEffortSuggestion()) { return Tuple.Create(false, status); } var location = contextNode.GetLocation(); foreach (var variable in variables) { var originalType = variable.GetVariableType(document); var result = await CheckTypeAsync(document.Document, contextNode, location, originalType, cancellationToken).ConfigureAwait(false); if (result.FailedWithNoBestEffortSuggestion()) { status = status.With(result); return Tuple.Create(false, status); } } return Tuple.Create(true, status); } internal static string MakeMethodName(string prefix, string originalName, bool camelCase) { var startingWithLetter = originalName.ToCharArray().SkipWhile(c => !char.IsLetter(c)).ToArray(); var name = startingWithLetter.Length == 0 ? originalName : new string(startingWithLetter); if (camelCase && !prefix.IsEmpty()) { prefix = char.ToLowerInvariant(prefix[0]) + prefix[1..]; } return char.IsUpper(name[0]) ? prefix + name : prefix + char.ToUpper(name[0]).ToString() + name[1..]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected readonly SelectionResult OriginalSelectionResult; protected readonly bool LocalFunction; public MethodExtractor(SelectionResult selectionResult, bool localFunction) { Contract.ThrowIfNull(selectionResult); OriginalSelectionResult = selectionResult; LocalFunction = localFunction; } protected abstract Task<AnalyzerResult> AnalyzeAsync(SelectionResult selectionResult, bool localFunction, CancellationToken cancellationToken); protected abstract Task<InsertionPoint> GetInsertionPointAsync(SemanticDocument document, CancellationToken cancellationToken); protected abstract Task<TriviaResult> PreserveTriviaAsync(SelectionResult selectionResult, CancellationToken cancellationToken); protected abstract Task<SemanticDocument> ExpandAsync(SelectionResult selection, CancellationToken cancellationToken); protected abstract Task<GeneratedCode> GenerateCodeAsync(InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzeResult, OptionSet options, CancellationToken cancellationToken); protected abstract SyntaxToken GetMethodNameAtInvocation(IEnumerable<SyntaxNodeOrToken> methodNames); protected abstract IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document); protected abstract Task<OperationStatus> CheckTypeAsync(Document document, SyntaxNode contextNode, Location location, ITypeSymbol type, CancellationToken cancellationToken); protected abstract Task<(Document document, SyntaxToken methodName, SyntaxNode methodDefinition)> InsertNewLineBeforeLocalFunctionIfNecessaryAsync(Document document, SyntaxToken methodName, SyntaxNode methodDefinition, CancellationToken cancellationToken); public async Task<ExtractMethodResult> ExtractMethodAsync(CancellationToken cancellationToken) { var operationStatus = OriginalSelectionResult.Status; var analyzeResult = await AnalyzeAsync(OriginalSelectionResult, LocalFunction, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); operationStatus = await CheckVariableTypesAsync(analyzeResult.Status.With(operationStatus), analyzeResult, cancellationToken).ConfigureAwait(false); if (operationStatus.FailedWithNoBestEffortSuggestion()) { return new FailedExtractMethodResult(operationStatus); } var insertionPoint = await GetInsertionPointAsync(analyzeResult.SemanticDocument, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var triviaResult = await PreserveTriviaAsync(OriginalSelectionResult.With(insertionPoint.SemanticDocument), cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var expandedDocument = await ExpandAsync(OriginalSelectionResult.With(triviaResult.SemanticDocument), cancellationToken).ConfigureAwait(false); var options = await analyzeResult.SemanticDocument.Document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var generatedCode = await GenerateCodeAsync( insertionPoint.With(expandedDocument), OriginalSelectionResult.With(expandedDocument), analyzeResult.With(expandedDocument), options, cancellationToken).ConfigureAwait(false); var applied = await triviaResult.ApplyAsync(generatedCode, cancellationToken).ConfigureAwait(false); var afterTriviaRestored = applied.With(operationStatus); cancellationToken.ThrowIfCancellationRequested(); if (afterTriviaRestored.Status.FailedWithNoBestEffortSuggestion()) { return await CreateExtractMethodResultAsync( operationStatus, generatedCode.SemanticDocument, generatedCode.MethodNameAnnotation, generatedCode.MethodDefinitionAnnotation, cancellationToken).ConfigureAwait(false); } var finalDocument = afterTriviaRestored.Data.Document; finalDocument = await Formatter.FormatAsync( finalDocument, Formatter.Annotation, options: null, rules: GetFormattingRules(finalDocument), cancellationToken: cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); return await CreateExtractMethodResultAsync( operationStatus.With(generatedCode.Status), await SemanticDocument.CreateAsync(finalDocument, cancellationToken).ConfigureAwait(false), generatedCode.MethodNameAnnotation, generatedCode.MethodDefinitionAnnotation, cancellationToken).ConfigureAwait(false); } private async Task<ExtractMethodResult> CreateExtractMethodResultAsync( OperationStatus status, SemanticDocument semanticDocument, SyntaxAnnotation invocationAnnotation, SyntaxAnnotation methodAnnotation, CancellationToken cancellationToken) { var newRoot = semanticDocument.Root; var methodName = GetMethodNameAtInvocation(newRoot.GetAnnotatedNodesAndTokens(invocationAnnotation)); var methodDefinition = newRoot.GetAnnotatedNodesAndTokens(methodAnnotation).FirstOrDefault().AsNode(); if (LocalFunction && status.Succeeded()) { var result = await InsertNewLineBeforeLocalFunctionIfNecessaryAsync(semanticDocument.Document, methodName, methodDefinition, cancellationToken).ConfigureAwait(false); return new SimpleExtractMethodResult(status, result.document, result.methodName, result.methodDefinition); } return new SimpleExtractMethodResult(status, semanticDocument.Document, methodName, methodDefinition); } private async Task<OperationStatus> CheckVariableTypesAsync( OperationStatus status, AnalyzerResult analyzeResult, CancellationToken cancellationToken) { var document = analyzeResult.SemanticDocument; // sync selection result to same semantic data as analyzeResult var firstToken = OriginalSelectionResult.With(document).GetFirstTokenInSelection(); var context = firstToken.Parent; var result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), status, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.MethodParameters, result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToMoveOutToCallSite(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { result = await TryCheckVariableTypeAsync(document, context, analyzeResult.GetVariablesToSplitOrMoveOutToCallSite(cancellationToken), result.Item2, cancellationToken).ConfigureAwait(false); if (!result.Item1) { return result.Item2; } } } } } status = result.Item2; var checkedStatus = await CheckTypeAsync(document.Document, context, context.GetLocation(), analyzeResult.ReturnType, cancellationToken).ConfigureAwait(false); return checkedStatus.With(status); } private async Task<Tuple<bool, OperationStatus>> TryCheckVariableTypeAsync( SemanticDocument document, SyntaxNode contextNode, IEnumerable<VariableInfo> variables, OperationStatus status, CancellationToken cancellationToken) { if (status.FailedWithNoBestEffortSuggestion()) { return Tuple.Create(false, status); } var location = contextNode.GetLocation(); foreach (var variable in variables) { var originalType = variable.GetVariableType(document); var result = await CheckTypeAsync(document.Document, contextNode, location, originalType, cancellationToken).ConfigureAwait(false); if (result.FailedWithNoBestEffortSuggestion()) { status = status.With(result); return Tuple.Create(false, status); } } return Tuple.Create(true, status); } internal static string MakeMethodName(string prefix, string originalName, bool camelCase) { var startingWithLetter = originalName.ToCharArray().SkipWhile(c => !char.IsLetter(c)).ToArray(); var name = startingWithLetter.Length == 0 ? originalName : new string(startingWithLetter); if (camelCase && !prefix.IsEmpty()) { prefix = char.ToLowerInvariant(prefix[0]) + prefix[1..]; } return char.IsUpper(name[0]) ? prefix + name : prefix + char.ToUpper(name[0]).ToString() + name[1..]; } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.Reverse.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.Reverse.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse(int listLength) { SegmentedList<T> list = GenericListFactory(listLength); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(); for (int i = 0; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[listBefore.Count - (i + 1)]); //"Expect them to be the same." } } [Theory] [InlineData(10, 0, 10)] [InlineData(10, 3, 3)] [InlineData(10, 10, 0)] [InlineData(10, 5, 5)] [InlineData(10, 0, 5)] [InlineData(10, 1, 9)] [InlineData(10, 9, 1)] [InlineData(10, 2, 8)] [InlineData(10, 8, 2)] public void Reverse_int_int(int listLength, int index, int count) { SegmentedList<T> list = GenericListFactory(listLength); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(index, count); for (int i = 0; i < index; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } int j = 0; for (int i = index; i < index + count; i++) { Assert.Equal(list[i], listBefore[index + count - (j + 1)]); //"Expect them to be the same." j++; } for (int i = index + count; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } } [Theory] [InlineData(10, 3, 3)] [InlineData(10, 0, 10)] [InlineData(10, 10, 0)] [InlineData(10, 5, 5)] [InlineData(10, 0, 5)] [InlineData(10, 1, 9)] [InlineData(10, 9, 1)] [InlineData(10, 2, 8)] [InlineData(10, 8, 2)] public void Reverse_RepeatedValues(int listLength, int index, int count) { SegmentedList<T> list = GenericListFactory(1); for (int i = 1; i < listLength; i++) list.Add(list[0]); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(index, count); for (int i = 0; i < index; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } int j = 0; for (int i = index; i < index + count; i++) { Assert.Equal(list[i], listBefore[index + count - (j + 1)]); //"Expect them to be the same." j++; } for (int i = index + count; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse_InvalidParameters(int listLength) { if (listLength % 2 != 0) listLength++; SegmentedList<T> list = GenericListFactory(listLength); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(listLength ,1 ), Tuple.Create(listLength+1 ,0 ), Tuple.Create(listLength+1 ,1 ), Tuple.Create(listLength ,2 ), Tuple.Create(listLength/2 ,listLength/2+1), Tuple.Create(listLength-1 ,2 ), Tuple.Create(listLength-2 ,3 ), Tuple.Create(1 ,listLength ), Tuple.Create(0 ,listLength+1 ), Tuple.Create(1 ,listLength+1 ), Tuple.Create(2 ,listLength ), Tuple.Create(listLength/2+1 ,listLength/2 ), Tuple.Create(2 ,listLength-1 ), Tuple.Create(3 ,listLength-2 ), }; Assert.All(InvalidParameters, invalidSet => { if (invalidSet.Item1 >= 0 && invalidSet.Item2 >= 0) Assert.Throws<ArgumentException>(null, () => list.Reverse(invalidSet.Item1, invalidSet.Item2)); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse_NegativeParameters(int listLength) { if (listLength % 2 != 0) listLength++; SegmentedList<T> list = GenericListFactory(listLength); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(-1,-1), Tuple.Create(-1, 0), Tuple.Create(-1, 1), Tuple.Create(-1, 2), Tuple.Create(0 ,-1), Tuple.Create(1 ,-1), Tuple.Create(2 ,-1), }; Assert.All(InvalidParameters, invalidSet => { Assert.Throws<ArgumentOutOfRangeException>(() => list.Reverse(invalidSet.Item1, invalidSet.Item2)); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.Reverse.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse(int listLength) { SegmentedList<T> list = GenericListFactory(listLength); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(); for (int i = 0; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[listBefore.Count - (i + 1)]); //"Expect them to be the same." } } [Theory] [InlineData(10, 0, 10)] [InlineData(10, 3, 3)] [InlineData(10, 10, 0)] [InlineData(10, 5, 5)] [InlineData(10, 0, 5)] [InlineData(10, 1, 9)] [InlineData(10, 9, 1)] [InlineData(10, 2, 8)] [InlineData(10, 8, 2)] public void Reverse_int_int(int listLength, int index, int count) { SegmentedList<T> list = GenericListFactory(listLength); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(index, count); for (int i = 0; i < index; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } int j = 0; for (int i = index; i < index + count; i++) { Assert.Equal(list[i], listBefore[index + count - (j + 1)]); //"Expect them to be the same." j++; } for (int i = index + count; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } } [Theory] [InlineData(10, 3, 3)] [InlineData(10, 0, 10)] [InlineData(10, 10, 0)] [InlineData(10, 5, 5)] [InlineData(10, 0, 5)] [InlineData(10, 1, 9)] [InlineData(10, 9, 1)] [InlineData(10, 2, 8)] [InlineData(10, 8, 2)] public void Reverse_RepeatedValues(int listLength, int index, int count) { SegmentedList<T> list = GenericListFactory(1); for (int i = 1; i < listLength; i++) list.Add(list[0]); SegmentedList<T> listBefore = list.ToSegmentedList(); list.Reverse(index, count); for (int i = 0; i < index; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } int j = 0; for (int i = index; i < index + count; i++) { Assert.Equal(list[i], listBefore[index + count - (j + 1)]); //"Expect them to be the same." j++; } for (int i = index + count; i < listBefore.Count; i++) { Assert.Equal(list[i], listBefore[i]); //"Expect them to be the same." } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse_InvalidParameters(int listLength) { if (listLength % 2 != 0) listLength++; SegmentedList<T> list = GenericListFactory(listLength); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(listLength ,1 ), Tuple.Create(listLength+1 ,0 ), Tuple.Create(listLength+1 ,1 ), Tuple.Create(listLength ,2 ), Tuple.Create(listLength/2 ,listLength/2+1), Tuple.Create(listLength-1 ,2 ), Tuple.Create(listLength-2 ,3 ), Tuple.Create(1 ,listLength ), Tuple.Create(0 ,listLength+1 ), Tuple.Create(1 ,listLength+1 ), Tuple.Create(2 ,listLength ), Tuple.Create(listLength/2+1 ,listLength/2 ), Tuple.Create(2 ,listLength-1 ), Tuple.Create(3 ,listLength-2 ), }; Assert.All(InvalidParameters, invalidSet => { if (invalidSet.Item1 >= 0 && invalidSet.Item2 >= 0) Assert.Throws<ArgumentException>(null, () => list.Reverse(invalidSet.Item1, invalidSet.Item2)); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Reverse_NegativeParameters(int listLength) { if (listLength % 2 != 0) listLength++; SegmentedList<T> list = GenericListFactory(listLength); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(-1,-1), Tuple.Create(-1, 0), Tuple.Create(-1, 1), Tuple.Create(-1, 2), Tuple.Create(0 ,-1), Tuple.Create(1 ,-1), Tuple.Create(2 ,-1), }; Assert.All(InvalidParameters, invalidSet => { Assert.Throws<ArgumentOutOfRangeException>(() => list.Reverse(invalidSet.Item1, invalidSet.Item2)); }); } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Dependencies/PooledObjects/PooledDictionary.cs
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.PooledObjects { // Dictionary that can be recycled via an object pool // NOTE: these dictionaries always have the default comparer. internal sealed partial class PooledDictionary<K, V> : Dictionary<K, V> where K : notnull { private readonly ObjectPool<PooledDictionary<K, V>> _pool; private PooledDictionary(ObjectPool<PooledDictionary<K, V>> pool, IEqualityComparer<K> keyComparer) : base(keyComparer) { _pool = pool; } public ImmutableDictionary<K, V> ToImmutableDictionaryAndFree() { var result = this.ToImmutableDictionary(this.Comparer); this.Free(); return result; } public ImmutableDictionary<K, V> ToImmutableDictionary() => this.ToImmutableDictionary(this.Comparer); public void Free() { this.Clear(); _pool?.Free(this); } // global pool private static readonly ObjectPool<PooledDictionary<K, V>> s_poolInstance = CreatePool(EqualityComparer<K>.Default); // if someone needs to create a pool; public static ObjectPool<PooledDictionary<K, V>> CreatePool(IEqualityComparer<K> keyComparer) { ObjectPool<PooledDictionary<K, V>>? pool = null; pool = new ObjectPool<PooledDictionary<K, V>>(() => new PooledDictionary<K, V>(pool!, keyComparer), 128); return pool; } public static PooledDictionary<K, V> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.PooledObjects { // Dictionary that can be recycled via an object pool // NOTE: these dictionaries always have the default comparer. internal sealed partial class PooledDictionary<K, V> : Dictionary<K, V> where K : notnull { private readonly ObjectPool<PooledDictionary<K, V>> _pool; private PooledDictionary(ObjectPool<PooledDictionary<K, V>> pool, IEqualityComparer<K> keyComparer) : base(keyComparer) { _pool = pool; } public ImmutableDictionary<K, V> ToImmutableDictionaryAndFree() { var result = this.ToImmutableDictionary(this.Comparer); this.Free(); return result; } public ImmutableDictionary<K, V> ToImmutableDictionary() => this.ToImmutableDictionary(this.Comparer); public void Free() { this.Clear(); _pool?.Free(this); } // global pool private static readonly ObjectPool<PooledDictionary<K, V>> s_poolInstance = CreatePool(EqualityComparer<K>.Default); // if someone needs to create a pool; public static ObjectPool<PooledDictionary<K, V>> CreatePool(IEqualityComparer<K> keyComparer) { ObjectPool<PooledDictionary<K, V>>? pool = null; pool = new ObjectPool<PooledDictionary<K, V>>(() => new PooledDictionary<K, V>(pool!, keyComparer), 128); return pool; } public static PooledDictionary<K, V> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Features/CSharp/Portable/Completion/Providers/ContextVariableArgumentProvider.cs
// Licensed to the .NET Foundation under one or more 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.Completion; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportArgumentProvider(nameof(ContextVariableArgumentProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(FirstBuiltInArgumentProvider))] [Shared] internal sealed class ContextVariableArgumentProvider : AbstractContextVariableArgumentProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ContextVariableArgumentProvider() { } } }
// Licensed to the .NET Foundation under one or more 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.Completion; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportArgumentProvider(nameof(ContextVariableArgumentProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(FirstBuiltInArgumentProvider))] [Shared] internal sealed class ContextVariableArgumentProvider : AbstractContextVariableArgumentProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ContextVariableArgumentProvider() { } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Workspaces/Core/Portable/Options/Option`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Options { /// <inheritdoc cref="Option2{T}"/> public class Option<T> : ILanguageSpecificOption<T> { private readonly OptionDefinition _optionDefinition; /// <inheritdoc cref="OptionDefinition.Feature"/> public string Feature => _optionDefinition.Feature; /// <inheritdoc cref="OptionDefinition.Group"/> internal OptionGroup Group => _optionDefinition.Group; /// <inheritdoc cref="OptionDefinition.Name"/> public string Name => _optionDefinition.Name; /// <inheritdoc cref="OptionDefinition.DefaultValue"/> public T DefaultValue => (T)_optionDefinition.DefaultValue!; /// <inheritdoc cref="OptionDefinition.Type"/> public Type Type => _optionDefinition.Type; /// <inheritdoc cref="Option2{T}.StorageLocations"/> public ImmutableArray<OptionStorageLocation> StorageLocations { get; } [Obsolete("Use a constructor that specifies an explicit default value.")] public Option(string feature, string name) : this(feature, name, default!) { // This constructor forwards to the next one; it exists to maintain source-level compatibility with older callers. } public Option(string feature, string name, T defaultValue) : this(feature, name, defaultValue, storageLocations: Array.Empty<OptionStorageLocation>()) { } public Option(string feature, string name, T defaultValue, params OptionStorageLocation[] storageLocations) : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations) { } internal Option(string feature, OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) : this(feature, group, name, defaultValue, storageLocations.ToImmutableArray()) { } internal Option(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray<OptionStorageLocation> storageLocations) : this(new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: false), storageLocations) { } internal Option(OptionDefinition optionDefinition, ImmutableArray<OptionStorageLocation> storageLocations) { _optionDefinition = optionDefinition; this.StorageLocations = storageLocations; } OptionGroup IOptionWithGroup.Group => this.Group; object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => false; OptionDefinition IOption2.OptionDefinition => _optionDefinition; bool IEquatable<IOption2?>.Equals(IOption2? other) => Equals(other); public override string ToString() => _optionDefinition.ToString(); public override int GetHashCode() => _optionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); private bool Equals(IOption2? other) { if (ReferenceEquals(this, other)) { return true; } return _optionDefinition == other?.OptionDefinition; } public static implicit operator OptionKey(Option<T> option) => new(option); } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Options { /// <inheritdoc cref="Option2{T}"/> public class Option<T> : ILanguageSpecificOption<T> { private readonly OptionDefinition _optionDefinition; /// <inheritdoc cref="OptionDefinition.Feature"/> public string Feature => _optionDefinition.Feature; /// <inheritdoc cref="OptionDefinition.Group"/> internal OptionGroup Group => _optionDefinition.Group; /// <inheritdoc cref="OptionDefinition.Name"/> public string Name => _optionDefinition.Name; /// <inheritdoc cref="OptionDefinition.DefaultValue"/> public T DefaultValue => (T)_optionDefinition.DefaultValue!; /// <inheritdoc cref="OptionDefinition.Type"/> public Type Type => _optionDefinition.Type; /// <inheritdoc cref="Option2{T}.StorageLocations"/> public ImmutableArray<OptionStorageLocation> StorageLocations { get; } [Obsolete("Use a constructor that specifies an explicit default value.")] public Option(string feature, string name) : this(feature, name, default!) { // This constructor forwards to the next one; it exists to maintain source-level compatibility with older callers. } public Option(string feature, string name, T defaultValue) : this(feature, name, defaultValue, storageLocations: Array.Empty<OptionStorageLocation>()) { } public Option(string feature, string name, T defaultValue, params OptionStorageLocation[] storageLocations) : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations) { } internal Option(string feature, OptionGroup group, string name, T defaultValue, params OptionStorageLocation[] storageLocations) : this(feature, group, name, defaultValue, storageLocations.ToImmutableArray()) { } internal Option(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray<OptionStorageLocation> storageLocations) : this(new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: false), storageLocations) { } internal Option(OptionDefinition optionDefinition, ImmutableArray<OptionStorageLocation> storageLocations) { _optionDefinition = optionDefinition; this.StorageLocations = storageLocations; } OptionGroup IOptionWithGroup.Group => this.Group; object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => false; OptionDefinition IOption2.OptionDefinition => _optionDefinition; bool IEquatable<IOption2?>.Equals(IOption2? other) => Equals(other); public override string ToString() => _optionDefinition.ToString(); public override int GetHashCode() => _optionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); private bool Equals(IOption2? other) { if (ReferenceEquals(this, other)) { return true; } return _optionDefinition == other?.OptionDefinition; } public static implicit operator OptionKey(Option<T> option) => new(option); } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/Server/VBCSCompiler/DiagnosticListener.cs
// Licensed to the .NET Foundation under one or more 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.IO.Pipes; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer { internal interface IDiagnosticListener { /// <summary> /// Called when the server updates the keep alive value. /// </summary> void UpdateKeepAlive(TimeSpan keepAlive); /// <summary> /// Called when a connection to the server occurs. /// </summary> void ConnectionReceived(); /// <summary> /// Called when a connection has finished processing. /// </summary> void ConnectionCompleted(CompletionData completionData); /// <summary> /// Called when the server is shutting down because the keep alive timeout was reached. /// </summary> void KeepAliveReached(); } internal sealed class EmptyDiagnosticListener : IDiagnosticListener { public void UpdateKeepAlive(TimeSpan keepAlive) { } public void ConnectionReceived() { } public void ConnectionCompleted(CompletionData completionData) { } public void KeepAliveReached() { } } }
// Licensed to the .NET Foundation under one or more 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.IO.Pipes; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CompilerServer { internal interface IDiagnosticListener { /// <summary> /// Called when the server updates the keep alive value. /// </summary> void UpdateKeepAlive(TimeSpan keepAlive); /// <summary> /// Called when a connection to the server occurs. /// </summary> void ConnectionReceived(); /// <summary> /// Called when a connection has finished processing. /// </summary> void ConnectionCompleted(CompletionData completionData); /// <summary> /// Called when the server is shutting down because the keep alive timeout was reached. /// </summary> void KeepAliveReached(); } internal sealed class EmptyDiagnosticListener : IDiagnosticListener { public void UpdateKeepAlive(TimeSpan keepAlive) { } public void ConnectionReceived() { } public void ConnectionCompleted(CompletionData completionData) { } public void KeepAliveReached() { } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Workspaces/Core/Portable/CodeGeneration/AbstractFlagsEnumGenerator.cs
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class AbstractFlagsEnumGenerator : IComparer<(IFieldSymbol field, ulong value)> { protected abstract SyntaxGenerator GetSyntaxGenerator(); protected abstract SyntaxNode CreateExplicitlyCastedLiteralValue(INamedTypeSymbol enumType, SpecialType underlyingSpecialType, object? constantValue); protected abstract bool IsValidName(INamedTypeSymbol enumType, string name); public SyntaxNode? TryCreateEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { // Code copied from System.Enum. var isFlagsEnum = IsFlagsEnum(enumType); if (isFlagsEnum) { return CreateFlagsEnumConstantValue(enumType, constantValue); } else { // Try to see if its one of the enum values. If so, add that. Otherwise, just add // the literal value of the enum. return CreateNonFlagsEnumConstantValue(enumType, constantValue); } } private static bool IsFlagsEnum(INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeKind != TypeKind.Enum) { return false; } foreach (var attribute in typeSymbol.GetAttributes()) { var ctor = attribute.AttributeConstructor; if (ctor != null) { var type = ctor.ContainingType; if (!ctor.Parameters.Any() && type.Name == "FlagsAttribute") { var containingSymbol = type.ContainingSymbol; if (containingSymbol.Kind == SymbolKind.Namespace && containingSymbol.Name == "System" && ((INamespaceSymbol)containingSymbol.ContainingSymbol).IsGlobalNamespace) { return true; } } } } return false; } private SyntaxNode? CreateFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { // These values are sorted by value. Don't change this. var allFieldsAndValues = new List<(IFieldSymbol field, ulong value)>(); GetSortedEnumFieldsAndValues(enumType, allFieldsAndValues); var usedFieldsAndValues = new List<(IFieldSymbol field, ulong value)>(); return CreateFlagsEnumConstantValue(enumType, constantValue, allFieldsAndValues, usedFieldsAndValues); } private SyntaxNode? CreateFlagsEnumConstantValue( INamedTypeSymbol enumType, object constantValue, List<(IFieldSymbol field, ulong value)> allFieldsAndValues, List<(IFieldSymbol field, ulong value)> usedFieldsAndValues) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); var result = constantValueULong; // We will not optimize this code further to keep it maintainable. There are some // boundary checks that can be applied to minimize the comparisons required. This code // works the same for the best/worst case. In general the number of items in an enum are // sufficiently small and not worth the optimization. for (var index = allFieldsAndValues.Count - 1; index >= 0 && result != 0; index--) { var fieldAndValue = allFieldsAndValues[index]; var valueAtIndex = fieldAndValue.value; if (valueAtIndex != 0 && (result & valueAtIndex) == valueAtIndex) { result -= valueAtIndex; usedFieldsAndValues.Add(fieldAndValue); } } var syntaxFactory = GetSyntaxGenerator(); // We were able to represent this number as a bitwise OR of valid flags. if (result == 0 && usedFieldsAndValues.Count > 0) { // We want to emit the fields in lower to higher value. So we walk backward. SyntaxNode? finalNode = null; for (var i = usedFieldsAndValues.Count - 1; i >= 0; i--) { var field = usedFieldsAndValues[i]; var node = CreateMemberAccessExpression(field.field, enumType, underlyingSpecialType); if (finalNode == null) { finalNode = node; } else { finalNode = syntaxFactory.BitwiseOrExpression(finalNode, node); } } return finalNode; } else { // We couldn't find fields to OR together to make the value. // If we had 0 as the value, and there's an enum value equal to 0, then use that. var zeroField = GetZeroField(allFieldsAndValues); if (constantValueULong == 0 && zeroField != null) { return CreateMemberAccessExpression(zeroField, enumType, underlyingSpecialType); } else { // Add anything else in as a literal value. return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue); } } } private SyntaxNode CreateMemberAccessExpression( IFieldSymbol field, INamedTypeSymbol enumType, SpecialType underlyingSpecialType) { if (IsValidName(enumType, field.Name)) { var syntaxFactory = GetSyntaxGenerator(); return syntaxFactory.MemberAccessExpression( syntaxFactory.TypeExpression(enumType), syntaxFactory.IdentifierName(field.Name)); } else { return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, field.ConstantValue); } } private static IFieldSymbol? GetZeroField(List<(IFieldSymbol field, ulong value)> allFieldsAndValues) { for (var i = allFieldsAndValues.Count - 1; i >= 0; i--) { var (field, value) = allFieldsAndValues[i]; if (value == 0) { return field; } } return null; } private void GetSortedEnumFieldsAndValues( INamedTypeSymbol enumType, List<(IFieldSymbol field, ulong value)> allFieldsAndValues) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; foreach (var field in enumType.GetMembers().OfType<IFieldSymbol>()) { if (field is { HasConstantValue: true, ConstantValue: not null }) { var value = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType); allFieldsAndValues.Add((field, value)); } } allFieldsAndValues.Sort(this); } private SyntaxNode CreateNonFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); // See if there's a member with this value. If so, then use that. foreach (var field in enumType.GetMembers().OfType<IFieldSymbol>()) { if (field is { HasConstantValue: true, ConstantValue: not null }) { var fieldValue = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType); if (constantValueULong == fieldValue) { return CreateMemberAccessExpression(field, enumType, underlyingSpecialType); } } } // Otherwise, just add the enum as a literal. return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue); } int IComparer<(IFieldSymbol field, ulong value)>.Compare((IFieldSymbol field, ulong value) x, (IFieldSymbol field, ulong value) y) { unchecked { return (long)x.value < (long)y.value ? -1 : (long)x.value > (long)y.value ? 1 : -x.field.Name.CompareTo(y.field.Name); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class AbstractFlagsEnumGenerator : IComparer<(IFieldSymbol field, ulong value)> { protected abstract SyntaxGenerator GetSyntaxGenerator(); protected abstract SyntaxNode CreateExplicitlyCastedLiteralValue(INamedTypeSymbol enumType, SpecialType underlyingSpecialType, object? constantValue); protected abstract bool IsValidName(INamedTypeSymbol enumType, string name); public SyntaxNode? TryCreateEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { // Code copied from System.Enum. var isFlagsEnum = IsFlagsEnum(enumType); if (isFlagsEnum) { return CreateFlagsEnumConstantValue(enumType, constantValue); } else { // Try to see if its one of the enum values. If so, add that. Otherwise, just add // the literal value of the enum. return CreateNonFlagsEnumConstantValue(enumType, constantValue); } } private static bool IsFlagsEnum(INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeKind != TypeKind.Enum) { return false; } foreach (var attribute in typeSymbol.GetAttributes()) { var ctor = attribute.AttributeConstructor; if (ctor != null) { var type = ctor.ContainingType; if (!ctor.Parameters.Any() && type.Name == "FlagsAttribute") { var containingSymbol = type.ContainingSymbol; if (containingSymbol.Kind == SymbolKind.Namespace && containingSymbol.Name == "System" && ((INamespaceSymbol)containingSymbol.ContainingSymbol).IsGlobalNamespace) { return true; } } } } return false; } private SyntaxNode? CreateFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { // These values are sorted by value. Don't change this. var allFieldsAndValues = new List<(IFieldSymbol field, ulong value)>(); GetSortedEnumFieldsAndValues(enumType, allFieldsAndValues); var usedFieldsAndValues = new List<(IFieldSymbol field, ulong value)>(); return CreateFlagsEnumConstantValue(enumType, constantValue, allFieldsAndValues, usedFieldsAndValues); } private SyntaxNode? CreateFlagsEnumConstantValue( INamedTypeSymbol enumType, object constantValue, List<(IFieldSymbol field, ulong value)> allFieldsAndValues, List<(IFieldSymbol field, ulong value)> usedFieldsAndValues) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); var result = constantValueULong; // We will not optimize this code further to keep it maintainable. There are some // boundary checks that can be applied to minimize the comparisons required. This code // works the same for the best/worst case. In general the number of items in an enum are // sufficiently small and not worth the optimization. for (var index = allFieldsAndValues.Count - 1; index >= 0 && result != 0; index--) { var fieldAndValue = allFieldsAndValues[index]; var valueAtIndex = fieldAndValue.value; if (valueAtIndex != 0 && (result & valueAtIndex) == valueAtIndex) { result -= valueAtIndex; usedFieldsAndValues.Add(fieldAndValue); } } var syntaxFactory = GetSyntaxGenerator(); // We were able to represent this number as a bitwise OR of valid flags. if (result == 0 && usedFieldsAndValues.Count > 0) { // We want to emit the fields in lower to higher value. So we walk backward. SyntaxNode? finalNode = null; for (var i = usedFieldsAndValues.Count - 1; i >= 0; i--) { var field = usedFieldsAndValues[i]; var node = CreateMemberAccessExpression(field.field, enumType, underlyingSpecialType); if (finalNode == null) { finalNode = node; } else { finalNode = syntaxFactory.BitwiseOrExpression(finalNode, node); } } return finalNode; } else { // We couldn't find fields to OR together to make the value. // If we had 0 as the value, and there's an enum value equal to 0, then use that. var zeroField = GetZeroField(allFieldsAndValues); if (constantValueULong == 0 && zeroField != null) { return CreateMemberAccessExpression(zeroField, enumType, underlyingSpecialType); } else { // Add anything else in as a literal value. return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue); } } } private SyntaxNode CreateMemberAccessExpression( IFieldSymbol field, INamedTypeSymbol enumType, SpecialType underlyingSpecialType) { if (IsValidName(enumType, field.Name)) { var syntaxFactory = GetSyntaxGenerator(); return syntaxFactory.MemberAccessExpression( syntaxFactory.TypeExpression(enumType), syntaxFactory.IdentifierName(field.Name)); } else { return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, field.ConstantValue); } } private static IFieldSymbol? GetZeroField(List<(IFieldSymbol field, ulong value)> allFieldsAndValues) { for (var i = allFieldsAndValues.Count - 1; i >= 0; i--) { var (field, value) = allFieldsAndValues[i]; if (value == 0) { return field; } } return null; } private void GetSortedEnumFieldsAndValues( INamedTypeSymbol enumType, List<(IFieldSymbol field, ulong value)> allFieldsAndValues) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; foreach (var field in enumType.GetMembers().OfType<IFieldSymbol>()) { if (field is { HasConstantValue: true, ConstantValue: not null }) { var value = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType); allFieldsAndValues.Add((field, value)); } } allFieldsAndValues.Sort(this); } private SyntaxNode CreateNonFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); // See if there's a member with this value. If so, then use that. foreach (var field in enumType.GetMembers().OfType<IFieldSymbol>()) { if (field is { HasConstantValue: true, ConstantValue: not null }) { var fieldValue = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType); if (constantValueULong == fieldValue) { return CreateMemberAccessExpression(field, enumType, underlyingSpecialType); } } } // Otherwise, just add the enum as a literal. return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue); } int IComparer<(IFieldSymbol field, ulong value)>.Compare((IFieldSymbol field, ulong value) x, (IFieldSymbol field, ulong value) y) { unchecked { return (long)x.value < (long)y.value ? -1 : (long)x.value > (long)y.value ? 1 : -x.field.Name.CompareTo(y.field.Name); } } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Tools/ExternalAccess/FSharp/Internal/Editor/FSharpBraceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { [ExportBraceMatcher(LanguageNames.FSharp)] internal class FSharpBraceMatcher : IBraceMatcher { private readonly IFSharpBraceMatcher _braceMatcher; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpBraceMatcher(IFSharpBraceMatcher braceMatcher) { _braceMatcher = braceMatcher; } public async Task<Microsoft.CodeAnalysis.Editor.BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken = default) { var result = await _braceMatcher.FindBracesAsync(document, position, cancellationToken).ConfigureAwait(false); if (result.HasValue) { return new Microsoft.CodeAnalysis.Editor.BraceMatchingResult(result.Value.LeftSpan, result.Value.RightSpan); } 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.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { [ExportBraceMatcher(LanguageNames.FSharp)] internal class FSharpBraceMatcher : IBraceMatcher { private readonly IFSharpBraceMatcher _braceMatcher; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpBraceMatcher(IFSharpBraceMatcher braceMatcher) { _braceMatcher = braceMatcher; } public async Task<Microsoft.CodeAnalysis.Editor.BraceMatchingResult?> FindBracesAsync(Document document, int position, CancellationToken cancellationToken = default) { var result = await _braceMatcher.FindBracesAsync(document, position, cancellationToken).ConfigureAwait(false); if (result.HasValue) { return new Microsoft.CodeAnalysis.Editor.BraceMatchingResult(result.Value.LeftSpan, result.Value.RightSpan); } else { return null; } } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/LocalSlotMappingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader.Tools; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class LocalSlotMappingTests : EditAndContinueTestBase { /// <summary> /// If no changes were made we don't produce a syntax map. /// If we don't have syntax map and preserve variables is true we should still successfully map the locals to their previous slots. /// </summary> [Fact] public void SlotMappingWithNoChanges() { var source0 = @" using System; class C { static void Main(string[] args) { var b = true; do { Console.WriteLine(""hi""); } while (b == true); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source0); var v0 = CompileAndVerify(compilation0); var methodData0 = v0.TestData.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); v0.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0, //b bool V_1) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 -IL_0003: nop -IL_0004: ldstr ""hi"" IL_0009: call ""void System.Console.WriteLine(string)"" IL_000e: nop -IL_000f: nop -IL_0010: ldloc.0 IL_0011: stloc.1 ~IL_0012: ldloc.1 IL_0013: brtrue.s IL_0003 -IL_0015: ret }", sequencePoints: "C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, syntaxMap: null, preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0, //b bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: nop IL_0004: ldstr ""hi"" IL_0009: call ""void System.Console.WriteLine(string)"" IL_000e: nop IL_000f: nop IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: brtrue.s IL_0003 IL_0015: ret }"); } [Fact] public void OutOfOrderUserLocals() { var source = WithWindowsLineBreaks(@" using System; public class C { public static void M() { for (int i = 1; i < 1; i++) Console.WriteLine(1); for (int i = 1; i < 2; i++) Console.WriteLine(2); int j; for (j = 1; j < 3; j++) Console.WriteLine(3); } }"); var compilation0 = CreateCompilation(source, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 75 (0x4b) .maxstack 2 .locals init (int V_0, //j int V_1, //i bool V_2, int V_3, //i bool V_4, bool V_5) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: br.s IL_0010 IL_0005: ldc.i4.1 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: ldloc.1 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.1 IL_0012: clt IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: brtrue.s IL_0005 IL_0018: ldc.i4.1 IL_0019: stloc.3 IL_001a: br.s IL_0027 IL_001c: ldc.i4.2 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: ldloc.3 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.3 IL_0027: ldloc.3 IL_0028: ldc.i4.2 IL_0029: clt IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brtrue.s IL_001c IL_0031: ldc.i4.1 IL_0032: stloc.0 IL_0033: br.s IL_0040 IL_0035: ldc.i4.3 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldc.i4.1 IL_003e: add IL_003f: stloc.0 IL_0040: ldloc.0 IL_0041: ldc.i4.3 IL_0042: clt IL_0044: stloc.s V_5 IL_0046: ldloc.s V_5 IL_0048: brtrue.s IL_0035 IL_004a: ret } "); v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""135"" /> <slot kind=""0"" offset=""20"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""0"" offset=""79"" /> <slot kind=""1"" offset=""70"" /> <slot kind=""1"" offset=""147"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""14"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""58"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""32"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x10"" startLine=""8"" startColumn=""25"" endLine=""8"" endColumn=""30"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""37"" endLine=""9"" endColumn=""58"" document=""1"" /> <entry offset=""0x23"" startLine=""9"" startColumn=""32"" endLine=""9"" endColumn=""35"" document=""1"" /> <entry offset=""0x27"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x2d"" hidden=""true"" document=""1"" /> <entry offset=""0x31"" startLine=""12"" startColumn=""14"" endLine=""12"" endColumn=""19"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" startLine=""12"" startColumn=""33"" endLine=""12"" endColumn=""54"" document=""1"" /> <entry offset=""0x3c"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""31"" document=""1"" /> <entry offset=""0x40"" startLine=""12"" startColumn=""21"" endLine=""12"" endColumn=""26"" document=""1"" /> <entry offset=""0x46"" hidden=""true"" document=""1"" /> <entry offset=""0x4a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4b""> <namespace name=""System"" /> <local name=""j"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" /> <scope startOffset=""0x1"" endOffset=""0x18""> <local name=""i"" il_index=""1"" il_start=""0x1"" il_end=""0x18"" attributes=""0"" /> </scope> <scope startOffset=""0x18"" endOffset=""0x31""> <local name=""i"" il_index=""3"" il_start=""0x18"" il_end=""0x31"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); var symReader = v0.CreateSymReader(); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), symReader.GetEncMethodDebugInfo); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // check that all user-defined and long-lived synthesized local slots are reused diff1.VerifyIL("C.M", @" { // Code size 75 (0x4b) .maxstack 2 .locals init (int V_0, //j int V_1, //i bool V_2, int V_3, //i bool V_4, bool V_5) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: br.s IL_0010 IL_0005: ldc.i4.1 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: ldloc.1 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.1 IL_0012: clt IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: brtrue.s IL_0005 IL_0018: ldc.i4.1 IL_0019: stloc.3 IL_001a: br.s IL_0027 IL_001c: ldc.i4.2 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: ldloc.3 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.3 IL_0027: ldloc.3 IL_0028: ldc.i4.2 IL_0029: clt IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brtrue.s IL_001c IL_0031: ldc.i4.1 IL_0032: stloc.0 IL_0033: br.s IL_0040 IL_0035: ldc.i4.3 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldc.i4.1 IL_003e: add IL_003f: stloc.0 IL_0040: ldloc.0 IL_0041: ldc.i4.3 IL_0042: clt IL_0044: stloc.s V_5 IL_0046: ldloc.s V_5 IL_0048: brtrue.s IL_0035 IL_004a: ret } "); } /// <summary> /// Enc debug info is only present in debug builds. /// </summary> [Fact] public void DebugOnly() { var source = WithWindowsLineBreaks( @"class C { static System.IDisposable F() { return null; } static void M() { lock (F()) { } using (F()) { } } }"); var debug = CreateCompilation(source, options: TestOptions.DebugDll); var release = CreateCompilation(source, options: TestOptions.ReleaseDll); CompileAndVerify(debug).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""3"" offset=""11"" /> <slot kind=""2"" offset=""11"" /> <slot kind=""4"" offset=""35"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""21"" document=""1"" /> <entry offset=""0x13"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x20"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x27"" startLine=""10"" startColumn=""21"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0x28"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); CompileAndVerify(release).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x10"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x22"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x2d"" hidden=""true"" document=""1"" /> <entry offset=""0x2e"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void Using() { var source = WithWindowsLineBreaks( @"class C : System.IDisposable { public void Dispose() { } static System.IDisposable F() { return new C(); } static void M() { using (F()) { using (var u = F()) { } using (F()) { } } } }"); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), m => methodData0.GetEncDebugInfo()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 65 (0x41) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1, //u System.IDisposable V_2) IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: call ""System.IDisposable C.F()"" IL_000d: stloc.1 .try { IL_000e: nop IL_000f: nop IL_0010: leave.s IL_001d } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001c IL_0015: ldloc.1 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } IL_001d: call ""System.IDisposable C.F()"" IL_0022: stloc.2 .try { IL_0023: nop IL_0024: nop IL_0025: leave.s IL_0032 } finally { IL_0027: ldloc.2 IL_0028: brfalse.s IL_0031 IL_002a: ldloc.2 IL_002b: callvirt ""void System.IDisposable.Dispose()"" IL_0030: nop IL_0031: endfinally } IL_0032: nop IL_0033: leave.s IL_0040 } finally { IL_0035: ldloc.0 IL_0036: brfalse.s IL_003f IL_0038: ldloc.0 IL_0039: callvirt ""void System.IDisposable.Dispose()"" IL_003e: nop IL_003f: endfinally } IL_0040: ret }"); } [Fact] public void Lock() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { lock (F()) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 66 (0x42) .maxstack 2 .locals init (object V_0, bool V_1, object V_2, bool V_3) -IL_0000: nop -IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop -IL_0012: nop -IL_0013: call ""object C.F()"" IL_0018: stloc.2 IL_0019: ldc.i4.0 IL_001a: stloc.3 .try { IL_001b: ldloc.2 IL_001c: ldloca.s V_3 IL_001e: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0023: nop -IL_0024: nop -IL_0025: nop IL_0026: leave.s IL_0033 } finally { ~IL_0028: ldloc.3 IL_0029: brfalse.s IL_0032 IL_002b: ldloc.2 IL_002c: call ""void System.Threading.Monitor.Exit(object)"" IL_0031: nop ~IL_0032: endfinally } -IL_0033: nop IL_0034: leave.s IL_0041 } finally { ~IL_0036: ldloc.1 IL_0037: brfalse.s IL_0040 IL_0039: ldloc.0 IL_003a: call ""void System.Threading.Monitor.Exit(object)"" IL_003f: nop ~IL_0040: endfinally } -IL_0041: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Using Monitor.Enter(object). /// </summary> [Fact] public void Lock_Pre40() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { } } }"; var compilation0 = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { MscorlibRef_v20 }); var compilation1 = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { MscorlibRef_v20 }); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 27 (0x1b) .maxstack 1 .locals init (object V_0) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void System.Threading.Monitor.Enter(object)"" IL_000d: nop .try { IL_000e: nop IL_000f: nop IL_0010: leave.s IL_001a } finally { IL_0012: ldloc.0 IL_0013: call ""void System.Threading.Monitor.Exit(object)"" IL_0018: nop IL_0019: endfinally } IL_001a: ret }"); } [Fact] public void Fixed() { var source = @"class C { unsafe static void M(string s, int[] i) { fixed (char *p = s) { fixed (int *q = i) { } fixed (char *r = s) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 81 (0x51) .maxstack 2 .locals init (char* V_0, //p pinned string V_1, int* V_2, //q [unchanged] V_3, char* V_4, //r pinned string V_5, pinned int[] V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: conv.u IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0011 IL_0009: ldloc.0 IL_000a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_000f: add IL_0010: stloc.0 IL_0011: nop IL_0012: ldarg.1 IL_0013: dup IL_0014: stloc.s V_6 IL_0016: brfalse.s IL_001e IL_0018: ldloc.s V_6 IL_001a: ldlen IL_001b: conv.i4 IL_001c: brtrue.s IL_0023 IL_001e: ldc.i4.0 IL_001f: conv.u IL_0020: stloc.2 IL_0021: br.s IL_002d IL_0023: ldloc.s V_6 IL_0025: ldc.i4.0 IL_0026: ldelema ""int"" IL_002b: conv.u IL_002c: stloc.2 IL_002d: nop IL_002e: nop IL_002f: ldnull IL_0030: stloc.s V_6 IL_0032: ldarg.0 IL_0033: stloc.s V_5 IL_0035: ldloc.s V_5 IL_0037: conv.u IL_0038: stloc.s V_4 IL_003a: ldloc.s V_4 IL_003c: brfalse.s IL_0048 IL_003e: ldloc.s V_4 IL_0040: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_0045: add IL_0046: stloc.s V_4 IL_0048: nop IL_0049: nop IL_004a: ldnull IL_004b: stloc.s V_5 IL_004d: nop IL_004e: ldnull IL_004f: stloc.1 IL_0050: ret }"); } [WorkItem(770053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770053")] [Fact] public void FixedMultiple() { var source = @"class C { unsafe static void M(string s1, string s2, string s3, string s4) { fixed (char* p1 = s1, p2 = s2) { *p1 = *p2; } fixed (char* p1 = s1, p3 = s3, p2 = s4) { *p1 = *p2; *p2 = *p3; fixed (char *p4 = s2) { *p3 = *p4; } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 166 (0xa6) .maxstack 2 .locals init (char* V_0, //p1 char* V_1, //p2 pinned string V_2, pinned string V_3, char* V_4, //p1 char* V_5, //p3 char* V_6, //p2 pinned string V_7, pinned string V_8, pinned string V_9, char* V_10, //p4 pinned string V_11) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: conv.u IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0011 IL_0009: ldloc.0 IL_000a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_000f: add IL_0010: stloc.0 IL_0011: ldarg.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: conv.u IL_0015: stloc.1 IL_0016: ldloc.1 IL_0017: brfalse.s IL_0021 IL_0019: ldloc.1 IL_001a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_001f: add IL_0020: stloc.1 IL_0021: nop IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: ldind.u2 IL_0025: stind.i2 IL_0026: nop IL_0027: ldnull IL_0028: stloc.2 IL_0029: ldnull IL_002a: stloc.3 IL_002b: ldarg.0 IL_002c: stloc.s V_7 IL_002e: ldloc.s V_7 IL_0030: conv.u IL_0031: stloc.s V_4 IL_0033: ldloc.s V_4 IL_0035: brfalse.s IL_0041 IL_0037: ldloc.s V_4 IL_0039: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_003e: add IL_003f: stloc.s V_4 IL_0041: ldarg.2 IL_0042: stloc.s V_8 IL_0044: ldloc.s V_8 IL_0046: conv.u IL_0047: stloc.s V_5 IL_0049: ldloc.s V_5 IL_004b: brfalse.s IL_0057 IL_004d: ldloc.s V_5 IL_004f: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_0054: add IL_0055: stloc.s V_5 IL_0057: ldarg.3 IL_0058: stloc.s V_9 IL_005a: ldloc.s V_9 IL_005c: conv.u IL_005d: stloc.s V_6 IL_005f: ldloc.s V_6 IL_0061: brfalse.s IL_006d IL_0063: ldloc.s V_6 IL_0065: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_006a: add IL_006b: stloc.s V_6 IL_006d: nop IL_006e: ldloc.s V_4 IL_0070: ldloc.s V_6 IL_0072: ldind.u2 IL_0073: stind.i2 IL_0074: ldloc.s V_6 IL_0076: ldloc.s V_5 IL_0078: ldind.u2 IL_0079: stind.i2 IL_007a: ldarg.1 IL_007b: stloc.s V_11 IL_007d: ldloc.s V_11 IL_007f: conv.u IL_0080: stloc.s V_10 IL_0082: ldloc.s V_10 IL_0084: brfalse.s IL_0090 IL_0086: ldloc.s V_10 IL_0088: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_008d: add IL_008e: stloc.s V_10 IL_0090: nop IL_0091: ldloc.s V_5 IL_0093: ldloc.s V_10 IL_0095: ldind.u2 IL_0096: stind.i2 IL_0097: nop IL_0098: ldnull IL_0099: stloc.s V_11 IL_009b: nop IL_009c: ldnull IL_009d: stloc.s V_7 IL_009f: ldnull IL_00a0: stloc.s V_8 IL_00a2: ldnull IL_00a3: stloc.s V_9 IL_00a5: ret } "); } [Fact] public void ForEach() { var source = @"using System.Collections; using System.Collections.Generic; class C { static IEnumerable F1() { return null; } static List<object> F2() { return null; } static IEnumerable F3() { return null; } static List<object> F4() { return null; } static void M() { foreach (var @x in F1()) { foreach (object y in F2()) { } } foreach (var x in F4()) { foreach (var y in F3()) { } foreach (var z in F2()) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 272 (0x110) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, object V_1, //x System.Collections.Generic.List<object>.Enumerator V_2, object V_3, //y [unchanged] V_4, System.Collections.Generic.List<object>.Enumerator V_5, object V_6, //x System.Collections.IEnumerator V_7, object V_8, //y System.Collections.Generic.List<object>.Enumerator V_9, object V_10, //z System.IDisposable V_11) IL_0000: nop IL_0001: nop IL_0002: call ""System.Collections.IEnumerable C.F1()"" IL_0007: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_000c: stloc.0 .try { IL_000d: br.s IL_004a IL_000f: ldloc.0 IL_0010: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0015: stloc.1 IL_0016: nop IL_0017: nop IL_0018: call ""System.Collections.Generic.List<object> C.F2()"" IL_001d: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_0022: stloc.2 .try { IL_0023: br.s IL_002f IL_0025: ldloca.s V_2 IL_0027: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_002c: stloc.3 IL_002d: nop IL_002e: nop IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_0036: brtrue.s IL_0025 IL_0038: leave.s IL_0049 } finally { IL_003a: ldloca.s V_2 IL_003c: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_0042: callvirt ""void System.IDisposable.Dispose()"" IL_0047: nop IL_0048: endfinally } IL_0049: nop IL_004a: ldloc.0 IL_004b: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0050: brtrue.s IL_000f IL_0052: leave.s IL_0069 } finally { IL_0054: ldloc.0 IL_0055: isinst ""System.IDisposable"" IL_005a: stloc.s V_11 IL_005c: ldloc.s V_11 IL_005e: brfalse.s IL_0068 IL_0060: ldloc.s V_11 IL_0062: callvirt ""void System.IDisposable.Dispose()"" IL_0067: nop IL_0068: endfinally } IL_0069: nop IL_006a: call ""System.Collections.Generic.List<object> C.F4()"" IL_006f: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_0074: stloc.s V_5 .try { IL_0076: br.s IL_00f2 IL_0078: ldloca.s V_5 IL_007a: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_007f: stloc.s V_6 IL_0081: nop IL_0082: nop IL_0083: call ""System.Collections.IEnumerable C.F3()"" IL_0088: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_008d: stloc.s V_7 .try { IL_008f: br.s IL_009c IL_0091: ldloc.s V_7 IL_0093: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0098: stloc.s V_8 IL_009a: nop IL_009b: nop IL_009c: ldloc.s V_7 IL_009e: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_00a3: brtrue.s IL_0091 IL_00a5: leave.s IL_00bd } finally { IL_00a7: ldloc.s V_7 IL_00a9: isinst ""System.IDisposable"" IL_00ae: stloc.s V_11 IL_00b0: ldloc.s V_11 IL_00b2: brfalse.s IL_00bc IL_00b4: ldloc.s V_11 IL_00b6: callvirt ""void System.IDisposable.Dispose()"" IL_00bb: nop IL_00bc: endfinally } IL_00bd: nop IL_00be: call ""System.Collections.Generic.List<object> C.F2()"" IL_00c3: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_00c8: stloc.s V_9 .try { IL_00ca: br.s IL_00d7 IL_00cc: ldloca.s V_9 IL_00ce: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_00d3: stloc.s V_10 IL_00d5: nop IL_00d6: nop IL_00d7: ldloca.s V_9 IL_00d9: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_00de: brtrue.s IL_00cc IL_00e0: leave.s IL_00f1 } finally { IL_00e2: ldloca.s V_9 IL_00e4: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_00ea: callvirt ""void System.IDisposable.Dispose()"" IL_00ef: nop IL_00f0: endfinally } IL_00f1: nop IL_00f2: ldloca.s V_5 IL_00f4: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_00f9: brtrue IL_0078 IL_00fe: leave.s IL_010f } finally { IL_0100: ldloca.s V_5 IL_0102: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_0108: callvirt ""void System.IDisposable.Dispose()"" IL_010d: nop IL_010e: endfinally } IL_010f: ret }"); } [Fact] public void ForEachArray1() { var source = @"class C { static void M(double[,,] c) { foreach (var x in c) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 111 (0x6f) .maxstack 4 .locals init (double[,,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, int V_6, double V_7) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: callvirt ""int System.Array.GetUpperBound(int)"" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: callvirt ""int System.Array.GetUpperBound(int)"" IL_0013: stloc.2 IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: callvirt ""int System.Array.GetUpperBound(int)"" IL_001b: stloc.3 IL_001c: ldloc.0 IL_001d: ldc.i4.0 IL_001e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0023: stloc.s V_4 ~IL_0025: br.s IL_0069 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: callvirt ""int System.Array.GetLowerBound(int)"" IL_002e: stloc.s V_5 ~IL_0030: br.s IL_005e IL_0032: ldloc.0 IL_0033: ldc.i4.2 IL_0034: callvirt ""int System.Array.GetLowerBound(int)"" IL_0039: stloc.s V_6 ~IL_003b: br.s IL_0053 -IL_003d: ldloc.0 IL_003e: ldloc.s V_4 IL_0040: ldloc.s V_5 IL_0042: ldloc.s V_6 IL_0044: call ""double[*,*,*].Get"" IL_0049: stloc.s V_7 -IL_004b: nop -IL_004c: nop ~IL_004d: ldloc.s V_6 IL_004f: ldc.i4.1 IL_0050: add IL_0051: stloc.s V_6 -IL_0053: ldloc.s V_6 IL_0055: ldloc.3 IL_0056: ble.s IL_003d ~IL_0058: ldloc.s V_5 IL_005a: ldc.i4.1 IL_005b: add IL_005c: stloc.s V_5 -IL_005e: ldloc.s V_5 IL_0060: ldloc.2 IL_0061: ble.s IL_0032 ~IL_0063: ldloc.s V_4 IL_0065: ldc.i4.1 IL_0066: add IL_0067: stloc.s V_4 -IL_0069: ldloc.s V_4 IL_006b: ldloc.1 IL_006c: ble.s IL_0027 -IL_006e: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 111 (0x6f) .maxstack 4 .locals init (double[,,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, int V_6, double V_7) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: callvirt ""int System.Array.GetUpperBound(int)"" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: callvirt ""int System.Array.GetUpperBound(int)"" IL_0013: stloc.2 IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: callvirt ""int System.Array.GetUpperBound(int)"" IL_001b: stloc.3 IL_001c: ldloc.0 IL_001d: ldc.i4.0 IL_001e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0023: stloc.s V_4 ~IL_0025: br.s IL_0069 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: callvirt ""int System.Array.GetLowerBound(int)"" IL_002e: stloc.s V_5 ~IL_0030: br.s IL_005e IL_0032: ldloc.0 IL_0033: ldc.i4.2 IL_0034: callvirt ""int System.Array.GetLowerBound(int)"" IL_0039: stloc.s V_6 ~IL_003b: br.s IL_0053 -IL_003d: ldloc.0 IL_003e: ldloc.s V_4 IL_0040: ldloc.s V_5 IL_0042: ldloc.s V_6 IL_0044: call ""double[*,*,*].Get"" IL_0049: stloc.s V_7 -IL_004b: nop -IL_004c: nop ~IL_004d: ldloc.s V_6 IL_004f: ldc.i4.1 IL_0050: add IL_0051: stloc.s V_6 -IL_0053: ldloc.s V_6 IL_0055: ldloc.3 IL_0056: ble.s IL_003d ~IL_0058: ldloc.s V_5 IL_005a: ldc.i4.1 IL_005b: add IL_005c: stloc.s V_5 -IL_005e: ldloc.s V_5 IL_0060: ldloc.2 IL_0061: ble.s IL_0032 ~IL_0063: ldloc.s V_4 IL_0065: ldc.i4.1 IL_0066: add IL_0067: stloc.s V_4 -IL_0069: ldloc.s V_4 IL_006b: ldloc.1 IL_006c: ble.s IL_0027 -IL_006e: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ForEachArray2() { var source = @"class C { static void M(string a, object[] b, double[,,] c) { foreach (var x in a) { foreach (var y in b) { } } foreach (var x in c) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 184 (0xb8) .maxstack 4 .locals init (string V_0, int V_1, char V_2, //x object[] V_3, int V_4, object V_5, //y double[,,] V_6, int V_7, int V_8, int V_9, int V_10, int V_11, int V_12, double V_13) //x IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldc.i4.0 IL_0005: stloc.1 IL_0006: br.s IL_0033 IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: callvirt ""char string.this[int].get"" IL_000f: stloc.2 IL_0010: nop IL_0011: nop IL_0012: ldarg.1 IL_0013: stloc.3 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0027 IL_0019: ldloc.3 IL_001a: ldloc.s V_4 IL_001c: ldelem.ref IL_001d: stloc.s V_5 IL_001f: nop IL_0020: nop IL_0021: ldloc.s V_4 IL_0023: ldc.i4.1 IL_0024: add IL_0025: stloc.s V_4 IL_0027: ldloc.s V_4 IL_0029: ldloc.3 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0019 IL_002e: nop IL_002f: ldloc.1 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.1 IL_0033: ldloc.1 IL_0034: ldloc.0 IL_0035: callvirt ""int string.Length.get"" IL_003a: blt.s IL_0008 IL_003c: nop IL_003d: ldarg.2 IL_003e: stloc.s V_6 IL_0040: ldloc.s V_6 IL_0042: ldc.i4.0 IL_0043: callvirt ""int System.Array.GetUpperBound(int)"" IL_0048: stloc.s V_7 IL_004a: ldloc.s V_6 IL_004c: ldc.i4.1 IL_004d: callvirt ""int System.Array.GetUpperBound(int)"" IL_0052: stloc.s V_8 IL_0054: ldloc.s V_6 IL_0056: ldc.i4.2 IL_0057: callvirt ""int System.Array.GetUpperBound(int)"" IL_005c: stloc.s V_9 IL_005e: ldloc.s V_6 IL_0060: ldc.i4.0 IL_0061: callvirt ""int System.Array.GetLowerBound(int)"" IL_0066: stloc.s V_10 IL_0068: br.s IL_00b1 IL_006a: ldloc.s V_6 IL_006c: ldc.i4.1 IL_006d: callvirt ""int System.Array.GetLowerBound(int)"" IL_0072: stloc.s V_11 IL_0074: br.s IL_00a5 IL_0076: ldloc.s V_6 IL_0078: ldc.i4.2 IL_0079: callvirt ""int System.Array.GetLowerBound(int)"" IL_007e: stloc.s V_12 IL_0080: br.s IL_0099 IL_0082: ldloc.s V_6 IL_0084: ldloc.s V_10 IL_0086: ldloc.s V_11 IL_0088: ldloc.s V_12 IL_008a: call ""double[*,*,*].Get"" IL_008f: stloc.s V_13 IL_0091: nop IL_0092: nop IL_0093: ldloc.s V_12 IL_0095: ldc.i4.1 IL_0096: add IL_0097: stloc.s V_12 IL_0099: ldloc.s V_12 IL_009b: ldloc.s V_9 IL_009d: ble.s IL_0082 IL_009f: ldloc.s V_11 IL_00a1: ldc.i4.1 IL_00a2: add IL_00a3: stloc.s V_11 IL_00a5: ldloc.s V_11 IL_00a7: ldloc.s V_8 IL_00a9: ble.s IL_0076 IL_00ab: ldloc.s V_10 IL_00ad: ldc.i4.1 IL_00ae: add IL_00af: stloc.s V_10 IL_00b1: ldloc.s V_10 IL_00b3: ldloc.s V_7 IL_00b5: ble.s IL_006a IL_00b7: ret }"); } /// <summary> /// Unlike Dev12 we can handle array with more than 256 dimensions. /// </summary> [Fact] public void ForEachArray_ToManyDimensions() { var source = @"class C { static void M(object o) { foreach (var x in (object[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,])o) { } } }"; // Make sure the source contains an array with too many dimensions. var tooManyCommas = new string(',', 256); Assert.True(source.IndexOf(tooManyCommas, StringComparison.Ordinal) > 0); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); } [Fact] public void ForEachWithDynamicAndTuple() { var source = @"class C { static void M((dynamic, int) t) { foreach (var o in t.Item1) { } } }"; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 119 (0x77) .maxstack 3 .locals init (System.Collections.IEnumerator V_0, object V_1, //o [unchanged] V_2, System.IDisposable V_3) IL_0000: nop IL_0001: nop IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_0007: brfalse.s IL_000b IL_0009: br.s IL_002f IL_000b: ldc.i4.0 IL_000c: ldtoken ""System.Collections.IEnumerable"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0025: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_002f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_0034: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>>.Target"" IL_0039: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_003e: ldarg.0 IL_003f: ldfld ""dynamic System.ValueTuple<dynamic, int>.Item1"" IL_0044: callvirt ""System.Collections.IEnumerable System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0049: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_004e: stloc.0 .try { IL_004f: br.s IL_005a IL_0051: ldloc.0 IL_0052: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0057: stloc.1 IL_0058: nop IL_0059: nop IL_005a: ldloc.0 IL_005b: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0060: brtrue.s IL_0051 IL_0062: leave.s IL_0076 } finally { IL_0064: ldloc.0 IL_0065: isinst ""System.IDisposable"" IL_006a: stloc.3 IL_006b: ldloc.3 IL_006c: brfalse.s IL_0075 IL_006e: ldloc.3 IL_006f: callvirt ""void System.IDisposable.Dispose()"" IL_0074: nop IL_0075: endfinally } IL_0076: ret }"); } [Fact] public void RemoveRestoreNullableAtArrayElement() { var source0 = MarkedSource( @"using System; class C { public static void M() { var <N:1>arr</N:1> = new string?[] { ""0"" }; <N:0>foreach</N:0> (var s in arr) { Console.WriteLine(1); } } }"); // Remove nullable var source1 = MarkedSource( @"using System; class C { public static void M() { var <N:1>arr</N:1> = new string[] { ""0"" }; <N:0>foreach</N:0> (var s in arr) { Console.WriteLine(1); } } }"); // Restore nullable var source2 = source0; var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: nop IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_0028 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: nop IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 IL_002e: ret }"); var compilation1 = CreateCompilation(source1.Tree, options: TestOptions.DebugDll); var compilation2 = compilation0.WithSource(source2.Tree); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: nop IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_0028 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: nop IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 IL_002e: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 -IL_0010: nop -IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 ~IL_0015: br.s IL_0028 -IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 -IL_001b: nop -IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop -IL_0023: nop ~IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 -IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 -IL_002e: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void AddAndDelete() { var source0 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { lock (F1()) { } foreach (var c in F2()) { } using (F3()) { } } }"; // Delete one statement. var source1 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { lock (F1()) { } foreach (var c in F2()) { } } }"; // Add statement with same temp kind. var source2 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { using (F3()) { } lock (F1()) { } foreach (var c in F2()) { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 93 (0x5d) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c System.IDisposable V_5) IL_0000: nop IL_0001: call ""object C.F1()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: nop IL_0022: call ""string C.F2()"" IL_0027: stloc.2 IL_0028: ldc.i4.0 IL_0029: stloc.3 IL_002a: br.s IL_003b IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: callvirt ""char string.this[int].get"" IL_0033: stloc.s V_4 IL_0035: nop IL_0036: nop IL_0037: ldloc.3 IL_0038: ldc.i4.1 IL_0039: add IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldloc.2 IL_003d: callvirt ""int string.Length.get"" IL_0042: blt.s IL_002c IL_0044: call ""System.IDisposable C.F3()"" IL_0049: stloc.s V_5 .try { IL_004b: nop IL_004c: nop IL_004d: leave.s IL_005c } finally { IL_004f: ldloc.s V_5 IL_0051: brfalse.s IL_005b IL_0053: ldloc.s V_5 IL_0055: callvirt ""void System.IDisposable.Dispose()"" IL_005a: nop IL_005b: endfinally } IL_005c: ret }"); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var compilation2 = compilation0.WithSource(source2); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 69 (0x45) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c [unchanged] V_5) IL_0000: nop IL_0001: call ""object C.F1()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: nop IL_0022: call ""string C.F2()"" IL_0027: stloc.2 IL_0028: ldc.i4.0 IL_0029: stloc.3 IL_002a: br.s IL_003b IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: callvirt ""char string.this[int].get"" IL_0033: stloc.s V_4 IL_0035: nop IL_0036: nop IL_0037: ldloc.3 IL_0038: ldc.i4.1 IL_0039: add IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldloc.2 IL_003d: callvirt ""int string.Length.get"" IL_0042: blt.s IL_002c IL_0044: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 93 (0x5d) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c [unchanged] V_5, System.IDisposable V_6) -IL_0000: nop -IL_0001: call ""System.IDisposable C.F3()"" IL_0006: stloc.s V_6 .try { -IL_0008: nop -IL_0009: nop IL_000a: leave.s IL_0019 } finally { ~IL_000c: ldloc.s V_6 IL_000e: brfalse.s IL_0018 IL_0010: ldloc.s V_6 IL_0012: callvirt ""void System.IDisposable.Dispose()"" IL_0017: nop ~IL_0018: endfinally } -IL_0019: call ""object C.F1()"" IL_001e: stloc.0 IL_001f: ldc.i4.0 IL_0020: stloc.1 .try { IL_0021: ldloc.0 IL_0022: ldloca.s V_1 IL_0024: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0029: nop -IL_002a: nop -IL_002b: nop IL_002c: leave.s IL_0039 } finally { ~IL_002e: ldloc.1 IL_002f: brfalse.s IL_0038 IL_0031: ldloc.0 IL_0032: call ""void System.Threading.Monitor.Exit(object)"" IL_0037: nop ~IL_0038: endfinally } -IL_0039: nop -IL_003a: call ""string C.F2()"" IL_003f: stloc.2 IL_0040: ldc.i4.0 IL_0041: stloc.3 ~IL_0042: br.s IL_0053 -IL_0044: ldloc.2 IL_0045: ldloc.3 IL_0046: callvirt ""char string.this[int].get"" IL_004b: stloc.s V_4 -IL_004d: nop -IL_004e: nop ~IL_004f: ldloc.3 IL_0050: ldc.i4.1 IL_0051: add IL_0052: stloc.3 -IL_0053: ldloc.3 IL_0054: ldloc.2 IL_0055: callvirt ""int string.Length.get"" IL_005a: blt.s IL_0044 -IL_005c: ret }", methodToken: diff2.EmitResult.UpdatedMethods.Single()); } [Fact] public void Insert() { var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } static void M() { lock (F1()) { } lock (F2()) { } } }"; var source1 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } static void M() { lock (F3()) { } // added lock (F1()) { } lock (F4()) { } // replaced } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Note that the order of unique ids in temporaries follows the // order of declaration in the updated method. Specifically, the // original temporary names (and unique ids) are not preserved. // (Should not be an issue since the names are used by EnC only.) diff1.VerifyIL("C.M", @"{ // Code size 108 (0x6c) .maxstack 2 .locals init (object V_0, bool V_1, [object] V_2, [bool] V_3, object V_4, bool V_5, object V_6, bool V_7) IL_0000: nop IL_0001: call ""object C.F3()"" IL_0006: stloc.s V_4 IL_0008: ldc.i4.0 IL_0009: stloc.s V_5 .try { IL_000b: ldloc.s V_4 IL_000d: ldloca.s V_5 IL_000f: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0014: nop IL_0015: nop IL_0016: nop IL_0017: leave.s IL_0026 } finally { IL_0019: ldloc.s V_5 IL_001b: brfalse.s IL_0025 IL_001d: ldloc.s V_4 IL_001f: call ""void System.Threading.Monitor.Exit(object)"" IL_0024: nop IL_0025: endfinally } IL_0026: call ""object C.F1()"" IL_002b: stloc.0 IL_002c: ldc.i4.0 IL_002d: stloc.1 .try { IL_002e: ldloc.0 IL_002f: ldloca.s V_1 IL_0031: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0036: nop IL_0037: nop IL_0038: nop IL_0039: leave.s IL_0046 } finally { IL_003b: ldloc.1 IL_003c: brfalse.s IL_0045 IL_003e: ldloc.0 IL_003f: call ""void System.Threading.Monitor.Exit(object)"" IL_0044: nop IL_0045: endfinally } IL_0046: call ""object C.F4()"" IL_004b: stloc.s V_6 IL_004d: ldc.i4.0 IL_004e: stloc.s V_7 .try { IL_0050: ldloc.s V_6 IL_0052: ldloca.s V_7 IL_0054: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0059: nop IL_005a: nop IL_005b: nop IL_005c: leave.s IL_006b } finally { IL_005e: ldloc.s V_7 IL_0060: brfalse.s IL_006a IL_0062: ldloc.s V_6 IL_0064: call ""void System.Threading.Monitor.Exit(object)"" IL_0069: nop IL_006a: endfinally } IL_006b: ret }"); } /// <summary> /// Should not reuse temporary locals /// having different temporary kinds. /// </summary> [Fact] public void NoReuseDifferentTempKind() { var source = @"class A : System.IDisposable { public object Current { get { return null; } } public bool MoveNext() { return false; } public void Dispose() { } internal int this[A a] { get { return 0; } set { } } } class B { public A GetEnumerator() { return null; } } class C { static A F() { return null; } static B G() { return null; } static void M(A a) { a[F()]++; using (F()) { } lock (F()) { } foreach (var o in G()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 137 (0x89) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, A V_2, A V_3, bool V_4, A V_5, object V_6, //o A V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""A C.F()"" IL_0007: stloc.s V_7 IL_0009: dup IL_000a: ldloc.s V_7 IL_000c: callvirt ""int A.this[A].get"" IL_0011: stloc.s V_8 IL_0013: ldloc.s V_7 IL_0015: ldloc.s V_8 IL_0017: ldc.i4.1 IL_0018: add IL_0019: callvirt ""void A.this[A].set"" IL_001e: nop IL_001f: call ""A C.F()"" IL_0024: stloc.2 .try { IL_0025: nop IL_0026: nop IL_0027: leave.s IL_0034 } finally { IL_0029: ldloc.2 IL_002a: brfalse.s IL_0033 IL_002c: ldloc.2 IL_002d: callvirt ""void System.IDisposable.Dispose()"" IL_0032: nop IL_0033: endfinally } IL_0034: call ""A C.F()"" IL_0039: stloc.3 IL_003a: ldc.i4.0 IL_003b: stloc.s V_4 .try { IL_003d: ldloc.3 IL_003e: ldloca.s V_4 IL_0040: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0045: nop IL_0046: nop IL_0047: nop IL_0048: leave.s IL_0056 } finally { IL_004a: ldloc.s V_4 IL_004c: brfalse.s IL_0055 IL_004e: ldloc.3 IL_004f: call ""void System.Threading.Monitor.Exit(object)"" IL_0054: nop IL_0055: endfinally } IL_0056: nop IL_0057: call ""B C.G()"" IL_005c: callvirt ""A B.GetEnumerator()"" IL_0061: stloc.s V_5 .try { IL_0063: br.s IL_0070 IL_0065: ldloc.s V_5 IL_0067: callvirt ""object A.Current.get"" IL_006c: stloc.s V_6 IL_006e: nop IL_006f: nop IL_0070: ldloc.s V_5 IL_0072: callvirt ""bool A.MoveNext()"" IL_0077: brtrue.s IL_0065 IL_0079: leave.s IL_0088 } finally { IL_007b: ldloc.s V_5 IL_007d: brfalse.s IL_0087 IL_007f: ldloc.s V_5 IL_0081: callvirt ""void System.IDisposable.Dispose()"" IL_0086: nop IL_0087: endfinally } IL_0088: ret }"); } [Fact] public void Switch_String() { var source0 = @"class C { static string F() { return null; } static void M() { switch (F()) { case ""a"": System.Console.WriteLine(1); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var source1 = @"class C { static string F() { return null; } static void M() { switch (F()) { case ""a"": System.Console.WriteLine(10); break; case ""b"": System.Console.WriteLine(20); break; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); // Validate presence of a hidden sequence point @IL_0007 that is required for proper function remapping. v0.VerifyIL("C.M", @" { // Code size 56 (0x38) .maxstack 2 .locals init (string V_0, string V_1) -IL_0000: nop -IL_0001: call ""string C.F()"" IL_0006: stloc.1 ~IL_0007: ldloc.1 IL_0008: stloc.0 ~IL_0009: ldloc.0 IL_000a: ldstr ""a"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldstr ""b"" IL_001c: call ""bool string.op_Equality(string, string)"" IL_0021: brtrue.s IL_002e IL_0023: br.s IL_0037 -IL_0025: ldc.i4.1 IL_0026: call ""void System.Console.WriteLine(int)"" IL_002b: nop -IL_002c: br.s IL_0037 -IL_002e: ldc.i4.2 IL_002f: call ""void System.Console.WriteLine(int)"" IL_0034: nop -IL_0035: br.s IL_0037 -IL_0037: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.SwitchStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0, string V_1) -IL_0000: nop -IL_0001: call ""string C.F()"" IL_0006: stloc.1 ~IL_0007: ldloc.1 IL_0008: stloc.0 ~IL_0009: ldloc.0 IL_000a: ldstr ""a"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldstr ""b"" IL_001c: call ""bool string.op_Equality(string, string)"" IL_0021: brtrue.s IL_002f IL_0023: br.s IL_0039 -IL_0025: ldc.i4.s 10 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop -IL_002d: br.s IL_0039 -IL_002f: ldc.i4.s 20 IL_0031: call ""void System.Console.WriteLine(int)"" IL_0036: nop -IL_0037: br.s IL_0039 -IL_0039: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Switch_Integer() { var source0 = WithWindowsLineBreaks( @"class C { static int F() { return 1; } static void M() { switch (F()) { case 1: System.Console.WriteLine(1); break; case 2: System.Console.WriteLine(2); break; } } }"); var source1 = WithWindowsLineBreaks( @"class C { static int F() { return 1; } static void M() { switch (F()) { case 1: System.Console.WriteLine(10); break; case 2: System.Console.WriteLine(20); break; } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 40 (0x28) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: call ""int C.F()"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: ldc.i4.1 IL_000b: beq.s IL_0015 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ldc.i4.2 IL_0011: beq.s IL_001e IL_0013: br.s IL_0027 IL_0015: ldc.i4.1 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: br.s IL_0027 IL_001e: ldc.i4.2 IL_001f: call ""void System.Console.WriteLine(int)"" IL_0024: nop IL_0025: br.s IL_0027 IL_0027: ret }"); // Validate that we emit a hidden sequence point @IL_0007. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""49"" document=""1"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""50"" endLine=""9"" endColumn=""56"" document=""1"" /> <entry offset=""0x1e"" startLine=""10"" startColumn=""21"" endLine=""10"" endColumn=""49"" document=""1"" /> <entry offset=""0x25"" startLine=""10"" startColumn=""50"" endLine=""10"" endColumn=""56"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.SwitchStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: call ""int C.F()"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: ldc.i4.1 IL_000b: beq.s IL_0015 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ldc.i4.2 IL_0011: beq.s IL_001f IL_0013: br.s IL_0029 IL_0015: ldc.i4.s 10 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: br.s IL_0029 IL_001f: ldc.i4.s 20 IL_0021: call ""void System.Console.WriteLine(int)"" IL_0026: nop IL_0027: br.s IL_0029 IL_0029: ret }"); } [Fact] public void Switch_Patterns() { var source = WithWindowsLineBreaks(@" using static System.Console; class C { static object F() => 1; static bool P() => false; static void M() { switch (F()) { case 1: WriteLine(""int 1""); break; case byte b when P(): WriteLine(b); break; case int i when P(): WriteLine(i); break; case (byte)1: WriteLine(""byte 1""); break; case int j: WriteLine(j); break; case object o: WriteLine(o); break; } } }"); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""0"" offset=""106"" /> <slot kind=""0"" offset=""162"" /> <slot kind=""0"" offset=""273"" /> <slot kind=""0"" offset=""323"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>", options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints); v0.VerifyIL("C.M", @" { // Code size 147 (0x93) .maxstack 2 .locals init (byte V_0, //b int V_1, //i int V_2, //j object V_3, //o object V_4) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.s V_4 IL_0008: ldloc.s V_4 IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: isinst ""int"" IL_0011: brfalse.s IL_0020 IL_0013: ldloc.3 IL_0014: unbox.any ""int"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: beq.s IL_003c IL_001e: br.s IL_005b IL_0020: ldloc.3 IL_0021: isinst ""byte"" IL_0026: brfalse.s IL_0037 IL_0028: ldloc.3 IL_0029: unbox.any ""byte"" IL_002e: stloc.0 IL_002f: br.s IL_0049 IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: beq.s IL_006d IL_0035: br.s IL_0087 IL_0037: ldloc.3 IL_0038: brtrue.s IL_0087 IL_003a: br.s IL_0092 IL_003c: ldstr ""int 1"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: nop IL_0047: br.s IL_0092 IL_0049: call ""bool C.P()"" IL_004e: brtrue.s IL_0052 IL_0050: br.s IL_0031 IL_0052: ldloc.0 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: br.s IL_0092 IL_005b: call ""bool C.P()"" IL_0060: brtrue.s IL_0064 IL_0062: br.s IL_007a IL_0064: ldloc.1 IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: br.s IL_0092 IL_006d: ldstr ""byte 1"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: nop IL_0078: br.s IL_0092 IL_007a: ldloc.1 IL_007b: stloc.2 IL_007c: br.s IL_007e IL_007e: ldloc.2 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop IL_0085: br.s IL_0092 IL_0087: br.s IL_0089 IL_0089: ldloc.3 IL_008a: call ""void System.Console.WriteLine(object)"" IL_008f: nop IL_0090: br.s IL_0092 IL_0092: ret }"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 147 (0x93) .maxstack 2 .locals init (byte V_0, //b int V_1, //i int V_2, //j object V_3, //o object V_4) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.s V_4 IL_0008: ldloc.s V_4 IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: isinst ""int"" IL_0011: brfalse.s IL_0020 IL_0013: ldloc.3 IL_0014: unbox.any ""int"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: beq.s IL_003c IL_001e: br.s IL_005b IL_0020: ldloc.3 IL_0021: isinst ""byte"" IL_0026: brfalse.s IL_0037 IL_0028: ldloc.3 IL_0029: unbox.any ""byte"" IL_002e: stloc.0 IL_002f: br.s IL_0049 IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: beq.s IL_006d IL_0035: br.s IL_0087 IL_0037: ldloc.3 IL_0038: brtrue.s IL_0087 IL_003a: br.s IL_0092 IL_003c: ldstr ""int 1"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: nop IL_0047: br.s IL_0092 IL_0049: call ""bool C.P()"" IL_004e: brtrue.s IL_0052 IL_0050: br.s IL_0031 IL_0052: ldloc.0 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: br.s IL_0092 IL_005b: call ""bool C.P()"" IL_0060: brtrue.s IL_0064 IL_0062: br.s IL_007a IL_0064: ldloc.1 IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: br.s IL_0092 IL_006d: ldstr ""byte 1"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: nop IL_0078: br.s IL_0092 IL_007a: ldloc.1 IL_007b: stloc.2 IL_007c: br.s IL_007e IL_007e: ldloc.2 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop IL_0085: br.s IL_0092 IL_0087: br.s IL_0089 IL_0089: ldloc.3 IL_008a: call ""void System.Console.WriteLine(object)"" IL_008f: nop IL_0090: br.s IL_0092 IL_0092: ret }"); } [Fact] public void If() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { if (F()) { System.Console.WriteLine(1); } } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { if (F()) { System.Console.WriteLine(10); } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: call ""bool C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0013 IL_000a: nop IL_000b: ldc.i4.1 IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: nop IL_0012: nop IL_0013: ret } "); // Validate presence of a hidden sequence point @IL_0007 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x12"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.IfStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 21 (0x15) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: call ""bool C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: nop IL_000b: ldc.i4.s 10 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: nop IL_0014: ret }"); } [Fact] public void While() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { while (F()) { System.Console.WriteLine(1); } } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { while (F()) { System.Console.WriteLine(10); } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: br.s IL_000c IL_0003: nop IL_0004: ldc.i4.1 IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: nop IL_000b: nop IL_000c: call ""bool C.F()"" IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: brtrue.s IL_0003 IL_0015: ret } "); // Validate presence of a hidden sequence point @IL_0012 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0xb"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""20"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.WhileStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: br.s IL_000d IL_0003: nop IL_0004: ldc.i4.s 10 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: nop IL_000d: call ""bool C.F()"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: brtrue.s IL_0003 IL_0016: ret }"); } [Fact] public void Do1() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { do { System.Console.WriteLine(1); } while (F()); } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { do { System.Console.WriteLine(10); } while (F()); } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: nop IL_0002: ldc.i4.1 IL_0003: call ""void System.Console.WriteLine(int)"" IL_0008: nop IL_0009: nop IL_000a: call ""bool C.F()"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: brtrue.s IL_0001 IL_0013: ret }"); // Validate presence of a hidden sequence point @IL_0010 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x9"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""21"" document=""1"" /> <entry offset=""0x10"" hidden=""true"" document=""1"" /> <entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.DoStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 21 (0x15) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: nop IL_0002: ldc.i4.s 10 IL_0004: call ""void System.Console.WriteLine(int)"" IL_0009: nop IL_000a: nop IL_000b: call ""bool C.F()"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: brtrue.s IL_0001 IL_0014: ret }"); } [Fact] public void For() { var source0 = @" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(1); } } }"; var source1 = @" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(10); } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); // Validate presence of a hidden sequence point @IL_001c that is required for proper function remapping. v0.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 1 .locals init (int V_0, //i bool V_1) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 ~IL_0003: br.s IL_0015 -IL_0005: nop -IL_0006: ldc.i4.1 IL_0007: call ""void System.Console.WriteLine(int)"" IL_000c: nop -IL_000d: nop -IL_000e: ldloc.0 IL_000f: call ""void C.G(int)"" IL_0014: nop -IL_0015: ldloc.0 IL_0016: call ""bool C.F(int)"" IL_001b: stloc.1 ~IL_001c: ldloc.1 IL_001d: brtrue.s IL_0005 -IL_001f: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.ForStatement, SyntaxKind.VariableDeclarator), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, //i bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: br.s IL_0016 IL_0005: nop IL_0006: ldc.i4.s 10 IL_0008: call ""void System.Console.WriteLine(int)"" IL_000d: nop IL_000e: nop IL_000f: ldloc.0 IL_0010: call ""void C.G(int)"" IL_0015: nop IL_0016: ldloc.0 IL_0017: call ""bool C.F(int)"" IL_001c: stloc.1 IL_001d: ldloc.1 IL_001e: brtrue.s IL_0005 IL_0020: ret } "); } [Fact] public void SynthesizedVariablesInLambdas1() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { var f = new System.Action(() => { lock (F()) { } }); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<>c.<M>b__1_0()", @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0, bool V_1) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: ret }"); #if TODO // identify the lambda in a semantic edit var methodData0 = v0.TestData.GetMethodData("C.<M>b__0"); var method0 = compilation0.GetMember<MethodSymbol>("C.<M>b__0"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("C.<M>b__0"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.<M>b__0", @" ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void SynthesizedVariablesInLambdas2() { var source0 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(1); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var source1 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(10); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var source2 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(100); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <M>b__0_0, <M>b__0_1}"); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <M>b__0_0, <M>b__0_1}"); var expectedIL = @" { // Code size 33 (0x21) .maxstack 2 .locals init (int[] V_0, int V_1, int V_2) //x IL_0000: nop IL_0001: nop IL_0002: ldarg.1 IL_0003: stloc.0 IL_0004: ldc.i4.0 IL_0005: stloc.1 IL_0006: br.s IL_001a IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: ldelem.i4 IL_000b: stloc.2 IL_000c: nop IL_000d: ldc.i4.s 20 IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: nop IL_0016: ldloc.1 IL_0017: ldc.i4.1 IL_0018: add IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldloc.0 IL_001c: ldlen IL_001d: conv.i4 IL_001e: blt.s IL_0008 IL_0020: ret }"; diff1.VerifyIL(@"C.<>c.<M>b__0_1", expectedIL); diff2.VerifyIL(@"C.<>c.<M>b__0_1", expectedIL); } [Fact] public void SynthesizedVariablesInIterator1() { var source = @" using System.Collections.Generic; class C { public IEnumerable<int> F() { lock (F()) { } yield return 1; } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 131 (0x83) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_007a IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldarg.0 IL_0022: ldfld ""C C.<F>d__0.<>4__this"" IL_0027: call ""System.Collections.Generic.IEnumerable<int> C.F()"" IL_002c: stfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_0031: ldarg.0 IL_0032: ldc.i4.0 IL_0033: stfld ""bool C.<F>d__0.<>s__2"" .try { IL_0038: ldarg.0 IL_0039: ldfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_003e: ldarg.0 IL_003f: ldflda ""bool C.<F>d__0.<>s__2"" IL_0044: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0049: nop IL_004a: nop IL_004b: nop IL_004c: leave.s IL_0063 } finally { IL_004e: ldarg.0 IL_004f: ldfld ""bool C.<F>d__0.<>s__2"" IL_0054: brfalse.s IL_0062 IL_0056: ldarg.0 IL_0057: ldfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_005c: call ""void System.Threading.Monitor.Exit(object)"" IL_0061: nop IL_0062: endfinally } IL_0063: ldarg.0 IL_0064: ldnull IL_0065: stfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_006a: ldarg.0 IL_006b: ldc.i4.1 IL_006c: stfld ""int C.<F>d__0.<>2__current"" IL_0071: ldarg.0 IL_0072: ldc.i4.1 IL_0073: stfld ""int C.<F>d__0.<>1__state"" IL_0078: ldc.i4.1 IL_0079: ret IL_007a: ldarg.0 IL_007b: ldc.i4.m1 IL_007c: stfld ""int C.<F>d__0.<>1__state"" IL_0081: ldc.i4.0 IL_0082: ret }"); #if TODO var methodData0 = v0.TestData.GetMethodData("?"); var method0 = compilation0.GetMember<MethodSymbol>("?"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("?"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("?", @" {", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void SynthesizedVariablesInAsyncMethod1() { var source = @" using System.Threading.Tasks; class C { public async Task<int> F() { lock (F()) { } await F(); return 1; } } "; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 246 (0xf6) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, C.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0011 IL_000c: br IL_009e -IL_0011: nop -IL_0012: ldarg.0 IL_0013: ldarg.0 IL_0014: ldfld ""C C.<F>d__0.<>4__this"" IL_0019: call ""System.Threading.Tasks.Task<int> C.F()"" IL_001e: stfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: stfld ""bool C.<F>d__0.<>s__2"" .try { IL_002a: ldarg.0 IL_002b: ldfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0030: ldarg.0 IL_0031: ldflda ""bool C.<F>d__0.<>s__2"" IL_0036: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_003b: nop -IL_003c: nop -IL_003d: nop IL_003e: leave.s IL_0059 } finally { ~IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: bge.s IL_0058 IL_0044: ldarg.0 IL_0045: ldfld ""bool C.<F>d__0.<>s__2"" IL_004a: brfalse.s IL_0058 IL_004c: ldarg.0 IL_004d: ldfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0052: call ""void System.Threading.Monitor.Exit(object)"" IL_0057: nop ~IL_0058: endfinally } ~IL_0059: ldarg.0 IL_005a: ldnull IL_005b: stfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" -IL_0060: ldarg.0 IL_0061: ldfld ""C C.<F>d__0.<>4__this"" IL_0066: call ""System.Threading.Tasks.Task<int> C.F()"" IL_006b: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0070: stloc.2 ~IL_0071: ldloca.s V_2 IL_0073: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0078: brtrue.s IL_00ba IL_007a: ldarg.0 IL_007b: ldc.i4.0 IL_007c: dup IL_007d: stloc.0 IL_007e: stfld ""int C.<F>d__0.<>1__state"" <IL_0083: ldarg.0 IL_0084: ldloc.2 IL_0085: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_008a: ldarg.0 IL_008b: stloc.3 IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0092: ldloca.s V_2 IL_0094: ldloca.s V_3 IL_0096: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)"" IL_009b: nop IL_009c: leave.s IL_00f5 >IL_009e: ldarg.0 IL_009f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_00a4: stloc.2 IL_00a5: ldarg.0 IL_00a6: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_00ab: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00b1: ldarg.0 IL_00b2: ldc.i4.m1 IL_00b3: dup IL_00b4: stloc.0 IL_00b5: stfld ""int C.<F>d__0.<>1__state"" IL_00ba: ldloca.s V_2 IL_00bc: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00c1: pop -IL_00c2: ldc.i4.1 IL_00c3: stloc.1 IL_00c4: leave.s IL_00e0 } catch System.Exception { ~IL_00c6: stloc.s V_4 IL_00c8: ldarg.0 IL_00c9: ldc.i4.s -2 IL_00cb: stfld ""int C.<F>d__0.<>1__state"" IL_00d0: ldarg.0 IL_00d1: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00d6: ldloc.s V_4 IL_00d8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00dd: nop IL_00de: leave.s IL_00f5 } -IL_00e0: ldarg.0 IL_00e1: ldc.i4.s -2 IL_00e3: stfld ""int C.<F>d__0.<>1__state"" ~IL_00e8: ldarg.0 IL_00e9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00ee: ldloc.1 IL_00ef: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00f4: nop IL_00f5: ret }", sequencePoints: "C+<F>d__0.MoveNext"); #if TODO var methodData0 = v0.TestData.GetMethodData("?"); var method0 = compilation0.GetMember<MethodSymbol>("?"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("?"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("?", @" {", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void OutVar() { var source = @" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int x, out var y); return x + y; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop -IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 -IL_0011: ldloc.3 IL_0012: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternVariable() { var source = @" class C { static int F(object o) { if (o is int i) { return i; } return 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d -IL_0018: nop -IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0021 -IL_001d: ldc.i4.0 IL_001e: stloc.3 IL_001f: br.s IL_0021 -IL_0021: ldloc.3 IL_0022: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Tuple_Parenthesized() { var source = @" class C { static int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x [int] V_1, int V_2) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" -IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.2 IL_002f: br.s IL_0031 -IL_0031: ldloc.2 IL_0032: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Tuple_Decomposition() { var source = @" class C { static int F() { (int x, (int y, int z)) = (1, (2, 3)); return x + y + z; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z [int] V_3, int V_4) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 -IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.s V_4 IL_000e: br.s IL_0010 -IL_0010: ldloc.s V_4 IL_0012: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternMatching_Variable() { var source = @" class C { static int F(object o) { if (o is int i) { return i; } return 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d -IL_0018: nop -IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0021 -IL_001d: ldc.i4.0 IL_001e: stloc.3 IL_001f: br.s IL_0021 -IL_0021: ldloc.3 IL_0022: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternMatching_NoVariable() { var source = @" class C { static int F(object o) { if ((o is bool) || (o is 0)) { return 0; } return 1; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (bool V_0, [int] V_1, int V_2) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brtrue.s IL_001f IL_0009: ldarg.0 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_001c IL_0011: ldarg.0 IL_0012: unbox.any ""int"" IL_0017: ldc.i4.0 IL_0018: ceq IL_001a: br.s IL_001d IL_001c: ldc.i4.0 IL_001d: br.s IL_0020 IL_001f: ldc.i4.1 IL_0020: stloc.0 ~IL_0021: ldloc.0 IL_0022: brfalse.s IL_0029 -IL_0024: nop -IL_0025: ldc.i4.0 IL_0026: stloc.2 IL_0027: br.s IL_002d -IL_0029: ldc.i4.1 IL_002a: stloc.2 IL_002b: br.s IL_002d -IL_002d: ldloc.2 IL_002e: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void VarPattern() { var source = @" using System.Threading.Tasks; class C { static object G(object o1, object o2) { return (o1, o2) switch { (int a, string b) => a, _ => 0 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 62 (0x3e) .maxstack 1 .locals init (int V_0, //a string V_1, //b [int] V_2, [object] V_3, int V_4, object V_5) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 -IL_0004: nop ~IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0027 IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.0 ~IL_0014: ldarg.1 IL_0015: isinst ""string"" IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: brtrue.s IL_0020 IL_001e: br.s IL_0027 ~IL_0020: br.s IL_0022 -IL_0022: ldloc.0 IL_0023: stloc.s V_4 IL_0025: br.s IL_002c -IL_0027: ldc.i4.0 IL_0028: stloc.s V_4 IL_002a: br.s IL_002c ~IL_002c: ldc.i4.1 IL_002d: brtrue.s IL_0030 -IL_002f: nop ~IL_0030: ldloc.s V_4 IL_0032: box ""int"" IL_0037: stloc.s V_5 IL_0039: br.s IL_003b -IL_003b: ldloc.s V_5 IL_003d: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void RecursiveSwitchExpression() { var source = @" class C { static object G(object o) { return o switch { int i => i switch { 0 => 1, _ => 2, }, _ => 3 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 76 (0x4c) .maxstack 1 .locals init (int V_0, //i [int] V_1, [int] V_2, [object] V_3, int V_4, int V_5, object V_6) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 -IL_0004: nop ~IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0035 IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.0 ~IL_0014: br.s IL_0016 ~IL_0016: br.s IL_0018 IL_0018: ldc.i4.1 IL_0019: brtrue.s IL_001c -IL_001b: nop ~IL_001c: ldloc.0 IL_001d: brfalse.s IL_0021 IL_001f: br.s IL_0026 -IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b -IL_0026: ldc.i4.2 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b ~IL_002b: ldc.i4.1 IL_002c: brtrue.s IL_002f -IL_002e: nop -IL_002f: ldloc.s V_5 IL_0031: stloc.s V_4 IL_0033: br.s IL_003a -IL_0035: ldc.i4.3 IL_0036: stloc.s V_4 IL_0038: br.s IL_003a ~IL_003a: ldc.i4.1 IL_003b: brtrue.s IL_003e -IL_003d: nop ~IL_003e: ldloc.s V_4 IL_0040: box ""int"" IL_0045: stloc.s V_6 IL_0047: br.s IL_0049 -IL_0049: ldloc.s V_6 IL_004b: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void RecursiveSwitchExpressionWithAwait() { var source = @" using System.Threading.Tasks; class C { static async Task<object> G(object o) { return o switch { Task<int> i when await i > 0 => await i switch { 1 => 1, _ => 2, }, _ => 3 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetEquivalentNodesMap(g1, g0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 56 (0x38) .maxstack 2 .locals init (C.<G>d__0 V_0) ~IL_0000: newobj ""C.<G>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 ~IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""object C.<G>d__0.o"" IL_0018: ldloc.0 -IL_0019: ldc.i4.m1 -IL_001a: stfld ""int C.<G>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<C.<G>d__0>(ref C.<G>d__0)"" IL_002c: ldloc.0 IL_002d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0032: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0037: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void SwitchExpressionInsideAwait() { var source = @" using System.Threading.Tasks; class C { static async Task<object> G(Task<object> o) { return await o switch { int i => 0, _ => 1 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 56 (0x38) .maxstack 2 .locals init (C.<G>d__0 V_0) ~IL_0000: newobj ""C.<G>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 ~IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""System.Threading.Tasks.Task<object> C.<G>d__0.o"" IL_0018: ldloc.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<G>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<C.<G>d__0>(ref C.<G>d__0)"" IL_002c: ldloc.0 <IL_002d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0032: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0037: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void SwitchExpressionWithOutVar() { var source = @" class C { static object G() { return N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 73 (0x49) .maxstack 2 .locals init (int V_0, //x [int] V_1, [object] V_2, [int] V_3, [object] V_4, int V_5, object V_6, int V_7, object V_8) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: call ""object C.N(out int)"" IL_0008: stloc.s V_6 IL_000a: ldc.i4.1 IL_000b: brtrue.s IL_000e -IL_000d: nop ~IL_000e: ldloc.s V_6 IL_0010: brfalse.s IL_0014 IL_0012: br.s IL_0032 ~IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 -IL_0017: nop ~IL_0018: ldloc.0 IL_0019: ldc.i4.1 IL_001a: beq.s IL_001e IL_001c: br.s IL_0023 -IL_001e: ldc.i4.1 IL_001f: stloc.s V_7 IL_0021: br.s IL_0028 -IL_0023: ldc.i4.2 IL_0024: stloc.s V_7 IL_0026: br.s IL_0028 ~IL_0028: ldc.i4.1 IL_0029: brtrue.s IL_002c -IL_002b: nop -IL_002c: ldloc.s V_7 IL_002e: stloc.s V_5 IL_0030: br.s IL_0037 -IL_0032: ldc.i4.1 IL_0033: stloc.s V_5 IL_0035: br.s IL_0037 ~IL_0037: ldc.i4.1 IL_0038: brtrue.s IL_003b -IL_003a: nop ~IL_003b: ldloc.s V_5 IL_003d: box ""int"" IL_0042: stloc.s V_8 IL_0044: br.s IL_0046 -IL_0046: ldloc.s V_8 IL_0048: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ForEachStatement_Deconstruction() { var source = @" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (x, (y, z)) in F()) { System.Console.WriteLine(x); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) -IL_0000: nop -IL_0001: nop -IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 ~IL_000c: br.s IL_0045 -IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 -IL_0036: nop -IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop -IL_003e: nop ~IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 -IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e -IL_004d: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ComplexTypes() { var sourceText = @" using System; using System.Collections.Generic; class C1<T> { public enum E { A } } class C { public unsafe static void G() { var <N:0>a</N:0> = new { key = ""a"", value = new List<(int, int)>()}; var <N:1>b</N:1> = (number: 5, value: a); var <N:2>c</N:2> = new[] { b }; int[] <N:3>array</N:3> = { 1, 2, 3 }; ref int <N:4>d</N:4> = ref array[0]; ref readonly int <N:5>e</N:5> = ref array[0]; C1<(int, dynamic)>.E***[,,] <N:6>x</N:6> = null; var <N:7>f</N:7> = new List<string?>(); } } "; var source0 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source1 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source2 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithAllowUnsafe(true)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 88 (0x58) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_0035: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldc.i4.0 IL_003d: ldelema ""int"" IL_0042: stloc.s V_4 IL_0044: ldloc.3 IL_0045: ldc.i4.0 IL_0046: ldelema ""int"" IL_004b: stloc.s V_5 IL_004d: ldnull IL_004e: stloc.s V_6 IL_0050: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0055: stloc.s V_7 IL_0057: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 89 (0x59) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i4 IL_0033: dup IL_0034: ldc.i4.1 IL_0035: ldc.i4.2 IL_0036: stelem.i4 IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.3 IL_003a: stelem.i4 IL_003b: stloc.3 IL_003c: ldloc.3 IL_003d: ldc.i4.0 IL_003e: ldelema ""int"" IL_0043: stloc.s V_4 IL_0045: ldloc.3 IL_0046: ldc.i4.0 IL_0047: ldelema ""int"" IL_004c: stloc.s V_5 IL_004e: ldnull IL_004f: stloc.s V_6 IL_0051: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0056: stloc.s V_7 IL_0058: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 89 (0x59) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i4 IL_0033: dup IL_0034: ldc.i4.1 IL_0035: ldc.i4.2 IL_0036: stelem.i4 IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.3 IL_003a: stelem.i4 IL_003b: stloc.3 IL_003c: ldloc.3 IL_003d: ldc.i4.0 IL_003e: ldelema ""int"" IL_0043: stloc.s V_4 IL_0045: ldloc.3 IL_0046: ldc.i4.0 IL_0047: ldelema ""int"" IL_004c: stloc.s V_5 IL_004e: ldnull IL_004f: stloc.s V_6 IL_0051: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0056: stloc.s V_7 IL_0058: 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 System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader.Tools; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class LocalSlotMappingTests : EditAndContinueTestBase { /// <summary> /// If no changes were made we don't produce a syntax map. /// If we don't have syntax map and preserve variables is true we should still successfully map the locals to their previous slots. /// </summary> [Fact] public void SlotMappingWithNoChanges() { var source0 = @" using System; class C { static void Main(string[] args) { var b = true; do { Console.WriteLine(""hi""); } while (b == true); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source0); var v0 = CompileAndVerify(compilation0); var methodData0 = v0.TestData.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); v0.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0, //b bool V_1) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 -IL_0003: nop -IL_0004: ldstr ""hi"" IL_0009: call ""void System.Console.WriteLine(string)"" IL_000e: nop -IL_000f: nop -IL_0010: ldloc.0 IL_0011: stloc.1 ~IL_0012: ldloc.1 IL_0013: brtrue.s IL_0003 -IL_0015: ret }", sequencePoints: "C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, syntaxMap: null, preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0, //b bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: nop IL_0004: ldstr ""hi"" IL_0009: call ""void System.Console.WriteLine(string)"" IL_000e: nop IL_000f: nop IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: brtrue.s IL_0003 IL_0015: ret }"); } [Fact] public void OutOfOrderUserLocals() { var source = WithWindowsLineBreaks(@" using System; public class C { public static void M() { for (int i = 1; i < 1; i++) Console.WriteLine(1); for (int i = 1; i < 2; i++) Console.WriteLine(2); int j; for (j = 1; j < 3; j++) Console.WriteLine(3); } }"); var compilation0 = CreateCompilation(source, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 75 (0x4b) .maxstack 2 .locals init (int V_0, //j int V_1, //i bool V_2, int V_3, //i bool V_4, bool V_5) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: br.s IL_0010 IL_0005: ldc.i4.1 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: ldloc.1 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.1 IL_0012: clt IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: brtrue.s IL_0005 IL_0018: ldc.i4.1 IL_0019: stloc.3 IL_001a: br.s IL_0027 IL_001c: ldc.i4.2 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: ldloc.3 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.3 IL_0027: ldloc.3 IL_0028: ldc.i4.2 IL_0029: clt IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brtrue.s IL_001c IL_0031: ldc.i4.1 IL_0032: stloc.0 IL_0033: br.s IL_0040 IL_0035: ldc.i4.3 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldc.i4.1 IL_003e: add IL_003f: stloc.0 IL_0040: ldloc.0 IL_0041: ldc.i4.3 IL_0042: clt IL_0044: stloc.s V_5 IL_0046: ldloc.s V_5 IL_0048: brtrue.s IL_0035 IL_004a: ret } "); v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""135"" /> <slot kind=""0"" offset=""20"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""0"" offset=""79"" /> <slot kind=""1"" offset=""70"" /> <slot kind=""1"" offset=""147"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""14"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""58"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""32"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x10"" startLine=""8"" startColumn=""25"" endLine=""8"" endColumn=""30"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""37"" endLine=""9"" endColumn=""58"" document=""1"" /> <entry offset=""0x23"" startLine=""9"" startColumn=""32"" endLine=""9"" endColumn=""35"" document=""1"" /> <entry offset=""0x27"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x2d"" hidden=""true"" document=""1"" /> <entry offset=""0x31"" startLine=""12"" startColumn=""14"" endLine=""12"" endColumn=""19"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" startLine=""12"" startColumn=""33"" endLine=""12"" endColumn=""54"" document=""1"" /> <entry offset=""0x3c"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""31"" document=""1"" /> <entry offset=""0x40"" startLine=""12"" startColumn=""21"" endLine=""12"" endColumn=""26"" document=""1"" /> <entry offset=""0x46"" hidden=""true"" document=""1"" /> <entry offset=""0x4a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4b""> <namespace name=""System"" /> <local name=""j"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" /> <scope startOffset=""0x1"" endOffset=""0x18""> <local name=""i"" il_index=""1"" il_start=""0x1"" il_end=""0x18"" attributes=""0"" /> </scope> <scope startOffset=""0x18"" endOffset=""0x31""> <local name=""i"" il_index=""3"" il_start=""0x18"" il_end=""0x31"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); var symReader = v0.CreateSymReader(); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), symReader.GetEncMethodDebugInfo); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // check that all user-defined and long-lived synthesized local slots are reused diff1.VerifyIL("C.M", @" { // Code size 75 (0x4b) .maxstack 2 .locals init (int V_0, //j int V_1, //i bool V_2, int V_3, //i bool V_4, bool V_5) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: br.s IL_0010 IL_0005: ldc.i4.1 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: ldloc.1 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.1 IL_0012: clt IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: brtrue.s IL_0005 IL_0018: ldc.i4.1 IL_0019: stloc.3 IL_001a: br.s IL_0027 IL_001c: ldc.i4.2 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: ldloc.3 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.3 IL_0027: ldloc.3 IL_0028: ldc.i4.2 IL_0029: clt IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brtrue.s IL_001c IL_0031: ldc.i4.1 IL_0032: stloc.0 IL_0033: br.s IL_0040 IL_0035: ldc.i4.3 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldc.i4.1 IL_003e: add IL_003f: stloc.0 IL_0040: ldloc.0 IL_0041: ldc.i4.3 IL_0042: clt IL_0044: stloc.s V_5 IL_0046: ldloc.s V_5 IL_0048: brtrue.s IL_0035 IL_004a: ret } "); } /// <summary> /// Enc debug info is only present in debug builds. /// </summary> [Fact] public void DebugOnly() { var source = WithWindowsLineBreaks( @"class C { static System.IDisposable F() { return null; } static void M() { lock (F()) { } using (F()) { } } }"); var debug = CreateCompilation(source, options: TestOptions.DebugDll); var release = CreateCompilation(source, options: TestOptions.ReleaseDll); CompileAndVerify(debug).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""3"" offset=""11"" /> <slot kind=""2"" offset=""11"" /> <slot kind=""4"" offset=""35"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""21"" document=""1"" /> <entry offset=""0x13"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x20"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x27"" startLine=""10"" startColumn=""21"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0x28"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); CompileAndVerify(release).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""19"" document=""1"" /> <entry offset=""0x10"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x22"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x2d"" hidden=""true"" document=""1"" /> <entry offset=""0x2e"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void Using() { var source = WithWindowsLineBreaks( @"class C : System.IDisposable { public void Dispose() { } static System.IDisposable F() { return new C(); } static void M() { using (F()) { using (var u = F()) { } using (F()) { } } } }"); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), m => methodData0.GetEncDebugInfo()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 65 (0x41) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1, //u System.IDisposable V_2) IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: call ""System.IDisposable C.F()"" IL_000d: stloc.1 .try { IL_000e: nop IL_000f: nop IL_0010: leave.s IL_001d } finally { IL_0012: ldloc.1 IL_0013: brfalse.s IL_001c IL_0015: ldloc.1 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } IL_001d: call ""System.IDisposable C.F()"" IL_0022: stloc.2 .try { IL_0023: nop IL_0024: nop IL_0025: leave.s IL_0032 } finally { IL_0027: ldloc.2 IL_0028: brfalse.s IL_0031 IL_002a: ldloc.2 IL_002b: callvirt ""void System.IDisposable.Dispose()"" IL_0030: nop IL_0031: endfinally } IL_0032: nop IL_0033: leave.s IL_0040 } finally { IL_0035: ldloc.0 IL_0036: brfalse.s IL_003f IL_0038: ldloc.0 IL_0039: callvirt ""void System.IDisposable.Dispose()"" IL_003e: nop IL_003f: endfinally } IL_0040: ret }"); } [Fact] public void Lock() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { lock (F()) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 66 (0x42) .maxstack 2 .locals init (object V_0, bool V_1, object V_2, bool V_3) -IL_0000: nop -IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop -IL_0012: nop -IL_0013: call ""object C.F()"" IL_0018: stloc.2 IL_0019: ldc.i4.0 IL_001a: stloc.3 .try { IL_001b: ldloc.2 IL_001c: ldloca.s V_3 IL_001e: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0023: nop -IL_0024: nop -IL_0025: nop IL_0026: leave.s IL_0033 } finally { ~IL_0028: ldloc.3 IL_0029: brfalse.s IL_0032 IL_002b: ldloc.2 IL_002c: call ""void System.Threading.Monitor.Exit(object)"" IL_0031: nop ~IL_0032: endfinally } -IL_0033: nop IL_0034: leave.s IL_0041 } finally { ~IL_0036: ldloc.1 IL_0037: brfalse.s IL_0040 IL_0039: ldloc.0 IL_003a: call ""void System.Threading.Monitor.Exit(object)"" IL_003f: nop ~IL_0040: endfinally } -IL_0041: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Using Monitor.Enter(object). /// </summary> [Fact] public void Lock_Pre40() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { } } }"; var compilation0 = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { MscorlibRef_v20 }); var compilation1 = CreateEmptyCompilation(source, options: TestOptions.DebugDll, references: new[] { MscorlibRef_v20 }); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 27 (0x1b) .maxstack 1 .locals init (object V_0) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void System.Threading.Monitor.Enter(object)"" IL_000d: nop .try { IL_000e: nop IL_000f: nop IL_0010: leave.s IL_001a } finally { IL_0012: ldloc.0 IL_0013: call ""void System.Threading.Monitor.Exit(object)"" IL_0018: nop IL_0019: endfinally } IL_001a: ret }"); } [Fact] public void Fixed() { var source = @"class C { unsafe static void M(string s, int[] i) { fixed (char *p = s) { fixed (int *q = i) { } fixed (char *r = s) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 81 (0x51) .maxstack 2 .locals init (char* V_0, //p pinned string V_1, int* V_2, //q [unchanged] V_3, char* V_4, //r pinned string V_5, pinned int[] V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: conv.u IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0011 IL_0009: ldloc.0 IL_000a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_000f: add IL_0010: stloc.0 IL_0011: nop IL_0012: ldarg.1 IL_0013: dup IL_0014: stloc.s V_6 IL_0016: brfalse.s IL_001e IL_0018: ldloc.s V_6 IL_001a: ldlen IL_001b: conv.i4 IL_001c: brtrue.s IL_0023 IL_001e: ldc.i4.0 IL_001f: conv.u IL_0020: stloc.2 IL_0021: br.s IL_002d IL_0023: ldloc.s V_6 IL_0025: ldc.i4.0 IL_0026: ldelema ""int"" IL_002b: conv.u IL_002c: stloc.2 IL_002d: nop IL_002e: nop IL_002f: ldnull IL_0030: stloc.s V_6 IL_0032: ldarg.0 IL_0033: stloc.s V_5 IL_0035: ldloc.s V_5 IL_0037: conv.u IL_0038: stloc.s V_4 IL_003a: ldloc.s V_4 IL_003c: brfalse.s IL_0048 IL_003e: ldloc.s V_4 IL_0040: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_0045: add IL_0046: stloc.s V_4 IL_0048: nop IL_0049: nop IL_004a: ldnull IL_004b: stloc.s V_5 IL_004d: nop IL_004e: ldnull IL_004f: stloc.1 IL_0050: ret }"); } [WorkItem(770053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770053")] [Fact] public void FixedMultiple() { var source = @"class C { unsafe static void M(string s1, string s2, string s3, string s4) { fixed (char* p1 = s1, p2 = s2) { *p1 = *p2; } fixed (char* p1 = s1, p3 = s3, p2 = s4) { *p1 = *p2; *p2 = *p3; fixed (char *p4 = s2) { *p3 = *p4; } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.UnsafeDebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 166 (0xa6) .maxstack 2 .locals init (char* V_0, //p1 char* V_1, //p2 pinned string V_2, pinned string V_3, char* V_4, //p1 char* V_5, //p3 char* V_6, //p2 pinned string V_7, pinned string V_8, pinned string V_9, char* V_10, //p4 pinned string V_11) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.2 IL_0003: ldloc.2 IL_0004: conv.u IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0011 IL_0009: ldloc.0 IL_000a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_000f: add IL_0010: stloc.0 IL_0011: ldarg.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: conv.u IL_0015: stloc.1 IL_0016: ldloc.1 IL_0017: brfalse.s IL_0021 IL_0019: ldloc.1 IL_001a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_001f: add IL_0020: stloc.1 IL_0021: nop IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: ldind.u2 IL_0025: stind.i2 IL_0026: nop IL_0027: ldnull IL_0028: stloc.2 IL_0029: ldnull IL_002a: stloc.3 IL_002b: ldarg.0 IL_002c: stloc.s V_7 IL_002e: ldloc.s V_7 IL_0030: conv.u IL_0031: stloc.s V_4 IL_0033: ldloc.s V_4 IL_0035: brfalse.s IL_0041 IL_0037: ldloc.s V_4 IL_0039: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_003e: add IL_003f: stloc.s V_4 IL_0041: ldarg.2 IL_0042: stloc.s V_8 IL_0044: ldloc.s V_8 IL_0046: conv.u IL_0047: stloc.s V_5 IL_0049: ldloc.s V_5 IL_004b: brfalse.s IL_0057 IL_004d: ldloc.s V_5 IL_004f: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_0054: add IL_0055: stloc.s V_5 IL_0057: ldarg.3 IL_0058: stloc.s V_9 IL_005a: ldloc.s V_9 IL_005c: conv.u IL_005d: stloc.s V_6 IL_005f: ldloc.s V_6 IL_0061: brfalse.s IL_006d IL_0063: ldloc.s V_6 IL_0065: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_006a: add IL_006b: stloc.s V_6 IL_006d: nop IL_006e: ldloc.s V_4 IL_0070: ldloc.s V_6 IL_0072: ldind.u2 IL_0073: stind.i2 IL_0074: ldloc.s V_6 IL_0076: ldloc.s V_5 IL_0078: ldind.u2 IL_0079: stind.i2 IL_007a: ldarg.1 IL_007b: stloc.s V_11 IL_007d: ldloc.s V_11 IL_007f: conv.u IL_0080: stloc.s V_10 IL_0082: ldloc.s V_10 IL_0084: brfalse.s IL_0090 IL_0086: ldloc.s V_10 IL_0088: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get"" IL_008d: add IL_008e: stloc.s V_10 IL_0090: nop IL_0091: ldloc.s V_5 IL_0093: ldloc.s V_10 IL_0095: ldind.u2 IL_0096: stind.i2 IL_0097: nop IL_0098: ldnull IL_0099: stloc.s V_11 IL_009b: nop IL_009c: ldnull IL_009d: stloc.s V_7 IL_009f: ldnull IL_00a0: stloc.s V_8 IL_00a2: ldnull IL_00a3: stloc.s V_9 IL_00a5: ret } "); } [Fact] public void ForEach() { var source = @"using System.Collections; using System.Collections.Generic; class C { static IEnumerable F1() { return null; } static List<object> F2() { return null; } static IEnumerable F3() { return null; } static List<object> F4() { return null; } static void M() { foreach (var @x in F1()) { foreach (object y in F2()) { } } foreach (var x in F4()) { foreach (var y in F3()) { } foreach (var z in F2()) { } } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 272 (0x110) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, object V_1, //x System.Collections.Generic.List<object>.Enumerator V_2, object V_3, //y [unchanged] V_4, System.Collections.Generic.List<object>.Enumerator V_5, object V_6, //x System.Collections.IEnumerator V_7, object V_8, //y System.Collections.Generic.List<object>.Enumerator V_9, object V_10, //z System.IDisposable V_11) IL_0000: nop IL_0001: nop IL_0002: call ""System.Collections.IEnumerable C.F1()"" IL_0007: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_000c: stloc.0 .try { IL_000d: br.s IL_004a IL_000f: ldloc.0 IL_0010: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0015: stloc.1 IL_0016: nop IL_0017: nop IL_0018: call ""System.Collections.Generic.List<object> C.F2()"" IL_001d: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_0022: stloc.2 .try { IL_0023: br.s IL_002f IL_0025: ldloca.s V_2 IL_0027: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_002c: stloc.3 IL_002d: nop IL_002e: nop IL_002f: ldloca.s V_2 IL_0031: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_0036: brtrue.s IL_0025 IL_0038: leave.s IL_0049 } finally { IL_003a: ldloca.s V_2 IL_003c: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_0042: callvirt ""void System.IDisposable.Dispose()"" IL_0047: nop IL_0048: endfinally } IL_0049: nop IL_004a: ldloc.0 IL_004b: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0050: brtrue.s IL_000f IL_0052: leave.s IL_0069 } finally { IL_0054: ldloc.0 IL_0055: isinst ""System.IDisposable"" IL_005a: stloc.s V_11 IL_005c: ldloc.s V_11 IL_005e: brfalse.s IL_0068 IL_0060: ldloc.s V_11 IL_0062: callvirt ""void System.IDisposable.Dispose()"" IL_0067: nop IL_0068: endfinally } IL_0069: nop IL_006a: call ""System.Collections.Generic.List<object> C.F4()"" IL_006f: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_0074: stloc.s V_5 .try { IL_0076: br.s IL_00f2 IL_0078: ldloca.s V_5 IL_007a: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_007f: stloc.s V_6 IL_0081: nop IL_0082: nop IL_0083: call ""System.Collections.IEnumerable C.F3()"" IL_0088: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_008d: stloc.s V_7 .try { IL_008f: br.s IL_009c IL_0091: ldloc.s V_7 IL_0093: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0098: stloc.s V_8 IL_009a: nop IL_009b: nop IL_009c: ldloc.s V_7 IL_009e: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_00a3: brtrue.s IL_0091 IL_00a5: leave.s IL_00bd } finally { IL_00a7: ldloc.s V_7 IL_00a9: isinst ""System.IDisposable"" IL_00ae: stloc.s V_11 IL_00b0: ldloc.s V_11 IL_00b2: brfalse.s IL_00bc IL_00b4: ldloc.s V_11 IL_00b6: callvirt ""void System.IDisposable.Dispose()"" IL_00bb: nop IL_00bc: endfinally } IL_00bd: nop IL_00be: call ""System.Collections.Generic.List<object> C.F2()"" IL_00c3: callvirt ""System.Collections.Generic.List<object>.Enumerator System.Collections.Generic.List<object>.GetEnumerator()"" IL_00c8: stloc.s V_9 .try { IL_00ca: br.s IL_00d7 IL_00cc: ldloca.s V_9 IL_00ce: call ""object System.Collections.Generic.List<object>.Enumerator.Current.get"" IL_00d3: stloc.s V_10 IL_00d5: nop IL_00d6: nop IL_00d7: ldloca.s V_9 IL_00d9: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_00de: brtrue.s IL_00cc IL_00e0: leave.s IL_00f1 } finally { IL_00e2: ldloca.s V_9 IL_00e4: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_00ea: callvirt ""void System.IDisposable.Dispose()"" IL_00ef: nop IL_00f0: endfinally } IL_00f1: nop IL_00f2: ldloca.s V_5 IL_00f4: call ""bool System.Collections.Generic.List<object>.Enumerator.MoveNext()"" IL_00f9: brtrue IL_0078 IL_00fe: leave.s IL_010f } finally { IL_0100: ldloca.s V_5 IL_0102: constrained. ""System.Collections.Generic.List<object>.Enumerator"" IL_0108: callvirt ""void System.IDisposable.Dispose()"" IL_010d: nop IL_010e: endfinally } IL_010f: ret }"); } [Fact] public void ForEachArray1() { var source = @"class C { static void M(double[,,] c) { foreach (var x in c) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 111 (0x6f) .maxstack 4 .locals init (double[,,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, int V_6, double V_7) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: callvirt ""int System.Array.GetUpperBound(int)"" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: callvirt ""int System.Array.GetUpperBound(int)"" IL_0013: stloc.2 IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: callvirt ""int System.Array.GetUpperBound(int)"" IL_001b: stloc.3 IL_001c: ldloc.0 IL_001d: ldc.i4.0 IL_001e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0023: stloc.s V_4 ~IL_0025: br.s IL_0069 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: callvirt ""int System.Array.GetLowerBound(int)"" IL_002e: stloc.s V_5 ~IL_0030: br.s IL_005e IL_0032: ldloc.0 IL_0033: ldc.i4.2 IL_0034: callvirt ""int System.Array.GetLowerBound(int)"" IL_0039: stloc.s V_6 ~IL_003b: br.s IL_0053 -IL_003d: ldloc.0 IL_003e: ldloc.s V_4 IL_0040: ldloc.s V_5 IL_0042: ldloc.s V_6 IL_0044: call ""double[*,*,*].Get"" IL_0049: stloc.s V_7 -IL_004b: nop -IL_004c: nop ~IL_004d: ldloc.s V_6 IL_004f: ldc.i4.1 IL_0050: add IL_0051: stloc.s V_6 -IL_0053: ldloc.s V_6 IL_0055: ldloc.3 IL_0056: ble.s IL_003d ~IL_0058: ldloc.s V_5 IL_005a: ldc.i4.1 IL_005b: add IL_005c: stloc.s V_5 -IL_005e: ldloc.s V_5 IL_0060: ldloc.2 IL_0061: ble.s IL_0032 ~IL_0063: ldloc.s V_4 IL_0065: ldc.i4.1 IL_0066: add IL_0067: stloc.s V_4 -IL_0069: ldloc.s V_4 IL_006b: ldloc.1 IL_006c: ble.s IL_0027 -IL_006e: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 111 (0x6f) .maxstack 4 .locals init (double[,,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5, int V_6, double V_7) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: callvirt ""int System.Array.GetUpperBound(int)"" IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: callvirt ""int System.Array.GetUpperBound(int)"" IL_0013: stloc.2 IL_0014: ldloc.0 IL_0015: ldc.i4.2 IL_0016: callvirt ""int System.Array.GetUpperBound(int)"" IL_001b: stloc.3 IL_001c: ldloc.0 IL_001d: ldc.i4.0 IL_001e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0023: stloc.s V_4 ~IL_0025: br.s IL_0069 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: callvirt ""int System.Array.GetLowerBound(int)"" IL_002e: stloc.s V_5 ~IL_0030: br.s IL_005e IL_0032: ldloc.0 IL_0033: ldc.i4.2 IL_0034: callvirt ""int System.Array.GetLowerBound(int)"" IL_0039: stloc.s V_6 ~IL_003b: br.s IL_0053 -IL_003d: ldloc.0 IL_003e: ldloc.s V_4 IL_0040: ldloc.s V_5 IL_0042: ldloc.s V_6 IL_0044: call ""double[*,*,*].Get"" IL_0049: stloc.s V_7 -IL_004b: nop -IL_004c: nop ~IL_004d: ldloc.s V_6 IL_004f: ldc.i4.1 IL_0050: add IL_0051: stloc.s V_6 -IL_0053: ldloc.s V_6 IL_0055: ldloc.3 IL_0056: ble.s IL_003d ~IL_0058: ldloc.s V_5 IL_005a: ldc.i4.1 IL_005b: add IL_005c: stloc.s V_5 -IL_005e: ldloc.s V_5 IL_0060: ldloc.2 IL_0061: ble.s IL_0032 ~IL_0063: ldloc.s V_4 IL_0065: ldc.i4.1 IL_0066: add IL_0067: stloc.s V_4 -IL_0069: ldloc.s V_4 IL_006b: ldloc.1 IL_006c: ble.s IL_0027 -IL_006e: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ForEachArray2() { var source = @"class C { static void M(string a, object[] b, double[,,] c) { foreach (var x in a) { foreach (var y in b) { } } foreach (var x in c) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 184 (0xb8) .maxstack 4 .locals init (string V_0, int V_1, char V_2, //x object[] V_3, int V_4, object V_5, //y double[,,] V_6, int V_7, int V_8, int V_9, int V_10, int V_11, int V_12, double V_13) //x IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: stloc.0 IL_0004: ldc.i4.0 IL_0005: stloc.1 IL_0006: br.s IL_0033 IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: callvirt ""char string.this[int].get"" IL_000f: stloc.2 IL_0010: nop IL_0011: nop IL_0012: ldarg.1 IL_0013: stloc.3 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0027 IL_0019: ldloc.3 IL_001a: ldloc.s V_4 IL_001c: ldelem.ref IL_001d: stloc.s V_5 IL_001f: nop IL_0020: nop IL_0021: ldloc.s V_4 IL_0023: ldc.i4.1 IL_0024: add IL_0025: stloc.s V_4 IL_0027: ldloc.s V_4 IL_0029: ldloc.3 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0019 IL_002e: nop IL_002f: ldloc.1 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.1 IL_0033: ldloc.1 IL_0034: ldloc.0 IL_0035: callvirt ""int string.Length.get"" IL_003a: blt.s IL_0008 IL_003c: nop IL_003d: ldarg.2 IL_003e: stloc.s V_6 IL_0040: ldloc.s V_6 IL_0042: ldc.i4.0 IL_0043: callvirt ""int System.Array.GetUpperBound(int)"" IL_0048: stloc.s V_7 IL_004a: ldloc.s V_6 IL_004c: ldc.i4.1 IL_004d: callvirt ""int System.Array.GetUpperBound(int)"" IL_0052: stloc.s V_8 IL_0054: ldloc.s V_6 IL_0056: ldc.i4.2 IL_0057: callvirt ""int System.Array.GetUpperBound(int)"" IL_005c: stloc.s V_9 IL_005e: ldloc.s V_6 IL_0060: ldc.i4.0 IL_0061: callvirt ""int System.Array.GetLowerBound(int)"" IL_0066: stloc.s V_10 IL_0068: br.s IL_00b1 IL_006a: ldloc.s V_6 IL_006c: ldc.i4.1 IL_006d: callvirt ""int System.Array.GetLowerBound(int)"" IL_0072: stloc.s V_11 IL_0074: br.s IL_00a5 IL_0076: ldloc.s V_6 IL_0078: ldc.i4.2 IL_0079: callvirt ""int System.Array.GetLowerBound(int)"" IL_007e: stloc.s V_12 IL_0080: br.s IL_0099 IL_0082: ldloc.s V_6 IL_0084: ldloc.s V_10 IL_0086: ldloc.s V_11 IL_0088: ldloc.s V_12 IL_008a: call ""double[*,*,*].Get"" IL_008f: stloc.s V_13 IL_0091: nop IL_0092: nop IL_0093: ldloc.s V_12 IL_0095: ldc.i4.1 IL_0096: add IL_0097: stloc.s V_12 IL_0099: ldloc.s V_12 IL_009b: ldloc.s V_9 IL_009d: ble.s IL_0082 IL_009f: ldloc.s V_11 IL_00a1: ldc.i4.1 IL_00a2: add IL_00a3: stloc.s V_11 IL_00a5: ldloc.s V_11 IL_00a7: ldloc.s V_8 IL_00a9: ble.s IL_0076 IL_00ab: ldloc.s V_10 IL_00ad: ldc.i4.1 IL_00ae: add IL_00af: stloc.s V_10 IL_00b1: ldloc.s V_10 IL_00b3: ldloc.s V_7 IL_00b5: ble.s IL_006a IL_00b7: ret }"); } /// <summary> /// Unlike Dev12 we can handle array with more than 256 dimensions. /// </summary> [Fact] public void ForEachArray_ToManyDimensions() { var source = @"class C { static void M(object o) { foreach (var x in (object[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,])o) { } } }"; // Make sure the source contains an array with too many dimensions. var tooManyCommas = new string(',', 256); Assert.True(source.IndexOf(tooManyCommas, StringComparison.Ordinal) > 0); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); } [Fact] public void ForEachWithDynamicAndTuple() { var source = @"class C { static void M((dynamic, int) t) { foreach (var o in t.Item1) { } } }"; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 119 (0x77) .maxstack 3 .locals init (System.Collections.IEnumerator V_0, object V_1, //o [unchanged] V_2, System.IDisposable V_3) IL_0000: nop IL_0001: nop IL_0002: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_0007: brfalse.s IL_000b IL_0009: br.s IL_002f IL_000b: ldc.i4.0 IL_000c: ldtoken ""System.Collections.IEnumerable"" IL_0011: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0016: ldtoken ""C"" IL_001b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0020: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0025: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_002a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_002f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_0034: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>>.Target"" IL_0039: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>> C.<>o__0#1.<>p__0"" IL_003e: ldarg.0 IL_003f: ldfld ""dynamic System.ValueTuple<dynamic, int>.Item1"" IL_0044: callvirt ""System.Collections.IEnumerable System.Func<System.Runtime.CompilerServices.CallSite, dynamic, System.Collections.IEnumerable>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0049: callvirt ""System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()"" IL_004e: stloc.0 .try { IL_004f: br.s IL_005a IL_0051: ldloc.0 IL_0052: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0057: stloc.1 IL_0058: nop IL_0059: nop IL_005a: ldloc.0 IL_005b: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_0060: brtrue.s IL_0051 IL_0062: leave.s IL_0076 } finally { IL_0064: ldloc.0 IL_0065: isinst ""System.IDisposable"" IL_006a: stloc.3 IL_006b: ldloc.3 IL_006c: brfalse.s IL_0075 IL_006e: ldloc.3 IL_006f: callvirt ""void System.IDisposable.Dispose()"" IL_0074: nop IL_0075: endfinally } IL_0076: ret }"); } [Fact] public void RemoveRestoreNullableAtArrayElement() { var source0 = MarkedSource( @"using System; class C { public static void M() { var <N:1>arr</N:1> = new string?[] { ""0"" }; <N:0>foreach</N:0> (var s in arr) { Console.WriteLine(1); } } }"); // Remove nullable var source1 = MarkedSource( @"using System; class C { public static void M() { var <N:1>arr</N:1> = new string[] { ""0"" }; <N:0>foreach</N:0> (var s in arr) { Console.WriteLine(1); } } }"); // Restore nullable var source2 = source0; var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: nop IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_0028 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: nop IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 IL_002e: ret }"); var compilation1 = CreateCompilation(source1.Tree, options: TestOptions.DebugDll); var compilation2 = compilation0.WithSource(source2.Tree); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 IL_0010: nop IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_0028 IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 IL_001b: nop IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop IL_0023: nop IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 IL_002e: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 47 (0x2f) .maxstack 4 .locals init (string[] V_0, //arr string[] V_1, int V_2, string V_3) //s -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: newarr ""string"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldstr ""0"" IL_000e: stelem.ref IL_000f: stloc.0 -IL_0010: nop -IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 ~IL_0015: br.s IL_0028 -IL_0017: ldloc.1 IL_0018: ldloc.2 IL_0019: ldelem.ref IL_001a: stloc.3 -IL_001b: nop -IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(int)"" IL_0022: nop -IL_0023: nop ~IL_0024: ldloc.2 IL_0025: ldc.i4.1 IL_0026: add IL_0027: stloc.2 -IL_0028: ldloc.2 IL_0029: ldloc.1 IL_002a: ldlen IL_002b: conv.i4 IL_002c: blt.s IL_0017 -IL_002e: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void AddAndDelete() { var source0 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { lock (F1()) { } foreach (var c in F2()) { } using (F3()) { } } }"; // Delete one statement. var source1 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { lock (F1()) { } foreach (var c in F2()) { } } }"; // Add statement with same temp kind. var source2 = @"class C { static object F1() { return null; } static string F2() { return null; } static System.IDisposable F3() { return null; } static void M() { using (F3()) { } lock (F1()) { } foreach (var c in F2()) { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 93 (0x5d) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c System.IDisposable V_5) IL_0000: nop IL_0001: call ""object C.F1()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: nop IL_0022: call ""string C.F2()"" IL_0027: stloc.2 IL_0028: ldc.i4.0 IL_0029: stloc.3 IL_002a: br.s IL_003b IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: callvirt ""char string.this[int].get"" IL_0033: stloc.s V_4 IL_0035: nop IL_0036: nop IL_0037: ldloc.3 IL_0038: ldc.i4.1 IL_0039: add IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldloc.2 IL_003d: callvirt ""int string.Length.get"" IL_0042: blt.s IL_002c IL_0044: call ""System.IDisposable C.F3()"" IL_0049: stloc.s V_5 .try { IL_004b: nop IL_004c: nop IL_004d: leave.s IL_005c } finally { IL_004f: ldloc.s V_5 IL_0051: brfalse.s IL_005b IL_0053: ldloc.s V_5 IL_0055: callvirt ""void System.IDisposable.Dispose()"" IL_005a: nop IL_005b: endfinally } IL_005c: ret }"); var compilation1 = CreateCompilation(source1, options: TestOptions.DebugDll); var compilation2 = compilation0.WithSource(source2); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 69 (0x45) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c [unchanged] V_5) IL_0000: nop IL_0001: call ""object C.F1()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: nop IL_0022: call ""string C.F2()"" IL_0027: stloc.2 IL_0028: ldc.i4.0 IL_0029: stloc.3 IL_002a: br.s IL_003b IL_002c: ldloc.2 IL_002d: ldloc.3 IL_002e: callvirt ""char string.this[int].get"" IL_0033: stloc.s V_4 IL_0035: nop IL_0036: nop IL_0037: ldloc.3 IL_0038: ldc.i4.1 IL_0039: add IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldloc.2 IL_003d: callvirt ""int string.Length.get"" IL_0042: blt.s IL_002c IL_0044: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 93 (0x5d) .maxstack 2 .locals init (object V_0, bool V_1, string V_2, int V_3, char V_4, //c [unchanged] V_5, System.IDisposable V_6) -IL_0000: nop -IL_0001: call ""System.IDisposable C.F3()"" IL_0006: stloc.s V_6 .try { -IL_0008: nop -IL_0009: nop IL_000a: leave.s IL_0019 } finally { ~IL_000c: ldloc.s V_6 IL_000e: brfalse.s IL_0018 IL_0010: ldloc.s V_6 IL_0012: callvirt ""void System.IDisposable.Dispose()"" IL_0017: nop ~IL_0018: endfinally } -IL_0019: call ""object C.F1()"" IL_001e: stloc.0 IL_001f: ldc.i4.0 IL_0020: stloc.1 .try { IL_0021: ldloc.0 IL_0022: ldloca.s V_1 IL_0024: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0029: nop -IL_002a: nop -IL_002b: nop IL_002c: leave.s IL_0039 } finally { ~IL_002e: ldloc.1 IL_002f: brfalse.s IL_0038 IL_0031: ldloc.0 IL_0032: call ""void System.Threading.Monitor.Exit(object)"" IL_0037: nop ~IL_0038: endfinally } -IL_0039: nop -IL_003a: call ""string C.F2()"" IL_003f: stloc.2 IL_0040: ldc.i4.0 IL_0041: stloc.3 ~IL_0042: br.s IL_0053 -IL_0044: ldloc.2 IL_0045: ldloc.3 IL_0046: callvirt ""char string.this[int].get"" IL_004b: stloc.s V_4 -IL_004d: nop -IL_004e: nop ~IL_004f: ldloc.3 IL_0050: ldc.i4.1 IL_0051: add IL_0052: stloc.3 -IL_0053: ldloc.3 IL_0054: ldloc.2 IL_0055: callvirt ""int string.Length.get"" IL_005a: blt.s IL_0044 -IL_005c: ret }", methodToken: diff2.EmitResult.UpdatedMethods.Single()); } [Fact] public void Insert() { var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } static void M() { lock (F1()) { } lock (F2()) { } } }"; var source1 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } static void M() { lock (F3()) { } // added lock (F1()) { } lock (F4()) { } // replaced } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Note that the order of unique ids in temporaries follows the // order of declaration in the updated method. Specifically, the // original temporary names (and unique ids) are not preserved. // (Should not be an issue since the names are used by EnC only.) diff1.VerifyIL("C.M", @"{ // Code size 108 (0x6c) .maxstack 2 .locals init (object V_0, bool V_1, [object] V_2, [bool] V_3, object V_4, bool V_5, object V_6, bool V_7) IL_0000: nop IL_0001: call ""object C.F3()"" IL_0006: stloc.s V_4 IL_0008: ldc.i4.0 IL_0009: stloc.s V_5 .try { IL_000b: ldloc.s V_4 IL_000d: ldloca.s V_5 IL_000f: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0014: nop IL_0015: nop IL_0016: nop IL_0017: leave.s IL_0026 } finally { IL_0019: ldloc.s V_5 IL_001b: brfalse.s IL_0025 IL_001d: ldloc.s V_4 IL_001f: call ""void System.Threading.Monitor.Exit(object)"" IL_0024: nop IL_0025: endfinally } IL_0026: call ""object C.F1()"" IL_002b: stloc.0 IL_002c: ldc.i4.0 IL_002d: stloc.1 .try { IL_002e: ldloc.0 IL_002f: ldloca.s V_1 IL_0031: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0036: nop IL_0037: nop IL_0038: nop IL_0039: leave.s IL_0046 } finally { IL_003b: ldloc.1 IL_003c: brfalse.s IL_0045 IL_003e: ldloc.0 IL_003f: call ""void System.Threading.Monitor.Exit(object)"" IL_0044: nop IL_0045: endfinally } IL_0046: call ""object C.F4()"" IL_004b: stloc.s V_6 IL_004d: ldc.i4.0 IL_004e: stloc.s V_7 .try { IL_0050: ldloc.s V_6 IL_0052: ldloca.s V_7 IL_0054: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0059: nop IL_005a: nop IL_005b: nop IL_005c: leave.s IL_006b } finally { IL_005e: ldloc.s V_7 IL_0060: brfalse.s IL_006a IL_0062: ldloc.s V_6 IL_0064: call ""void System.Threading.Monitor.Exit(object)"" IL_0069: nop IL_006a: endfinally } IL_006b: ret }"); } /// <summary> /// Should not reuse temporary locals /// having different temporary kinds. /// </summary> [Fact] public void NoReuseDifferentTempKind() { var source = @"class A : System.IDisposable { public object Current { get { return null; } } public bool MoveNext() { return false; } public void Dispose() { } internal int this[A a] { get { return 0; } set { } } } class B { public A GetEnumerator() { return null; } } class C { static A F() { return null; } static B G() { return null; } static void M(A a) { a[F()]++; using (F()) { } lock (F()) { } foreach (var o in G()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 137 (0x89) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, A V_2, A V_3, bool V_4, A V_5, object V_6, //o A V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""A C.F()"" IL_0007: stloc.s V_7 IL_0009: dup IL_000a: ldloc.s V_7 IL_000c: callvirt ""int A.this[A].get"" IL_0011: stloc.s V_8 IL_0013: ldloc.s V_7 IL_0015: ldloc.s V_8 IL_0017: ldc.i4.1 IL_0018: add IL_0019: callvirt ""void A.this[A].set"" IL_001e: nop IL_001f: call ""A C.F()"" IL_0024: stloc.2 .try { IL_0025: nop IL_0026: nop IL_0027: leave.s IL_0034 } finally { IL_0029: ldloc.2 IL_002a: brfalse.s IL_0033 IL_002c: ldloc.2 IL_002d: callvirt ""void System.IDisposable.Dispose()"" IL_0032: nop IL_0033: endfinally } IL_0034: call ""A C.F()"" IL_0039: stloc.3 IL_003a: ldc.i4.0 IL_003b: stloc.s V_4 .try { IL_003d: ldloc.3 IL_003e: ldloca.s V_4 IL_0040: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0045: nop IL_0046: nop IL_0047: nop IL_0048: leave.s IL_0056 } finally { IL_004a: ldloc.s V_4 IL_004c: brfalse.s IL_0055 IL_004e: ldloc.3 IL_004f: call ""void System.Threading.Monitor.Exit(object)"" IL_0054: nop IL_0055: endfinally } IL_0056: nop IL_0057: call ""B C.G()"" IL_005c: callvirt ""A B.GetEnumerator()"" IL_0061: stloc.s V_5 .try { IL_0063: br.s IL_0070 IL_0065: ldloc.s V_5 IL_0067: callvirt ""object A.Current.get"" IL_006c: stloc.s V_6 IL_006e: nop IL_006f: nop IL_0070: ldloc.s V_5 IL_0072: callvirt ""bool A.MoveNext()"" IL_0077: brtrue.s IL_0065 IL_0079: leave.s IL_0088 } finally { IL_007b: ldloc.s V_5 IL_007d: brfalse.s IL_0087 IL_007f: ldloc.s V_5 IL_0081: callvirt ""void System.IDisposable.Dispose()"" IL_0086: nop IL_0087: endfinally } IL_0088: ret }"); } [Fact] public void Switch_String() { var source0 = @"class C { static string F() { return null; } static void M() { switch (F()) { case ""a"": System.Console.WriteLine(1); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var source1 = @"class C { static string F() { return null; } static void M() { switch (F()) { case ""a"": System.Console.WriteLine(10); break; case ""b"": System.Console.WriteLine(20); break; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); // Validate presence of a hidden sequence point @IL_0007 that is required for proper function remapping. v0.VerifyIL("C.M", @" { // Code size 56 (0x38) .maxstack 2 .locals init (string V_0, string V_1) -IL_0000: nop -IL_0001: call ""string C.F()"" IL_0006: stloc.1 ~IL_0007: ldloc.1 IL_0008: stloc.0 ~IL_0009: ldloc.0 IL_000a: ldstr ""a"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldstr ""b"" IL_001c: call ""bool string.op_Equality(string, string)"" IL_0021: brtrue.s IL_002e IL_0023: br.s IL_0037 -IL_0025: ldc.i4.1 IL_0026: call ""void System.Console.WriteLine(int)"" IL_002b: nop -IL_002c: br.s IL_0037 -IL_002e: ldc.i4.2 IL_002f: call ""void System.Console.WriteLine(int)"" IL_0034: nop -IL_0035: br.s IL_0037 -IL_0037: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.SwitchStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0, string V_1) -IL_0000: nop -IL_0001: call ""string C.F()"" IL_0006: stloc.1 ~IL_0007: ldloc.1 IL_0008: stloc.0 ~IL_0009: ldloc.0 IL_000a: ldstr ""a"" IL_000f: call ""bool string.op_Equality(string, string)"" IL_0014: brtrue.s IL_0025 IL_0016: ldloc.0 IL_0017: ldstr ""b"" IL_001c: call ""bool string.op_Equality(string, string)"" IL_0021: brtrue.s IL_002f IL_0023: br.s IL_0039 -IL_0025: ldc.i4.s 10 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop -IL_002d: br.s IL_0039 -IL_002f: ldc.i4.s 20 IL_0031: call ""void System.Console.WriteLine(int)"" IL_0036: nop -IL_0037: br.s IL_0039 -IL_0039: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Switch_Integer() { var source0 = WithWindowsLineBreaks( @"class C { static int F() { return 1; } static void M() { switch (F()) { case 1: System.Console.WriteLine(1); break; case 2: System.Console.WriteLine(2); break; } } }"); var source1 = WithWindowsLineBreaks( @"class C { static int F() { return 1; } static void M() { switch (F()) { case 1: System.Console.WriteLine(10); break; case 2: System.Console.WriteLine(20); break; } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 40 (0x28) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: call ""int C.F()"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: ldc.i4.1 IL_000b: beq.s IL_0015 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ldc.i4.2 IL_0011: beq.s IL_001e IL_0013: br.s IL_0027 IL_0015: ldc.i4.1 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: br.s IL_0027 IL_001e: ldc.i4.2 IL_001f: call ""void System.Console.WriteLine(int)"" IL_0024: nop IL_0025: br.s IL_0027 IL_0027: ret }"); // Validate that we emit a hidden sequence point @IL_0007. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""21"" endLine=""9"" endColumn=""49"" document=""1"" /> <entry offset=""0x1c"" startLine=""9"" startColumn=""50"" endLine=""9"" endColumn=""56"" document=""1"" /> <entry offset=""0x1e"" startLine=""10"" startColumn=""21"" endLine=""10"" endColumn=""49"" document=""1"" /> <entry offset=""0x25"" startLine=""10"" startColumn=""50"" endLine=""10"" endColumn=""56"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.SwitchStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0, int V_1) IL_0000: nop IL_0001: call ""int C.F()"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: ldc.i4.1 IL_000b: beq.s IL_0015 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ldc.i4.2 IL_0011: beq.s IL_001f IL_0013: br.s IL_0029 IL_0015: ldc.i4.s 10 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: br.s IL_0029 IL_001f: ldc.i4.s 20 IL_0021: call ""void System.Console.WriteLine(int)"" IL_0026: nop IL_0027: br.s IL_0029 IL_0029: ret }"); } [Fact] public void Switch_Patterns() { var source = WithWindowsLineBreaks(@" using static System.Console; class C { static object F() => 1; static bool P() => false; static void M() { switch (F()) { case 1: WriteLine(""int 1""); break; case byte b when P(): WriteLine(b); break; case int i when P(): WriteLine(i); break; case (byte)1: WriteLine(""byte 1""); break; case int j: WriteLine(j); break; case object o: WriteLine(o); break; } } }"); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""0"" offset=""106"" /> <slot kind=""0"" offset=""162"" /> <slot kind=""0"" offset=""273"" /> <slot kind=""0"" offset=""323"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>", options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints); v0.VerifyIL("C.M", @" { // Code size 147 (0x93) .maxstack 2 .locals init (byte V_0, //b int V_1, //i int V_2, //j object V_3, //o object V_4) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.s V_4 IL_0008: ldloc.s V_4 IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: isinst ""int"" IL_0011: brfalse.s IL_0020 IL_0013: ldloc.3 IL_0014: unbox.any ""int"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: beq.s IL_003c IL_001e: br.s IL_005b IL_0020: ldloc.3 IL_0021: isinst ""byte"" IL_0026: brfalse.s IL_0037 IL_0028: ldloc.3 IL_0029: unbox.any ""byte"" IL_002e: stloc.0 IL_002f: br.s IL_0049 IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: beq.s IL_006d IL_0035: br.s IL_0087 IL_0037: ldloc.3 IL_0038: brtrue.s IL_0087 IL_003a: br.s IL_0092 IL_003c: ldstr ""int 1"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: nop IL_0047: br.s IL_0092 IL_0049: call ""bool C.P()"" IL_004e: brtrue.s IL_0052 IL_0050: br.s IL_0031 IL_0052: ldloc.0 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: br.s IL_0092 IL_005b: call ""bool C.P()"" IL_0060: brtrue.s IL_0064 IL_0062: br.s IL_007a IL_0064: ldloc.1 IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: br.s IL_0092 IL_006d: ldstr ""byte 1"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: nop IL_0078: br.s IL_0092 IL_007a: ldloc.1 IL_007b: stloc.2 IL_007c: br.s IL_007e IL_007e: ldloc.2 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop IL_0085: br.s IL_0092 IL_0087: br.s IL_0089 IL_0089: ldloc.3 IL_008a: call ""void System.Console.WriteLine(object)"" IL_008f: nop IL_0090: br.s IL_0092 IL_0092: ret }"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 147 (0x93) .maxstack 2 .locals init (byte V_0, //b int V_1, //i int V_2, //j object V_3, //o object V_4) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.s V_4 IL_0008: ldloc.s V_4 IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: isinst ""int"" IL_0011: brfalse.s IL_0020 IL_0013: ldloc.3 IL_0014: unbox.any ""int"" IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: beq.s IL_003c IL_001e: br.s IL_005b IL_0020: ldloc.3 IL_0021: isinst ""byte"" IL_0026: brfalse.s IL_0037 IL_0028: ldloc.3 IL_0029: unbox.any ""byte"" IL_002e: stloc.0 IL_002f: br.s IL_0049 IL_0031: ldloc.0 IL_0032: ldc.i4.1 IL_0033: beq.s IL_006d IL_0035: br.s IL_0087 IL_0037: ldloc.3 IL_0038: brtrue.s IL_0087 IL_003a: br.s IL_0092 IL_003c: ldstr ""int 1"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: nop IL_0047: br.s IL_0092 IL_0049: call ""bool C.P()"" IL_004e: brtrue.s IL_0052 IL_0050: br.s IL_0031 IL_0052: ldloc.0 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: br.s IL_0092 IL_005b: call ""bool C.P()"" IL_0060: brtrue.s IL_0064 IL_0062: br.s IL_007a IL_0064: ldloc.1 IL_0065: call ""void System.Console.WriteLine(int)"" IL_006a: nop IL_006b: br.s IL_0092 IL_006d: ldstr ""byte 1"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: nop IL_0078: br.s IL_0092 IL_007a: ldloc.1 IL_007b: stloc.2 IL_007c: br.s IL_007e IL_007e: ldloc.2 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop IL_0085: br.s IL_0092 IL_0087: br.s IL_0089 IL_0089: ldloc.3 IL_008a: call ""void System.Console.WriteLine(object)"" IL_008f: nop IL_0090: br.s IL_0092 IL_0092: ret }"); } [Fact] public void If() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { if (F()) { System.Console.WriteLine(1); } } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { if (F()) { System.Console.WriteLine(10); } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: call ""bool C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0013 IL_000a: nop IL_000b: ldc.i4.1 IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: nop IL_0012: nop IL_0013: ret } "); // Validate presence of a hidden sequence point @IL_0007 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x12"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.IfStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 21 (0x15) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: call ""bool C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0014 IL_000a: nop IL_000b: ldc.i4.s 10 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: nop IL_0014: ret }"); } [Fact] public void While() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { while (F()) { System.Console.WriteLine(1); } } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { while (F()) { System.Console.WriteLine(10); } } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: br.s IL_000c IL_0003: nop IL_0004: ldc.i4.1 IL_0005: call ""void System.Console.WriteLine(int)"" IL_000a: nop IL_000b: nop IL_000c: call ""bool C.F()"" IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: brtrue.s IL_0003 IL_0015: ret } "); // Validate presence of a hidden sequence point @IL_0012 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0xb"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""20"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.WhileStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: br.s IL_000d IL_0003: nop IL_0004: ldc.i4.s 10 IL_0006: call ""void System.Console.WriteLine(int)"" IL_000b: nop IL_000c: nop IL_000d: call ""bool C.F()"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: brtrue.s IL_0003 IL_0016: ret }"); } [Fact] public void Do1() { var source0 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { do { System.Console.WriteLine(1); } while (F()); } }"); var source1 = WithWindowsLineBreaks(@" class C { static bool F() { return true; } static void M() { do { System.Console.WriteLine(10); } while (F()); } }"); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: nop IL_0002: ldc.i4.1 IL_0003: call ""void System.Console.WriteLine(int)"" IL_0008: nop IL_0009: nop IL_000a: call ""bool C.F()"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: brtrue.s IL_0001 IL_0013: ret }"); // Validate presence of a hidden sequence point @IL_0010 that is required for proper function remapping. v0.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x9"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""21"" document=""1"" /> <entry offset=""0x10"" hidden=""true"" document=""1"" /> <entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.DoStatement), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 21 (0x15) .maxstack 1 .locals init (bool V_0) IL_0000: nop IL_0001: nop IL_0002: ldc.i4.s 10 IL_0004: call ""void System.Console.WriteLine(int)"" IL_0009: nop IL_000a: nop IL_000b: call ""bool C.F()"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: brtrue.s IL_0001 IL_0014: ret }"); } [Fact] public void For() { var source0 = @" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(1); } } }"; var source1 = @" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(10); } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var v0 = CompileAndVerify(compilation0); // Validate presence of a hidden sequence point @IL_001c that is required for proper function remapping. v0.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 1 .locals init (int V_0, //i bool V_1) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 ~IL_0003: br.s IL_0015 -IL_0005: nop -IL_0006: ldc.i4.1 IL_0007: call ""void System.Console.WriteLine(int)"" IL_000c: nop -IL_000d: nop -IL_000e: ldloc.0 IL_000f: call ""void C.G(int)"" IL_0014: nop -IL_0015: ldloc.0 IL_0016: call ""bool C.F(int)"" IL_001b: stloc.1 ~IL_001c: ldloc.1 IL_001d: brtrue.s IL_0005 -IL_001f: ret }", sequencePoints: "C.M"); var methodData0 = v0.TestData.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.ForStatement, SyntaxKind.VariableDeclarator), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, //i bool V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: br.s IL_0016 IL_0005: nop IL_0006: ldc.i4.s 10 IL_0008: call ""void System.Console.WriteLine(int)"" IL_000d: nop IL_000e: nop IL_000f: ldloc.0 IL_0010: call ""void C.G(int)"" IL_0015: nop IL_0016: ldloc.0 IL_0017: call ""bool C.F(int)"" IL_001c: stloc.1 IL_001d: ldloc.1 IL_001e: brtrue.s IL_0005 IL_0020: ret } "); } [Fact] public void SynthesizedVariablesInLambdas1() { var source = @"class C { static object F() { return null; } static void M() { lock (F()) { var f = new System.Action(() => { lock (F()) { } }); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<>c.<M>b__1_0()", @" { // Code size 34 (0x22) .maxstack 2 .locals init (object V_0, bool V_1) IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldc.i4.0 IL_0008: stloc.1 .try { IL_0009: ldloc.0 IL_000a: ldloca.s V_1 IL_000c: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0011: nop IL_0012: nop IL_0013: nop IL_0014: leave.s IL_0021 } finally { IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.0 IL_001a: call ""void System.Threading.Monitor.Exit(object)"" IL_001f: nop IL_0020: endfinally } IL_0021: ret }"); #if TODO // identify the lambda in a semantic edit var methodData0 = v0.TestData.GetMethodData("C.<M>b__0"); var method0 = compilation0.GetMember<MethodSymbol>("C.<M>b__0"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("C.<M>b__0"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.<M>b__0", @" ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void SynthesizedVariablesInLambdas2() { var source0 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(1); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var source1 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(10); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var source2 = MarkedSource(@" using System; class C { static void M() { var <N:0>f1</N:0> = new Action<int[], int>(<N:1>(a, _) => { <N:2>foreach</N:2> (var x in a) { Console.WriteLine(100); // change to 10 and then to 100 } }</N:1>); var <N:3>f2</N:3> = new Action<int[], int>(<N:4>(a, _) => { <N:5>foreach</N:5> (var x in a) { Console.WriteLine(20); } }</N:4>); f1(new[] { 1, 2 }, 1); f2(new[] { 1, 2 }, 1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <M>b__0_0, <M>b__0_1}"); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <M>b__0_0, <M>b__0_1}"); var expectedIL = @" { // Code size 33 (0x21) .maxstack 2 .locals init (int[] V_0, int V_1, int V_2) //x IL_0000: nop IL_0001: nop IL_0002: ldarg.1 IL_0003: stloc.0 IL_0004: ldc.i4.0 IL_0005: stloc.1 IL_0006: br.s IL_001a IL_0008: ldloc.0 IL_0009: ldloc.1 IL_000a: ldelem.i4 IL_000b: stloc.2 IL_000c: nop IL_000d: ldc.i4.s 20 IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: nop IL_0016: ldloc.1 IL_0017: ldc.i4.1 IL_0018: add IL_0019: stloc.1 IL_001a: ldloc.1 IL_001b: ldloc.0 IL_001c: ldlen IL_001d: conv.i4 IL_001e: blt.s IL_0008 IL_0020: ret }"; diff1.VerifyIL(@"C.<>c.<M>b__0_1", expectedIL); diff2.VerifyIL(@"C.<>c.<M>b__0_1", expectedIL); } [Fact] public void SynthesizedVariablesInIterator1() { var source = @" using System.Collections.Generic; class C { public IEnumerable<int> F() { lock (F()) { } yield return 1; } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @" { // Code size 131 (0x83) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0016 IL_0012: br.s IL_0018 IL_0014: br.s IL_007a IL_0016: ldc.i4.0 IL_0017: ret IL_0018: ldarg.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<F>d__0.<>1__state"" IL_001f: nop IL_0020: ldarg.0 IL_0021: ldarg.0 IL_0022: ldfld ""C C.<F>d__0.<>4__this"" IL_0027: call ""System.Collections.Generic.IEnumerable<int> C.F()"" IL_002c: stfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_0031: ldarg.0 IL_0032: ldc.i4.0 IL_0033: stfld ""bool C.<F>d__0.<>s__2"" .try { IL_0038: ldarg.0 IL_0039: ldfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_003e: ldarg.0 IL_003f: ldflda ""bool C.<F>d__0.<>s__2"" IL_0044: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0049: nop IL_004a: nop IL_004b: nop IL_004c: leave.s IL_0063 } finally { IL_004e: ldarg.0 IL_004f: ldfld ""bool C.<F>d__0.<>s__2"" IL_0054: brfalse.s IL_0062 IL_0056: ldarg.0 IL_0057: ldfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_005c: call ""void System.Threading.Monitor.Exit(object)"" IL_0061: nop IL_0062: endfinally } IL_0063: ldarg.0 IL_0064: ldnull IL_0065: stfld ""System.Collections.Generic.IEnumerable<int> C.<F>d__0.<>s__1"" IL_006a: ldarg.0 IL_006b: ldc.i4.1 IL_006c: stfld ""int C.<F>d__0.<>2__current"" IL_0071: ldarg.0 IL_0072: ldc.i4.1 IL_0073: stfld ""int C.<F>d__0.<>1__state"" IL_0078: ldc.i4.1 IL_0079: ret IL_007a: ldarg.0 IL_007b: ldc.i4.m1 IL_007c: stfld ""int C.<F>d__0.<>1__state"" IL_0081: ldc.i4.0 IL_0082: ret }"); #if TODO var methodData0 = v0.TestData.GetMethodData("?"); var method0 = compilation0.GetMember<MethodSymbol>("?"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("?"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("?", @" {", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void SynthesizedVariablesInAsyncMethod1() { var source = @" using System.Threading.Tasks; class C { public async Task<int> F() { lock (F()) { } await F(); return 1; } } "; var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 246 (0xf6) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, C.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int C.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_0011 IL_000c: br IL_009e -IL_0011: nop -IL_0012: ldarg.0 IL_0013: ldarg.0 IL_0014: ldfld ""C C.<F>d__0.<>4__this"" IL_0019: call ""System.Threading.Tasks.Task<int> C.F()"" IL_001e: stfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0023: ldarg.0 IL_0024: ldc.i4.0 IL_0025: stfld ""bool C.<F>d__0.<>s__2"" .try { IL_002a: ldarg.0 IL_002b: ldfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0030: ldarg.0 IL_0031: ldflda ""bool C.<F>d__0.<>s__2"" IL_0036: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_003b: nop -IL_003c: nop -IL_003d: nop IL_003e: leave.s IL_0059 } finally { ~IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: bge.s IL_0058 IL_0044: ldarg.0 IL_0045: ldfld ""bool C.<F>d__0.<>s__2"" IL_004a: brfalse.s IL_0058 IL_004c: ldarg.0 IL_004d: ldfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" IL_0052: call ""void System.Threading.Monitor.Exit(object)"" IL_0057: nop ~IL_0058: endfinally } ~IL_0059: ldarg.0 IL_005a: ldnull IL_005b: stfld ""System.Threading.Tasks.Task<int> C.<F>d__0.<>s__1"" -IL_0060: ldarg.0 IL_0061: ldfld ""C C.<F>d__0.<>4__this"" IL_0066: call ""System.Threading.Tasks.Task<int> C.F()"" IL_006b: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0070: stloc.2 ~IL_0071: ldloca.s V_2 IL_0073: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0078: brtrue.s IL_00ba IL_007a: ldarg.0 IL_007b: ldc.i4.0 IL_007c: dup IL_007d: stloc.0 IL_007e: stfld ""int C.<F>d__0.<>1__state"" <IL_0083: ldarg.0 IL_0084: ldloc.2 IL_0085: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_008a: ldarg.0 IL_008b: stloc.3 IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_0092: ldloca.s V_2 IL_0094: ldloca.s V_3 IL_0096: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)"" IL_009b: nop IL_009c: leave.s IL_00f5 >IL_009e: ldarg.0 IL_009f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_00a4: stloc.2 IL_00a5: ldarg.0 IL_00a6: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1"" IL_00ab: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00b1: ldarg.0 IL_00b2: ldc.i4.m1 IL_00b3: dup IL_00b4: stloc.0 IL_00b5: stfld ""int C.<F>d__0.<>1__state"" IL_00ba: ldloca.s V_2 IL_00bc: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00c1: pop -IL_00c2: ldc.i4.1 IL_00c3: stloc.1 IL_00c4: leave.s IL_00e0 } catch System.Exception { ~IL_00c6: stloc.s V_4 IL_00c8: ldarg.0 IL_00c9: ldc.i4.s -2 IL_00cb: stfld ""int C.<F>d__0.<>1__state"" IL_00d0: ldarg.0 IL_00d1: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00d6: ldloc.s V_4 IL_00d8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00dd: nop IL_00de: leave.s IL_00f5 } -IL_00e0: ldarg.0 IL_00e1: ldc.i4.s -2 IL_00e3: stfld ""int C.<F>d__0.<>1__state"" ~IL_00e8: ldarg.0 IL_00e9: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder"" IL_00ee: ldloc.1 IL_00ef: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00f4: nop IL_00f5: ret }", sequencePoints: "C+<F>d__0.MoveNext"); #if TODO var methodData0 = v0.TestData.GetMethodData("?"); var method0 = compilation0.GetMember<MethodSymbol>("?"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), m => GetLocalNames(methodData0)); var method1 = compilation1.GetMember<MethodSymbol>("?"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("?", @" {", methodToken: diff1.EmitResult.UpdatedMethods.Single()); #endif } [Fact] public void OutVar() { var source = @" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int x, out var y); return x + y; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop -IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 -IL_0011: ldloc.3 IL_0012: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternVariable() { var source = @" class C { static int F(object o) { if (o is int i) { return i; } return 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d -IL_0018: nop -IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0021 -IL_001d: ldc.i4.0 IL_001e: stloc.3 IL_001f: br.s IL_0021 -IL_0021: ldloc.3 IL_0022: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Tuple_Parenthesized() { var source = @" class C { static int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x [int] V_1, int V_2) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" -IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.2 IL_002f: br.s IL_0031 -IL_0031: ldloc.2 IL_0032: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void Tuple_Decomposition() { var source = @" class C { static int F() { (int x, (int y, int z)) = (1, (2, 3)); return x + y + z; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z [int] V_3, int V_4) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 -IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.s V_4 IL_000e: br.s IL_0010 -IL_0010: ldloc.s V_4 IL_0012: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternMatching_Variable() { var source = @" class C { static int F(object o) { if (o is int i) { return i; } return 0; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, [int] V_2, int V_3) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 ~IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d -IL_0018: nop -IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0021 -IL_001d: ldc.i4.0 IL_001e: stloc.3 IL_001f: br.s IL_0021 -IL_0021: ldloc.3 IL_0022: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void PatternMatching_NoVariable() { var source = @" class C { static int F(object o) { if ((o is bool) || (o is 0)) { return 0; } return 1; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (bool V_0, [int] V_1, int V_2) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brtrue.s IL_001f IL_0009: ldarg.0 IL_000a: isinst ""int"" IL_000f: brfalse.s IL_001c IL_0011: ldarg.0 IL_0012: unbox.any ""int"" IL_0017: ldc.i4.0 IL_0018: ceq IL_001a: br.s IL_001d IL_001c: ldc.i4.0 IL_001d: br.s IL_0020 IL_001f: ldc.i4.1 IL_0020: stloc.0 ~IL_0021: ldloc.0 IL_0022: brfalse.s IL_0029 -IL_0024: nop -IL_0025: ldc.i4.0 IL_0026: stloc.2 IL_0027: br.s IL_002d -IL_0029: ldc.i4.1 IL_002a: stloc.2 IL_002b: br.s IL_002d -IL_002d: ldloc.2 IL_002e: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void VarPattern() { var source = @" using System.Threading.Tasks; class C { static object G(object o1, object o2) { return (o1, o2) switch { (int a, string b) => a, _ => 0 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 62 (0x3e) .maxstack 1 .locals init (int V_0, //a string V_1, //b [int] V_2, [object] V_3, int V_4, object V_5) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 -IL_0004: nop ~IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0027 IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.0 ~IL_0014: ldarg.1 IL_0015: isinst ""string"" IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: brtrue.s IL_0020 IL_001e: br.s IL_0027 ~IL_0020: br.s IL_0022 -IL_0022: ldloc.0 IL_0023: stloc.s V_4 IL_0025: br.s IL_002c -IL_0027: ldc.i4.0 IL_0028: stloc.s V_4 IL_002a: br.s IL_002c ~IL_002c: ldc.i4.1 IL_002d: brtrue.s IL_0030 -IL_002f: nop ~IL_0030: ldloc.s V_4 IL_0032: box ""int"" IL_0037: stloc.s V_5 IL_0039: br.s IL_003b -IL_003b: ldloc.s V_5 IL_003d: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void RecursiveSwitchExpression() { var source = @" class C { static object G(object o) { return o switch { int i => i switch { 0 => 1, _ => 2, }, _ => 3 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 76 (0x4c) .maxstack 1 .locals init (int V_0, //i [int] V_1, [int] V_2, [object] V_3, int V_4, int V_5, object V_6) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 -IL_0004: nop ~IL_0005: ldarg.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_0035 IL_000d: ldarg.0 IL_000e: unbox.any ""int"" IL_0013: stloc.0 ~IL_0014: br.s IL_0016 ~IL_0016: br.s IL_0018 IL_0018: ldc.i4.1 IL_0019: brtrue.s IL_001c -IL_001b: nop ~IL_001c: ldloc.0 IL_001d: brfalse.s IL_0021 IL_001f: br.s IL_0026 -IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b -IL_0026: ldc.i4.2 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b ~IL_002b: ldc.i4.1 IL_002c: brtrue.s IL_002f -IL_002e: nop -IL_002f: ldloc.s V_5 IL_0031: stloc.s V_4 IL_0033: br.s IL_003a -IL_0035: ldc.i4.3 IL_0036: stloc.s V_4 IL_0038: br.s IL_003a ~IL_003a: ldc.i4.1 IL_003b: brtrue.s IL_003e -IL_003d: nop ~IL_003e: ldloc.s V_4 IL_0040: box ""int"" IL_0045: stloc.s V_6 IL_0047: br.s IL_0049 -IL_0049: ldloc.s V_6 IL_004b: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void RecursiveSwitchExpressionWithAwait() { var source = @" using System.Threading.Tasks; class C { static async Task<object> G(object o) { return o switch { Task<int> i when await i > 0 => await i switch { 1 => 1, _ => 2, }, _ => 3 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetEquivalentNodesMap(g1, g0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 56 (0x38) .maxstack 2 .locals init (C.<G>d__0 V_0) ~IL_0000: newobj ""C.<G>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 ~IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""object C.<G>d__0.o"" IL_0018: ldloc.0 -IL_0019: ldc.i4.m1 -IL_001a: stfld ""int C.<G>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<C.<G>d__0>(ref C.<G>d__0)"" IL_002c: ldloc.0 IL_002d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0032: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0037: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void SwitchExpressionInsideAwait() { var source = @" using System.Threading.Tasks; class C { static async Task<object> G(Task<object> o) { return await o switch { int i => 0, _ => 1 }; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 56 (0x38) .maxstack 2 .locals init (C.<G>d__0 V_0) ~IL_0000: newobj ""C.<G>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 ~IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldarg.0 IL_0013: stfld ""System.Threading.Tasks.Task<object> C.<G>d__0.o"" IL_0018: ldloc.0 IL_0019: ldc.i4.m1 IL_001a: stfld ""int C.<G>d__0.<>1__state"" IL_001f: ldloc.0 IL_0020: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0025: ldloca.s V_0 IL_0027: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Start<C.<G>d__0>(ref C.<G>d__0)"" IL_002c: ldloc.0 <IL_002d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> C.<G>d__0.<>t__builder"" IL_0032: call ""System.Threading.Tasks.Task<object> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.Task.get"" IL_0037: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void SwitchExpressionWithOutVar() { var source = @" class C { static object G() { return N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 73 (0x49) .maxstack 2 .locals init (int V_0, //x [int] V_1, [object] V_2, [int] V_3, [object] V_4, int V_5, object V_6, int V_7, object V_8) -IL_0000: nop -IL_0001: ldloca.s V_0 IL_0003: call ""object C.N(out int)"" IL_0008: stloc.s V_6 IL_000a: ldc.i4.1 IL_000b: brtrue.s IL_000e -IL_000d: nop ~IL_000e: ldloc.s V_6 IL_0010: brfalse.s IL_0014 IL_0012: br.s IL_0032 ~IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 -IL_0017: nop ~IL_0018: ldloc.0 IL_0019: ldc.i4.1 IL_001a: beq.s IL_001e IL_001c: br.s IL_0023 -IL_001e: ldc.i4.1 IL_001f: stloc.s V_7 IL_0021: br.s IL_0028 -IL_0023: ldc.i4.2 IL_0024: stloc.s V_7 IL_0026: br.s IL_0028 ~IL_0028: ldc.i4.1 IL_0029: brtrue.s IL_002c -IL_002b: nop -IL_002c: ldloc.s V_7 IL_002e: stloc.s V_5 IL_0030: br.s IL_0037 -IL_0032: ldc.i4.1 IL_0033: stloc.s V_5 IL_0035: br.s IL_0037 ~IL_0037: ldc.i4.1 IL_0038: brtrue.s IL_003b -IL_003a: nop ~IL_003b: ldloc.s V_5 IL_003d: box ""int"" IL_0042: stloc.s V_8 IL_0044: br.s IL_0046 -IL_0046: ldloc.s V_8 IL_0048: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ForEachStatement_Deconstruction() { var source = @" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (x, (y, z)) in F()) { System.Console.WriteLine(x); } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.G"); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) -IL_0000: nop -IL_0001: nop -IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 ~IL_000c: br.s IL_0045 -IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 -IL_0036: nop -IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop -IL_003e: nop ~IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 -IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e -IL_004d: ret } ", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } [Fact] public void ComplexTypes() { var sourceText = @" using System; using System.Collections.Generic; class C1<T> { public enum E { A } } class C { public unsafe static void G() { var <N:0>a</N:0> = new { key = ""a"", value = new List<(int, int)>()}; var <N:1>b</N:1> = (number: 5, value: a); var <N:2>c</N:2> = new[] { b }; int[] <N:3>array</N:3> = { 1, 2, 3 }; ref int <N:4>d</N:4> = ref array[0]; ref readonly int <N:5>e</N:5> = ref array[0]; C1<(int, dynamic)>.E***[,,] <N:6>x</N:6> = null; var <N:7>f</N:7> = new List<string?>(); } } "; var source0 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source1 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var source2 = MarkedSource(sourceText, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9)); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithAllowUnsafe(true)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 88 (0x58) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_0035: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_003a: stloc.3 IL_003b: ldloc.3 IL_003c: ldc.i4.0 IL_003d: ldelema ""int"" IL_0042: stloc.s V_4 IL_0044: ldloc.3 IL_0045: ldc.i4.0 IL_0046: ldelema ""int"" IL_004b: stloc.s V_5 IL_004d: ldnull IL_004e: stloc.s V_6 IL_0050: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0055: stloc.s V_7 IL_0057: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 89 (0x59) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i4 IL_0033: dup IL_0034: ldc.i4.1 IL_0035: ldc.i4.2 IL_0036: stelem.i4 IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.3 IL_003a: stelem.i4 IL_003b: stloc.3 IL_003c: ldloc.3 IL_003d: ldc.i4.0 IL_003e: ldelema ""int"" IL_0043: stloc.s V_4 IL_0045: ldloc.3 IL_0046: ldc.i4.0 IL_0047: ldelema ""int"" IL_004c: stloc.s V_5 IL_004e: ldnull IL_004f: stloc.s V_6 IL_0051: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0056: stloc.s V_7 IL_0058: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 89 (0x59) .maxstack 4 .locals init (<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>> V_0, //a System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>> V_1, //b System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>[] V_2, //c int[] V_3, //array int& V_4, //d int& V_5, //e C1<System.ValueTuple<int, dynamic>>.E***[,,] V_6, //x System.Collections.Generic.List<string> V_7) //f IL_0000: nop IL_0001: ldstr ""a"" IL_0006: newobj ""System.Collections.Generic.List<System.ValueTuple<int, int>>..ctor()"" IL_000b: newobj ""<>f__AnonymousType0<string, System.Collections.Generic.List<System.ValueTuple<int, int>>>..ctor(string, System.Collections.Generic.List<System.ValueTuple<int, int>>)"" IL_0010: stloc.0 IL_0011: ldloca.s V_1 IL_0013: ldc.i4.5 IL_0014: ldloc.0 IL_0015: call ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>..ctor(int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>)"" IL_001a: ldc.i4.1 IL_001b: newarr ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0020: dup IL_0021: ldc.i4.0 IL_0022: ldloc.1 IL_0023: stelem ""System.ValueTuple<int, <anonymous type: string key, System.Collections.Generic.List<System.ValueTuple<int, int>> value>>"" IL_0028: stloc.2 IL_0029: ldc.i4.3 IL_002a: newarr ""int"" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i4 IL_0033: dup IL_0034: ldc.i4.1 IL_0035: ldc.i4.2 IL_0036: stelem.i4 IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.3 IL_003a: stelem.i4 IL_003b: stloc.3 IL_003c: ldloc.3 IL_003d: ldc.i4.0 IL_003e: ldelema ""int"" IL_0043: stloc.s V_4 IL_0045: ldloc.3 IL_0046: ldc.i4.0 IL_0047: ldelema ""int"" IL_004c: stloc.s V_5 IL_004e: ldnull IL_004f: stloc.s V_6 IL_0051: newobj ""System.Collections.Generic.List<string>..ctor()"" IL_0056: stloc.s V_7 IL_0058: ret } "); } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/Test/Resources/Core/DiagnosticTests/ErrTestMod02.cs
// Licensed to the .NET Foundation under one or more 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 NS { namespace Util { public class A { } } }
// Licensed to the .NET Foundation under one or more 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 NS { namespace Util { public class A { } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/SynthesizedStateMachineMethod.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// State machine interface method implementation. /// </summary> internal abstract class SynthesizedStateMachineMethod : SynthesizedImplementationMethod, ISynthesizedMethodBodyImplementationSymbol { private readonly bool _hasMethodBodyDependency; protected SynthesizedStateMachineMethod( string name, MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType, PropertySymbol associatedProperty, bool generateDebugInfo, bool hasMethodBodyDependency) : base(interfaceMethod, stateMachineType, name, generateDebugInfo, associatedProperty) { _hasMethodBodyDependency = hasMethodBodyDependency; } public StateMachineTypeSymbol StateMachineType { get { return (StateMachineTypeSymbol)ContainingSymbol; } } public bool HasMethodBodyDependency { get { return _hasMethodBodyDependency; } } IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method { get { return StateMachineType.KickoffMethod; } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return this.StateMachineType.KickoffMethod.CalculateLocalSyntaxOffset(localPosition, localTree); } } /// <summary> /// Represents a state machine MoveNext method. /// Handles special behavior around inheriting some attributes from the original async/iterator method. /// </summary> internal sealed class SynthesizedStateMachineMoveNextMethod : SynthesizedStateMachineMethod { private ImmutableArray<CSharpAttributeData> _attributes; public SynthesizedStateMachineMoveNextMethod(MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType) : base(WellKnownMemberNames.MoveNextMethodName, interfaceMethod, stateMachineType, null, generateDebugInfo: true, hasMethodBodyDependency: true) { } public override ImmutableArray<CSharpAttributeData> GetAttributes() { if (_attributes.IsDefault) { Debug.Assert(base.GetAttributes().Length == 0); ArrayBuilder<CSharpAttributeData> builder = null; // Inherit some attributes from the kickoff method var kickoffMethod = StateMachineType.KickoffMethod; foreach (var attribute in kickoffMethod.GetAttributes()) { if (attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerHiddenAttribute) || attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerNonUserCodeAttribute) || attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepperBoundaryAttribute) || attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepThroughAttribute)) { if (builder == null) { builder = ArrayBuilder<CSharpAttributeData>.GetInstance(4); // only 4 different attributes are inherited at the moment } builder.Add(attribute); } } ImmutableInterlocked.InterlockedCompareExchange(ref _attributes, builder == null ? ImmutableArray<CSharpAttributeData>.Empty : builder.ToImmutableAndFree(), default(ImmutableArray<CSharpAttributeData>)); } return _attributes; } } /// <summary> /// Represents a state machine method other than a MoveNext method. /// All such methods are considered debugger hidden. /// </summary> internal sealed class SynthesizedStateMachineDebuggerHiddenMethod : SynthesizedStateMachineMethod { public SynthesizedStateMachineDebuggerHiddenMethod( string name, MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType, PropertySymbol associatedProperty, bool hasMethodBodyDependency) : base(name, interfaceMethod, stateMachineType, associatedProperty, generateDebugInfo: false, hasMethodBodyDependency: hasMethodBodyDependency) { } internal sealed override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)); base.AddSynthesizedAttributes(moduleBuilder, ref attributes); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// State machine interface method implementation. /// </summary> internal abstract class SynthesizedStateMachineMethod : SynthesizedImplementationMethod, ISynthesizedMethodBodyImplementationSymbol { private readonly bool _hasMethodBodyDependency; protected SynthesizedStateMachineMethod( string name, MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType, PropertySymbol associatedProperty, bool generateDebugInfo, bool hasMethodBodyDependency) : base(interfaceMethod, stateMachineType, name, generateDebugInfo, associatedProperty) { _hasMethodBodyDependency = hasMethodBodyDependency; } public StateMachineTypeSymbol StateMachineType { get { return (StateMachineTypeSymbol)ContainingSymbol; } } public bool HasMethodBodyDependency { get { return _hasMethodBodyDependency; } } IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method { get { return StateMachineType.KickoffMethod; } } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { return this.StateMachineType.KickoffMethod.CalculateLocalSyntaxOffset(localPosition, localTree); } } /// <summary> /// Represents a state machine MoveNext method. /// Handles special behavior around inheriting some attributes from the original async/iterator method. /// </summary> internal sealed class SynthesizedStateMachineMoveNextMethod : SynthesizedStateMachineMethod { private ImmutableArray<CSharpAttributeData> _attributes; public SynthesizedStateMachineMoveNextMethod(MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType) : base(WellKnownMemberNames.MoveNextMethodName, interfaceMethod, stateMachineType, null, generateDebugInfo: true, hasMethodBodyDependency: true) { } public override ImmutableArray<CSharpAttributeData> GetAttributes() { if (_attributes.IsDefault) { Debug.Assert(base.GetAttributes().Length == 0); ArrayBuilder<CSharpAttributeData> builder = null; // Inherit some attributes from the kickoff method var kickoffMethod = StateMachineType.KickoffMethod; foreach (var attribute in kickoffMethod.GetAttributes()) { if (attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerHiddenAttribute) || attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerNonUserCodeAttribute) || attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepperBoundaryAttribute) || attribute.IsTargetAttribute(kickoffMethod, AttributeDescription.DebuggerStepThroughAttribute)) { if (builder == null) { builder = ArrayBuilder<CSharpAttributeData>.GetInstance(4); // only 4 different attributes are inherited at the moment } builder.Add(attribute); } } ImmutableInterlocked.InterlockedCompareExchange(ref _attributes, builder == null ? ImmutableArray<CSharpAttributeData>.Empty : builder.ToImmutableAndFree(), default(ImmutableArray<CSharpAttributeData>)); } return _attributes; } } /// <summary> /// Represents a state machine method other than a MoveNext method. /// All such methods are considered debugger hidden. /// </summary> internal sealed class SynthesizedStateMachineDebuggerHiddenMethod : SynthesizedStateMachineMethod { public SynthesizedStateMachineDebuggerHiddenMethod( string name, MethodSymbol interfaceMethod, StateMachineTypeSymbol stateMachineType, PropertySymbol associatedProperty, bool hasMethodBodyDependency) : base(name, interfaceMethod, stateMachineType, associatedProperty, generateDebugInfo: false, hasMethodBodyDependency: hasMethodBodyDependency) { } internal sealed override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor)); base.AddSynthesizedAttributes(moduleBuilder, ref attributes); } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using MetadataOrDiagnostic = System.Object; /// <summary> /// The base class for language specific assembly managers. /// </summary> /// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam> /// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam> internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol> where TCompilation : Compilation where TAssemblySymbol : class, IAssemblySymbolInternal { protected abstract CommonMessageProvider MessageProvider { get; } protected abstract AssemblyData CreateAssemblyDataForFile( PEAssembly assembly, WeakList<IAssemblySymbolInternal> cachedSymbols, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions importOptions, bool embedInteropTypes); protected abstract AssemblyData CreateAssemblyDataForCompilation( CompilationReference compilationReference); /// <summary> /// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>. /// Reports inconsistencies to the given diagnostic bag. /// </summary> /// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns> protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics); /// <summary> /// Called to compare two weakly named identities with the same name. /// </summary> protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2); [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] protected struct ResolvedReference { private readonly MetadataImageKind _kind; private readonly int _index; private readonly ImmutableArray<string> _aliasesOpt; private readonly ImmutableArray<string> _recursiveAliasesOpt; private readonly ImmutableArray<MetadataReference> _mergedReferencesOpt; // uninitialized aliases public ResolvedReference(int index, MetadataImageKind kind) { Debug.Assert(index >= 0); _index = index + 1; _kind = kind; _aliasesOpt = default(ImmutableArray<string>); _recursiveAliasesOpt = default(ImmutableArray<string>); _mergedReferencesOpt = default(ImmutableArray<MetadataReference>); } // initialized aliases public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt, ImmutableArray<MetadataReference> mergedReferences) : this(index, kind) { // We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged. Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault); Debug.Assert(!mergedReferences.IsDefault); _aliasesOpt = aliasesOpt; _recursiveAliasesOpt = recursiveAliasesOpt; _mergedReferencesOpt = mergedReferences; } private bool IsUninitialized => (_aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault) || _mergedReferencesOpt.IsDefault; /// <summary> /// Aliases that should be applied to the referenced assembly. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has recursive aliases). /// </summary> public ImmutableArray<string> AliasesOpt { get { Debug.Assert(!IsUninitialized); return _aliasesOpt; } } /// <summary> /// Aliases that should be applied recursively to all dependent assemblies. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has simple aliases). /// </summary> public ImmutableArray<string> RecursiveAliasesOpt { get { Debug.Assert(!IsUninitialized); return _recursiveAliasesOpt; } } public ImmutableArray<MetadataReference> MergedReferences { get { Debug.Assert(!IsUninitialized); return _mergedReferencesOpt; } } /// <summary> /// default(<see cref="ResolvedReference"/>) is considered skipped. /// </summary> public bool IsSkipped { get { return _index == 0; } } public MetadataImageKind Kind { get { Debug.Assert(!IsSkipped); return _kind; } } /// <summary> /// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>. /// </summary> public int Index { get { Debug.Assert(!IsSkipped); return _index - 1; } } private string GetDebuggerDisplay() { return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}"; } private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name) { return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'"; } } protected readonly struct ReferencedAssemblyIdentity { public readonly AssemblyIdentity? Identity; public readonly MetadataReference? Reference; /// <summary> /// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies. /// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies. /// </summary> public readonly int RelativeAssemblyIndex; public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) => RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex; public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex) { Identity = identity; Reference = reference; RelativeAssemblyIndex = relativeAssemblyIndex; } } /// <summary> /// Resolves given metadata references to assemblies and modules. /// </summary> /// <param name="compilation">The compilation whose references are being resolved.</param> /// <param name="assemblyReferencesBySimpleName"> /// Used to filter out assemblies that have the same strong or weak identity. /// Maps simple name to a list of identities. The highest version of each name is the first. /// </param> /// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param> /// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param> /// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param> /// <param name="assemblies">List where to store information about resolved assemblies to.</param> /// <param name="modules">List where to store information about resolved modules to.</param> /// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param> /// <returns> /// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively. ///</returns> protected ImmutableArray<ResolvedReference> ResolveMetadataReferences( TCompilation compilation, [Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap, out ImmutableArray<MetadataReference> boundReferenceDirectives, out ImmutableArray<AssemblyData> assemblies, out ImmutableArray<PEModule> modules, DiagnosticBag diagnostics) { // Locations of all #r directives in the order they are listed in the references list. ImmutableArray<Location> referenceDirectiveLocations; GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations); // References originating from #r directives precede references supplied as arguments of the compilation. int referenceCount = references.Length; int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0); var referenceMap = new ResolvedReference[referenceCount]; // Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that // can be used to alias these references. Duplicate assemblies contribute their aliases into this set. Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null; // Used to filter out duplicate references that reference the same file (resolve to the same full normalized path). var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance); ArrayBuilder<MetadataReference>? uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null; var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance(); ArrayBuilder<PEModule>? lazyModulesBuilder = null; bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions; // When duplicate references with conflicting EmbedInteropTypes flag are encountered, // VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order // so that we find the one that matters first. for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--) { var boundReference = references[referenceIndex]; if (boundReference == null) { continue; } // add bound reference if it doesn't exist yet, merging aliases: MetadataReference? existingReference; if (boundReferences.TryGetValue(boundReference, out existingReference)) { // merge properties of compilation-based references if the underlying compilations are the same if ((object)boundReference != existingReference) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); } continue; } boundReferences.Add(boundReference, boundReference); Location location; if (referenceIndex < referenceDirectiveCount) { location = referenceDirectiveLocations[referenceIndex]; uniqueDirectiveReferences!.Add(boundReference); } else { location = Location.None; } // compilation reference var compilationReference = boundReference as CompilationReference; if (compilationReference != null) { switch (compilationReference.Properties.Kind) { case MetadataImageKind.Assembly: existingReference = TryAddAssembly( compilationReference.Compilation.Assembly.Identity, boundReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } // Note, if SourceAssemblySymbol hasn't been created for // compilationAssembly.Compilation yet, we want this to happen // right now. Conveniently, this constructor will trigger creation of the // SourceAssemblySymbol. var asmData = CreateAssemblyDataForCompilation(compilationReference); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); break; default: throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind); } continue; } // PE reference var peReference = (PortableExecutableReference)boundReference; Metadata? metadata = GetMetadata(peReference, MessageProvider, location, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata != null) { switch (peReference.Properties.Kind) { case MetadataImageKind.Assembly: var assemblyMetadata = (AssemblyMetadata)metadata; WeakList<IAssemblySymbolInternal> cachedSymbols = assemblyMetadata.CachedSymbols; if (assemblyMetadata.IsValidAssembly()) { PEAssembly? assembly = assemblyMetadata.GetAssembly(); Debug.Assert(assembly is object); existingReference = TryAddAssembly( assembly.Identity, peReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } var asmData = CreateAssemblyDataForFile( assembly, cachedSymbols, peReference.DocumentationProvider, SimpleAssemblyName, compilation.Options.MetadataImportOptions, peReference.Properties.EmbedInteropTypes); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display ?? "")); } // asmData keeps strong ref after this point GC.KeepAlive(assemblyMetadata); break; case MetadataImageKind.Module: var moduleMetadata = (ModuleMetadata)metadata; if (moduleMetadata.Module.IsLinkedModule) { // We don't support netmodules since some checks in the compiler need information from the full PE image // (Machine, Bit32Required, PE image hash). if (!moduleMetadata.Module.IsEntireImageAvailable) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display ?? "")); } AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display ?? "")); } break; default: throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind); } } } if (uniqueDirectiveReferences != null) { uniqueDirectiveReferences.ReverseContents(); boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree(); } else { boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty; } // We enumerated references in reverse order in the above code // and thus assemblies and modules in the builders are reversed. // Fix up all the indices and reverse the builder content now to get // the ordering matching the references. // // Also fills in aliases. for (int i = 0; i < referenceMap.Length; i++) { if (!referenceMap[i].IsSkipped) { int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0; int reversedIndex = count - 1 - referenceMap[i].Index; referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap); } } assembliesBuilder.ReverseContents(); assemblies = assembliesBuilder.ToImmutableAndFree(); if (lazyModulesBuilder == null) { modules = ImmutableArray<PEModule>.Empty; } else { lazyModulesBuilder.ReverseContents(); modules = lazyModulesBuilder.ToImmutableAndFree(); } return ImmutableArray.CreateRange(referenceMap); } private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases>? propertyMapOpt) { ImmutableArray<string> aliasesOpt, recursiveAliasesOpt; var mergedReferences = ImmutableArray<MetadataReference>.Empty; if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases? mergedProperties)) { aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); if (mergedProperties.MergedReferencesOpt is object) { mergedReferences = mergedProperties.MergedReferencesOpt.ToImmutableAndFree(); } } else if (reference.Properties.HasRecursiveAliases) { aliasesOpt = default(ImmutableArray<string>); recursiveAliasesOpt = reference.Properties.Aliases; } else { aliasesOpt = reference.Properties.Aliases; recursiveAliasesOpt = default(ImmutableArray<string>); } return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences); } /// <summary> /// Creates or gets metadata for PE reference. /// </summary> /// <remarks> /// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>, /// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>. /// </remarks> private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) { Metadata? existingMetadata; lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } } Metadata? newMetadata; Diagnostic? newDiagnostic = null; try { newMetadata = peReference.GetMetadataNoCopy(); // make sure basic structure of the PE image is valid: if (newMetadata is AssemblyMetadata assemblyMetadata) { _ = assemblyMetadata.IsValidAssembly(); } else { _ = ((ModuleMetadata)newMetadata).Module.IsLinkedModule; } } catch (Exception e) when (e is BadImageFormatException || e is IOException) { newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind); newMetadata = null; } lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } if (newDiagnostic != null) { diagnostics.Add(newDiagnostic); } ObservedMetadata.Add(peReference, (MetadataOrDiagnostic?)newMetadata ?? newDiagnostic!); return newMetadata; } } private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata) { if (ObservedMetadata.TryGetValue(peReference, out MetadataOrDiagnostic? existing)) { Debug.Assert(existing is Metadata || existing is Diagnostic); metadata = existing as Metadata; if (metadata == null) { diagnostics.Add((Diagnostic)existing); } return true; } metadata = null; return false; } internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics) { var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata == null) { return null; } // require the metadata to be a valid assembly metadata: var assemblyMetadata = metadata as AssemblyMetadata; if (assemblyMetadata?.IsValidAssembly() != true) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? "")); return null; } return assemblyMetadata; } /// <summary> /// Determines whether references are the same. Compilation references are the same if they refer to the same compilation. /// Otherwise, references are represented by their object identities. /// </summary> internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference> { internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer(); public bool Equals(MetadataReference? x, MetadataReference? y) { if (ReferenceEquals(x, y)) { return true; } var cx = x as CompilationReference; if (cx != null) { var cy = y as CompilationReference; if (cy != null) { return (object)cx.Compilation == cy.Compilation; } } return false; } public int GetHashCode(MetadataReference reference) { var compilationReference = reference as CompilationReference; if (compilationReference != null) { return RuntimeHelpers.GetHashCode(compilationReference.Compilation); } return RuntimeHelpers.GetHashCode(reference); } } /// <summary> /// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>). /// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols. /// </summary> private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases>? lazyAliasMap) { if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics)) { return; } if (lazyAliasMap == null) { lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>(); } MergedAliases? mergedAliases; if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases)) { mergedAliases = new MergedAliases(); lazyAliasMap.Add(primaryReference, mergedAliases); mergedAliases.Merge(primaryReference); } mergedAliases.Merge(newReference); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies) { // aliases will be filled in later: referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly); assemblies.Add(data); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder<PEModule>? modules) { if (modules == null) { modules = ArrayBuilder<PEModule>.GetInstance(); } referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module); modules.Add(module); } /// <summary> /// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it. /// Two identities are considered equivalent if /// - both assembly names are strong (have keys) and are either equal or FX unified /// - both assembly names are weak (no keys) and have the same simple name. /// </summary> private MetadataReference? TryAddAssembly( AssemblyIdentity identity, MetadataReference reference, int assemblyIndex, DiagnosticBag diagnostics, Location location, Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName, bool supersedeLowerVersions) { var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex); List<ReferencedAssemblyIdentity>? sameSimpleNameIdentities; if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly }); return null; } if (supersedeLowerVersions) { foreach (var other in sameSimpleNameIdentities) { Debug.Assert(other.Identity is object); if (identity.Version == other.Identity.Version) { return other.Reference; } } // Keep all versions of the assembly and the first identity in the list the one with the highest version: if (sameSimpleNameIdentities[0].Identity!.Version > identity.Version) { sameSimpleNameIdentities.Add(referencedAssembly); } else { sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]); sameSimpleNameIdentities[0] = referencedAssembly; } return null; } ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity); if (identity.IsStrongName) { foreach (var other in sameSimpleNameIdentities) { // Only compare strong with strong (weak is never equivalent to strong and vice versa). // In order to eliminate duplicate references we need to try to match their identities in both directions since // ReferenceMatchesDefinition is not necessarily symmetric. // (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.) Debug.Assert(other.Identity is object); if (other.Identity.IsStrongName && IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) && IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity)) { equivalent = other; break; } } } else { foreach (var other in sameSimpleNameIdentities) { // only compare weak with weak Debug.Assert(other.Identity is object); if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity)) { equivalent = other; break; } } } if (equivalent.Identity == null) { sameSimpleNameIdentities.Add(referencedAssembly); return null; } // equivalent found - ignore and/or report an error: if (identity.IsStrongName) { Debug.Assert(equivalent.Identity.IsStrongName); // versions might have been unified for a Framework assembly: if (identity != equivalent.Identity) { // Dev12 C# reports an error // Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used. // BREAKING CHANGE in VB: we report an error for both languages // Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } // If the versions match exactly we ignore duplicates w/o reporting errors while // Dev12 C# reports: // error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references. // Dev12 VB reports: // Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System. // A second reference to 'D:\Temp\System.dll' cannot be added. } else { Debug.Assert(!equivalent.Identity.IsStrongName); // Dev12 reports an error for all weak-named assemblies, even if the versions are the same. // We treat assemblies with the same name and version equal even if they don't have a strong name. // This change allows us to de-duplicate #r references based on identities rather than full paths, // and is closer to platforms that don't support strong names and consider name and version enough // to identify an assembly. An identity without version is considered to have version 0.0.0.0. if (identity != equivalent.Identity) { MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } } Debug.Assert(equivalent.Reference != null); return equivalent.Reference; } protected void GetCompilationReferences( TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectives, out ImmutableArray<Location> referenceDirectiveLocations) { ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance(); ArrayBuilder<Location>? referenceDirectiveLocationsBuilder = null; IDictionary<(string, string), MetadataReference>? localBoundReferenceDirectives = null; try { foreach (var referenceDirective in compilation.ReferenceDirectives) { Debug.Assert(referenceDirective.Location is object); if (compilation.Options.MetadataReferenceResolver == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); break; } // we already successfully bound #r with the same value: Debug.Assert(referenceDirective.File is object); Debug.Assert(referenceDirective.Location.SourceTree is object); if (localBoundReferenceDirectives != null && localBoundReferenceDirectives.ContainsKey((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File))) { continue; } MetadataReference? boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation); if (boundReference == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File)); continue; } if (localBoundReferenceDirectives == null) { localBoundReferenceDirectives = new Dictionary<(string, string), MetadataReference>(); referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance(); } referencesBuilder.Add(boundReference); referenceDirectiveLocationsBuilder!.Add(referenceDirective.Location); localBoundReferenceDirectives.Add((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference); } // add external reference at the end, so that they are processed first: referencesBuilder.AddRange(compilation.ExternalReferences); // Add all explicit references of the previous script compilation. var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousScriptCompilation != null) { referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences); } if (localBoundReferenceDirectives == null) { // no directive references resolved successfully: localBoundReferenceDirectives = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>(); } boundReferenceDirectives = localBoundReferenceDirectives; references = referencesBuilder.ToImmutable(); referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray<Location>.Empty; } finally { // Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and // we don't want to clutter the test output with leak reports. referencesBuilder.Free(); } } /// <summary> /// For each given directive return a bound PE reference, or null if the binding fails. /// </summary> private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation) { var tree = location.SourceTree; string? basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null; // checked earlier: Debug.Assert(compilation.Options.MetadataReferenceResolver != null); var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)); if (references.IsDefaultOrEmpty) { return null; } if (references.Length > 1) { // TODO: implement throw new NotSupportedException(); } return references[0]; } internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies( ImmutableArray<AssemblyIdentity> references, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[references.Length]; for (int j = 0; j < references.Length; j++) { boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } /// <summary> /// Used to match AssemblyRef with AssemblyDef. /// </summary> /// <param name="definitions">Array of definition identities to match against.</param> /// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param> /// <param name="reference">Reference identity to resolve.</param> /// <param name="assemblyIdentityComparer">Assembly identity comparer.</param> /// <returns> /// Returns an index the reference is bound. /// </returns> internal static AssemblyReferenceBinding ResolveReferencedAssembly( AssemblyIdentity reference, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { // Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version. // For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version. // If match.Version != reference.Version a warning is reported. // definition with the lowest version higher than reference version, unless exact version found int minHigherVersionDefinition = -1; int maxLowerVersionDefinition = -1; // Skip assembly being built for now; it will be considered at the very end: bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0; definitionStartIndex = Math.Max(definitionStartIndex, 1); for (int i = definitionStartIndex; i < definitions.Length; i++) { AssemblyIdentity definition = definitions[i].Identity; switch (assemblyIdentityComparer.Compare(reference, definition)) { case AssemblyIdentityComparer.ComparisonResult.NotEquivalent: continue; case AssemblyIdentityComparer.ComparisonResult.Equivalent: return new AssemblyReferenceBinding(reference, i); case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion: if (reference.Version < definition.Version) { // Refers to an older assembly than we have if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version) { minHigherVersionDefinition = i; } } else { Debug.Assert(reference.Version > definition.Version); // Refers to a newer assembly than we have if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version) { maxLowerVersionDefinition = i; } } continue; default: throw ExceptionUtilities.Unreachable; } } // we haven't found definition that matches the reference if (minHigherVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1); } if (maxLowerVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1); } // Handle cases where Windows.winmd is a runtime substitute for a // reference to a compile-time winmd. This is for scenarios such as a // debugger EE which constructs a compilation from the modules of // the running process where Windows.winmd loaded at runtime is a // substitute for a collection of Windows.*.winmd compile-time references. if (reference.IsWindowsComponent()) { for (int i = definitionStartIndex; i < definitions.Length; i++) { if (definitions[i].Identity.IsWindowsRuntime()) { return new AssemblyReferenceBinding(reference, i); } } } // In the IDE it is possible the reference we're looking for is a // compilation reference to a source assembly. However, if the reference // is of ContentType WindowsRuntime then the compilation will never // match since all C#/VB WindowsRuntime compilations output .winmdobjs, // not .winmds, and the ContentType of a .winmdobj is Default. // If this is the case, we want to ignore the ContentType mismatch and // allow the compilation to match the reference. if (reference.ContentType == AssemblyContentType.WindowsRuntime) { for (int i = definitionStartIndex; i < definitions.Length; i++) { var definition = definitions[i].Identity; var sourceCompilation = definitions[i].SourceCompilation; if (definition.ContentType == AssemblyContentType.Default && sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) && reference.Version.Equals(definition.Version) && reference.IsRetargetable == definition.IsRetargetable && AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) && AssemblyIdentity.KeysEqual(reference, definition)) { return new AssemblyReferenceBinding(reference, i); } } } // As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the // compilation (i.e. source) assembly as a last resort. We follow the native approach of // skipping the public key comparison since we have yet to compute it. if (resolveAgainstAssemblyBeingBuilt && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name)) { Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty); return new AssemblyReferenceBinding(reference, 0); } return new AssemblyReferenceBinding(reference); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using MetadataOrDiagnostic = System.Object; /// <summary> /// The base class for language specific assembly managers. /// </summary> /// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam> /// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam> internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol> where TCompilation : Compilation where TAssemblySymbol : class, IAssemblySymbolInternal { protected abstract CommonMessageProvider MessageProvider { get; } protected abstract AssemblyData CreateAssemblyDataForFile( PEAssembly assembly, WeakList<IAssemblySymbolInternal> cachedSymbols, DocumentationProvider documentationProvider, string sourceAssemblySimpleName, MetadataImportOptions importOptions, bool embedInteropTypes); protected abstract AssemblyData CreateAssemblyDataForCompilation( CompilationReference compilationReference); /// <summary> /// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>. /// Reports inconsistencies to the given diagnostic bag. /// </summary> /// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns> protected abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics); /// <summary> /// Called to compare two weakly named identities with the same name. /// </summary> protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2); [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] protected struct ResolvedReference { private readonly MetadataImageKind _kind; private readonly int _index; private readonly ImmutableArray<string> _aliasesOpt; private readonly ImmutableArray<string> _recursiveAliasesOpt; private readonly ImmutableArray<MetadataReference> _mergedReferencesOpt; // uninitialized aliases public ResolvedReference(int index, MetadataImageKind kind) { Debug.Assert(index >= 0); _index = index + 1; _kind = kind; _aliasesOpt = default(ImmutableArray<string>); _recursiveAliasesOpt = default(ImmutableArray<string>); _mergedReferencesOpt = default(ImmutableArray<MetadataReference>); } // initialized aliases public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt, ImmutableArray<MetadataReference> mergedReferences) : this(index, kind) { // We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged. Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault); Debug.Assert(!mergedReferences.IsDefault); _aliasesOpt = aliasesOpt; _recursiveAliasesOpt = recursiveAliasesOpt; _mergedReferencesOpt = mergedReferences; } private bool IsUninitialized => (_aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault) || _mergedReferencesOpt.IsDefault; /// <summary> /// Aliases that should be applied to the referenced assembly. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has recursive aliases). /// </summary> public ImmutableArray<string> AliasesOpt { get { Debug.Assert(!IsUninitialized); return _aliasesOpt; } } /// <summary> /// Aliases that should be applied recursively to all dependent assemblies. /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification). /// Null if not applicable (the reference only has simple aliases). /// </summary> public ImmutableArray<string> RecursiveAliasesOpt { get { Debug.Assert(!IsUninitialized); return _recursiveAliasesOpt; } } public ImmutableArray<MetadataReference> MergedReferences { get { Debug.Assert(!IsUninitialized); return _mergedReferencesOpt; } } /// <summary> /// default(<see cref="ResolvedReference"/>) is considered skipped. /// </summary> public bool IsSkipped { get { return _index == 0; } } public MetadataImageKind Kind { get { Debug.Assert(!IsSkipped); return _kind; } } /// <summary> /// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>. /// </summary> public int Index { get { Debug.Assert(!IsSkipped); return _index - 1; } } private string GetDebuggerDisplay() { return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}"; } private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name) { return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'"; } } protected readonly struct ReferencedAssemblyIdentity { public readonly AssemblyIdentity? Identity; public readonly MetadataReference? Reference; /// <summary> /// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies. /// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies. /// </summary> public readonly int RelativeAssemblyIndex; public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) => RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex; public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex) { Identity = identity; Reference = reference; RelativeAssemblyIndex = relativeAssemblyIndex; } } /// <summary> /// Resolves given metadata references to assemblies and modules. /// </summary> /// <param name="compilation">The compilation whose references are being resolved.</param> /// <param name="assemblyReferencesBySimpleName"> /// Used to filter out assemblies that have the same strong or weak identity. /// Maps simple name to a list of identities. The highest version of each name is the first. /// </param> /// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param> /// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param> /// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param> /// <param name="assemblies">List where to store information about resolved assemblies to.</param> /// <param name="modules">List where to store information about resolved modules to.</param> /// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param> /// <returns> /// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively. ///</returns> protected ImmutableArray<ResolvedReference> ResolveMetadataReferences( TCompilation compilation, [Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectiveMap, out ImmutableArray<MetadataReference> boundReferenceDirectives, out ImmutableArray<AssemblyData> assemblies, out ImmutableArray<PEModule> modules, DiagnosticBag diagnostics) { // Locations of all #r directives in the order they are listed in the references list. ImmutableArray<Location> referenceDirectiveLocations; GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations); // References originating from #r directives precede references supplied as arguments of the compilation. int referenceCount = references.Length; int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0); var referenceMap = new ResolvedReference[referenceCount]; // Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that // can be used to alias these references. Duplicate assemblies contribute their aliases into this set. Dictionary<MetadataReference, MergedAliases>? lazyAliasMap = null; // Used to filter out duplicate references that reference the same file (resolve to the same full normalized path). var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance); ArrayBuilder<MetadataReference>? uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null; var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance(); ArrayBuilder<PEModule>? lazyModulesBuilder = null; bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions; // When duplicate references with conflicting EmbedInteropTypes flag are encountered, // VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order // so that we find the one that matters first. for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--) { var boundReference = references[referenceIndex]; if (boundReference == null) { continue; } // add bound reference if it doesn't exist yet, merging aliases: MetadataReference? existingReference; if (boundReferences.TryGetValue(boundReference, out existingReference)) { // merge properties of compilation-based references if the underlying compilations are the same if ((object)boundReference != existingReference) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); } continue; } boundReferences.Add(boundReference, boundReference); Location location; if (referenceIndex < referenceDirectiveCount) { location = referenceDirectiveLocations[referenceIndex]; uniqueDirectiveReferences!.Add(boundReference); } else { location = Location.None; } // compilation reference var compilationReference = boundReference as CompilationReference; if (compilationReference != null) { switch (compilationReference.Properties.Kind) { case MetadataImageKind.Assembly: existingReference = TryAddAssembly( compilationReference.Compilation.Assembly.Identity, boundReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } // Note, if SourceAssemblySymbol hasn't been created for // compilationAssembly.Compilation yet, we want this to happen // right now. Conveniently, this constructor will trigger creation of the // SourceAssemblySymbol. var asmData = CreateAssemblyDataForCompilation(compilationReference); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); break; default: throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind); } continue; } // PE reference var peReference = (PortableExecutableReference)boundReference; Metadata? metadata = GetMetadata(peReference, MessageProvider, location, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata != null) { switch (peReference.Properties.Kind) { case MetadataImageKind.Assembly: var assemblyMetadata = (AssemblyMetadata)metadata; WeakList<IAssemblySymbolInternal> cachedSymbols = assemblyMetadata.CachedSymbols; if (assemblyMetadata.IsValidAssembly()) { PEAssembly? assembly = assemblyMetadata.GetAssembly(); Debug.Assert(assembly is object); existingReference = TryAddAssembly( assembly.Identity, peReference, -assembliesBuilder.Count - 1, diagnostics, location, assemblyReferencesBySimpleName, supersedeLowerVersions); if (existingReference != null) { MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap); continue; } var asmData = CreateAssemblyDataForFile( assembly, cachedSymbols, peReference.DocumentationProvider, SimpleAssemblyName, compilation.Options.MetadataImportOptions, peReference.Properties.EmbedInteropTypes); AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display ?? "")); } // asmData keeps strong ref after this point GC.KeepAlive(assemblyMetadata); break; case MetadataImageKind.Module: var moduleMetadata = (ModuleMetadata)metadata; if (moduleMetadata.Module.IsLinkedModule) { // We don't support netmodules since some checks in the compiler need information from the full PE image // (Machine, Bit32Required, PE image hash). if (!moduleMetadata.Module.IsEntireImageAvailable) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display ?? "")); } AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder); } else { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display ?? "")); } break; default: throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind); } } } if (uniqueDirectiveReferences != null) { uniqueDirectiveReferences.ReverseContents(); boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree(); } else { boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty; } // We enumerated references in reverse order in the above code // and thus assemblies and modules in the builders are reversed. // Fix up all the indices and reverse the builder content now to get // the ordering matching the references. // // Also fills in aliases. for (int i = 0; i < referenceMap.Length; i++) { if (!referenceMap[i].IsSkipped) { int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0; int reversedIndex = count - 1 - referenceMap[i].Index; referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap); } } assembliesBuilder.ReverseContents(); assemblies = assembliesBuilder.ToImmutableAndFree(); if (lazyModulesBuilder == null) { modules = ImmutableArray<PEModule>.Empty; } else { lazyModulesBuilder.ReverseContents(); modules = lazyModulesBuilder.ToImmutableAndFree(); } return ImmutableArray.CreateRange(referenceMap); } private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases>? propertyMapOpt) { ImmutableArray<string> aliasesOpt, recursiveAliasesOpt; var mergedReferences = ImmutableArray<MetadataReference>.Empty; if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out MergedAliases? mergedProperties)) { aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>); if (mergedProperties.MergedReferencesOpt is object) { mergedReferences = mergedProperties.MergedReferencesOpt.ToImmutableAndFree(); } } else if (reference.Properties.HasRecursiveAliases) { aliasesOpt = default(ImmutableArray<string>); recursiveAliasesOpt = reference.Properties.Aliases; } else { aliasesOpt = reference.Properties.Aliases; recursiveAliasesOpt = default(ImmutableArray<string>); } return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt, mergedReferences); } /// <summary> /// Creates or gets metadata for PE reference. /// </summary> /// <remarks> /// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>, /// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>. /// </remarks> private Metadata? GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics) { Metadata? existingMetadata; lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } } Metadata? newMetadata; Diagnostic? newDiagnostic = null; try { newMetadata = peReference.GetMetadataNoCopy(); // make sure basic structure of the PE image is valid: if (newMetadata is AssemblyMetadata assemblyMetadata) { _ = assemblyMetadata.IsValidAssembly(); } else { _ = ((ModuleMetadata)newMetadata).Module.IsLinkedModule; } } catch (Exception e) when (e is BadImageFormatException || e is IOException) { newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display ?? "", peReference.Properties.Kind); newMetadata = null; } lock (ObservedMetadata) { if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata)) { return existingMetadata; } if (newDiagnostic != null) { diagnostics.Add(newDiagnostic); } ObservedMetadata.Add(peReference, (MetadataOrDiagnostic?)newMetadata ?? newDiagnostic!); return newMetadata; } } private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata? metadata) { if (ObservedMetadata.TryGetValue(peReference, out MetadataOrDiagnostic? existing)) { Debug.Assert(existing is Metadata || existing is Diagnostic); metadata = existing as Metadata; if (metadata == null) { diagnostics.Add((Diagnostic)existing); } return true; } metadata = null; return false; } internal AssemblyMetadata? GetAssemblyMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics) { var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics); Debug.Assert(metadata != null || diagnostics.HasAnyErrors()); if (metadata == null) { return null; } // require the metadata to be a valid assembly metadata: var assemblyMetadata = metadata as AssemblyMetadata; if (assemblyMetadata?.IsValidAssembly() != true) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display ?? "")); return null; } return assemblyMetadata; } /// <summary> /// Determines whether references are the same. Compilation references are the same if they refer to the same compilation. /// Otherwise, references are represented by their object identities. /// </summary> internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference> { internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer(); public bool Equals(MetadataReference? x, MetadataReference? y) { if (ReferenceEquals(x, y)) { return true; } var cx = x as CompilationReference; if (cx != null) { var cy = y as CompilationReference; if (cy != null) { return (object)cx.Compilation == cy.Compilation; } } return false; } public int GetHashCode(MetadataReference reference) { var compilationReference = reference as CompilationReference; if (compilationReference != null) { return RuntimeHelpers.GetHashCode(compilationReference.Compilation); } return RuntimeHelpers.GetHashCode(reference); } } /// <summary> /// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>). /// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols. /// </summary> private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases>? lazyAliasMap) { if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics)) { return; } if (lazyAliasMap == null) { lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>(); } MergedAliases? mergedAliases; if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases)) { mergedAliases = new MergedAliases(); lazyAliasMap.Add(primaryReference, mergedAliases); mergedAliases.Merge(primaryReference); } mergedAliases.Merge(newReference); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies) { // aliases will be filled in later: referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly); assemblies.Add(data); } /// <remarks> /// Caller is responsible for freeing any allocated ArrayBuilders. /// </remarks> private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, [NotNull] ref ArrayBuilder<PEModule>? modules) { if (modules == null) { modules = ArrayBuilder<PEModule>.GetInstance(); } referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module); modules.Add(module); } /// <summary> /// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it. /// Two identities are considered equivalent if /// - both assembly names are strong (have keys) and are either equal or FX unified /// - both assembly names are weak (no keys) and have the same simple name. /// </summary> private MetadataReference? TryAddAssembly( AssemblyIdentity identity, MetadataReference reference, int assemblyIndex, DiagnosticBag diagnostics, Location location, Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName, bool supersedeLowerVersions) { var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex); List<ReferencedAssemblyIdentity>? sameSimpleNameIdentities; if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities)) { referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly }); return null; } if (supersedeLowerVersions) { foreach (var other in sameSimpleNameIdentities) { Debug.Assert(other.Identity is object); if (identity.Version == other.Identity.Version) { return other.Reference; } } // Keep all versions of the assembly and the first identity in the list the one with the highest version: if (sameSimpleNameIdentities[0].Identity!.Version > identity.Version) { sameSimpleNameIdentities.Add(referencedAssembly); } else { sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]); sameSimpleNameIdentities[0] = referencedAssembly; } return null; } ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity); if (identity.IsStrongName) { foreach (var other in sameSimpleNameIdentities) { // Only compare strong with strong (weak is never equivalent to strong and vice versa). // In order to eliminate duplicate references we need to try to match their identities in both directions since // ReferenceMatchesDefinition is not necessarily symmetric. // (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.) Debug.Assert(other.Identity is object); if (other.Identity.IsStrongName && IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) && IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity)) { equivalent = other; break; } } } else { foreach (var other in sameSimpleNameIdentities) { // only compare weak with weak Debug.Assert(other.Identity is object); if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity)) { equivalent = other; break; } } } if (equivalent.Identity == null) { sameSimpleNameIdentities.Add(referencedAssembly); return null; } // equivalent found - ignore and/or report an error: if (identity.IsStrongName) { Debug.Assert(equivalent.Identity.IsStrongName); // versions might have been unified for a Framework assembly: if (identity != equivalent.Identity) { // Dev12 C# reports an error // Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used. // BREAKING CHANGE in VB: we report an error for both languages // Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references. MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } // If the versions match exactly we ignore duplicates w/o reporting errors while // Dev12 C# reports: // error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references. // Dev12 VB reports: // Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System. // A second reference to 'D:\Temp\System.dll' cannot be added. } else { Debug.Assert(!equivalent.Identity.IsStrongName); // Dev12 reports an error for all weak-named assemblies, even if the versions are the same. // We treat assemblies with the same name and version equal even if they don't have a strong name. // This change allows us to de-duplicate #r references based on identities rather than full paths, // and is closer to platforms that don't support strong names and consider name and version enough // to identify an assembly. An identity without version is considered to have version 0.0.0.0. if (identity != equivalent.Identity) { MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference!, equivalent.Identity); } } Debug.Assert(equivalent.Reference != null); return equivalent.Reference; } protected void GetCompilationReferences( TCompilation compilation, DiagnosticBag diagnostics, out ImmutableArray<MetadataReference> references, out IDictionary<(string, string), MetadataReference> boundReferenceDirectives, out ImmutableArray<Location> referenceDirectiveLocations) { ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance(); ArrayBuilder<Location>? referenceDirectiveLocationsBuilder = null; IDictionary<(string, string), MetadataReference>? localBoundReferenceDirectives = null; try { foreach (var referenceDirective in compilation.ReferenceDirectives) { Debug.Assert(referenceDirective.Location is object); if (compilation.Options.MetadataReferenceResolver == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location)); break; } // we already successfully bound #r with the same value: Debug.Assert(referenceDirective.File is object); Debug.Assert(referenceDirective.Location.SourceTree is object); if (localBoundReferenceDirectives != null && localBoundReferenceDirectives.ContainsKey((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File))) { continue; } MetadataReference? boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation); if (boundReference == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File)); continue; } if (localBoundReferenceDirectives == null) { localBoundReferenceDirectives = new Dictionary<(string, string), MetadataReference>(); referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance(); } referencesBuilder.Add(boundReference); referenceDirectiveLocationsBuilder!.Add(referenceDirective.Location); localBoundReferenceDirectives.Add((referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference); } // add external reference at the end, so that they are processed first: referencesBuilder.AddRange(compilation.ExternalReferences); // Add all explicit references of the previous script compilation. var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousScriptCompilation != null) { referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences); } if (localBoundReferenceDirectives == null) { // no directive references resolved successfully: localBoundReferenceDirectives = SpecializedCollections.EmptyDictionary<(string, string), MetadataReference>(); } boundReferenceDirectives = localBoundReferenceDirectives; references = referencesBuilder.ToImmutable(); referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray<Location>.Empty; } finally { // Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and // we don't want to clutter the test output with leak reports. referencesBuilder.Free(); } } /// <summary> /// For each given directive return a bound PE reference, or null if the binding fails. /// </summary> private static PortableExecutableReference? ResolveReferenceDirective(string reference, Location location, TCompilation compilation) { var tree = location.SourceTree; string? basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null; // checked earlier: Debug.Assert(compilation.Options.MetadataReferenceResolver != null); var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true)); if (references.IsDefaultOrEmpty) { return null; } if (references.Length > 1) { // TODO: implement throw new NotSupportedException(); } return references[0]; } internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies( ImmutableArray<AssemblyIdentity> references, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[references.Length]; for (int j = 0; j < references.Length; j++) { boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } /// <summary> /// Used to match AssemblyRef with AssemblyDef. /// </summary> /// <param name="definitions">Array of definition identities to match against.</param> /// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param> /// <param name="reference">Reference identity to resolve.</param> /// <param name="assemblyIdentityComparer">Assembly identity comparer.</param> /// <returns> /// Returns an index the reference is bound. /// </returns> internal static AssemblyReferenceBinding ResolveReferencedAssembly( AssemblyIdentity reference, ImmutableArray<AssemblyData> definitions, int definitionStartIndex, AssemblyIdentityComparer assemblyIdentityComparer) { // Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version. // For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version. // If match.Version != reference.Version a warning is reported. // definition with the lowest version higher than reference version, unless exact version found int minHigherVersionDefinition = -1; int maxLowerVersionDefinition = -1; // Skip assembly being built for now; it will be considered at the very end: bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0; definitionStartIndex = Math.Max(definitionStartIndex, 1); for (int i = definitionStartIndex; i < definitions.Length; i++) { AssemblyIdentity definition = definitions[i].Identity; switch (assemblyIdentityComparer.Compare(reference, definition)) { case AssemblyIdentityComparer.ComparisonResult.NotEquivalent: continue; case AssemblyIdentityComparer.ComparisonResult.Equivalent: return new AssemblyReferenceBinding(reference, i); case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion: if (reference.Version < definition.Version) { // Refers to an older assembly than we have if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version) { minHigherVersionDefinition = i; } } else { Debug.Assert(reference.Version > definition.Version); // Refers to a newer assembly than we have if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version) { maxLowerVersionDefinition = i; } } continue; default: throw ExceptionUtilities.Unreachable; } } // we haven't found definition that matches the reference if (minHigherVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1); } if (maxLowerVersionDefinition != -1) { return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1); } // Handle cases where Windows.winmd is a runtime substitute for a // reference to a compile-time winmd. This is for scenarios such as a // debugger EE which constructs a compilation from the modules of // the running process where Windows.winmd loaded at runtime is a // substitute for a collection of Windows.*.winmd compile-time references. if (reference.IsWindowsComponent()) { for (int i = definitionStartIndex; i < definitions.Length; i++) { if (definitions[i].Identity.IsWindowsRuntime()) { return new AssemblyReferenceBinding(reference, i); } } } // In the IDE it is possible the reference we're looking for is a // compilation reference to a source assembly. However, if the reference // is of ContentType WindowsRuntime then the compilation will never // match since all C#/VB WindowsRuntime compilations output .winmdobjs, // not .winmds, and the ContentType of a .winmdobj is Default. // If this is the case, we want to ignore the ContentType mismatch and // allow the compilation to match the reference. if (reference.ContentType == AssemblyContentType.WindowsRuntime) { for (int i = definitionStartIndex; i < definitions.Length; i++) { var definition = definitions[i].Identity; var sourceCompilation = definitions[i].SourceCompilation; if (definition.ContentType == AssemblyContentType.Default && sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) && reference.Version.Equals(definition.Version) && reference.IsRetargetable == definition.IsRetargetable && AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) && AssemblyIdentity.KeysEqual(reference, definition)) { return new AssemblyReferenceBinding(reference, i); } } } // As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the // compilation (i.e. source) assembly as a last resort. We follow the native approach of // skipping the public key comparison since we have yet to compute it. if (resolveAgainstAssemblyBeingBuilt && AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name)) { Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty); return new AssemblyReferenceBinding(reference, 0); } return new AssemblyReferenceBinding(reference); } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/VisualBasic/vbc/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine { public class Program { public static int Main(string[] args) { try { return MainCore(args); } catch (FileNotFoundException e) { // Catch exception from missing compiler assembly. // Report the exception message and terminate the process. Console.WriteLine(e.Message); return CommonCompiler.Failed; } } private static int MainCore(string[] args) { using var logger = new CompilerServerLogger($"vbc {Process.GetCurrentProcess().Id}"); #if BOOTSTRAP ExitingTraceListener.Install(logger); #endif return BuildClient.Run(args, RequestLanguage.VisualBasicCompile, Vbc.Run, BuildClient.GetCompileOnServerFunc(logger)); } public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader) => Vbc.Run(args, new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir), textWriter, analyzerLoader); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.VisualBasic.CommandLine { public class Program { public static int Main(string[] args) { try { return MainCore(args); } catch (FileNotFoundException e) { // Catch exception from missing compiler assembly. // Report the exception message and terminate the process. Console.WriteLine(e.Message); return CommonCompiler.Failed; } } private static int MainCore(string[] args) { using var logger = new CompilerServerLogger($"vbc {Process.GetCurrentProcess().Id}"); #if BOOTSTRAP ExitingTraceListener.Install(logger); #endif return BuildClient.Run(args, RequestLanguage.VisualBasicCompile, Vbc.Run, BuildClient.GetCompileOnServerFunc(logger)); } public static int Run(string[] args, string clientDir, string workingDir, string sdkDir, string tempDir, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader) => Vbc.Run(args, new BuildPaths(clientDir: clientDir, workingDir: workingDir, sdkDir: sdkDir, tempDir: tempDir), textWriter, analyzerLoader); } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceParameterService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal abstract partial class AbstractIntroduceParameterService< TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> : CodeRefactoringProvider where TExpressionSyntax : SyntaxNode where TInvocationExpressionSyntax : TExpressionSyntax where TObjectCreationExpressionSyntax : TExpressionSyntax where TIdentifierNameSyntax : TExpressionSyntax { protected abstract SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol); protected abstract SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments); protected abstract SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl); protected abstract bool IsDestructor(IMethodSymbol methodSymbol); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var expression = await document.TryGetRelevantNodeAsync<TExpressionSyntax>(textSpan, cancellationToken).ConfigureAwait(false); if (expression == null || CodeRefactoringHelpers.IsNodeUnderselected(expression, textSpan)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType is null or IErrorTypeSymbol) { return; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Need to special case for expressions that are contained within a parameter // because it is technically "contained" within a method, but an expression in a parameter does not make // sense to introduce. var parameterNode = expression.FirstAncestorOrSelf<SyntaxNode>(node => syntaxFacts.IsParameter(node)); if (parameterNode is not null) { return; } // Need to special case for highlighting of method types because they are also "contained" within a method, // but it does not make sense to introduce a parameter in that case. if (syntaxFacts.IsInNamespaceOrTypeContext(expression)) { return; } // Need to special case for expressions whose direct parent is a MemberAccessExpression since they will // never introduce a parameter that makes sense in that case. if (syntaxFacts.IsNameOfAnyMemberAccessExpression(expression)) { return; } var generator = SyntaxGenerator.GetGenerator(document); var containingMethod = expression.FirstAncestorOrSelf<SyntaxNode>(node => generator.GetParameterListNode(node) is not null); if (containingMethod is null) { return; } var containingSymbol = semanticModel.GetDeclaredSymbol(containingMethod, cancellationToken); if (containingSymbol is not IMethodSymbol methodSymbol) { return; } // Code actions for trampoline and overloads will not be offered if the method is a constructor. // Code actions for overloads will not be offered if the method if the method is a local function. var methodKind = methodSymbol.MethodKind; if (methodKind is not (MethodKind.Ordinary or MethodKind.LocalFunction or MethodKind.Constructor)) { return; } if (IsDestructor(methodSymbol)) { return; } var actions = await GetActionsAsync(document, expression, methodSymbol, containingMethod, cancellationToken).ConfigureAwait(false); if (actions is null) { return; } var singleLineExpression = syntaxFacts.ConvertToSingleLine(expression); var nodeString = singleLineExpression.ToString(); if (actions.Value.actions.Length > 0) { context.RegisterRefactoring(new CodeActionWithNestedActions( string.Format(FeaturesResources.Introduce_parameter_for_0, nodeString), actions.Value.actions, isInlinable: false), textSpan); } if (actions.Value.actionsAllOccurrences.Length > 0) { context.RegisterRefactoring(new CodeActionWithNestedActions( string.Format(FeaturesResources.Introduce_parameter_for_all_occurrences_of_0, nodeString), actions.Value.actionsAllOccurrences, isInlinable: false), textSpan); } } /// <summary> /// Creates new code actions for each introduce parameter possibility. /// Does not create actions for overloads/trampoline if there are optional parameters or if the methodSymbol /// is a constructor. /// </summary> private async Task<(ImmutableArray<CodeAction> actions, ImmutableArray<CodeAction> actionsAllOccurrences)?> GetActionsAsync(Document document, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, CancellationToken cancellationToken) { var (shouldDisplay, containsClassExpression) = await ShouldExpressionDisplayCodeActionAsync( document, expression, cancellationToken).ConfigureAwait(false); if (!shouldDisplay) { return null; } using var actionsBuilder = TemporaryArray<CodeAction>.Empty; using var actionsBuilderAllOccurrences = TemporaryArray<CodeAction>.Empty; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (!containsClassExpression) { actionsBuilder.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: false, IntroduceParameterCodeActionKind.Refactor)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: true, IntroduceParameterCodeActionKind.Refactor)); } if (methodSymbol.MethodKind is not MethodKind.Constructor) { actionsBuilder.Add(CreateNewCodeAction( FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: false, IntroduceParameterCodeActionKind.Trampoline)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction( FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: true, IntroduceParameterCodeActionKind.Trampoline)); if (methodSymbol.MethodKind is not MethodKind.LocalFunction) { actionsBuilder.Add(CreateNewCodeAction( FeaturesResources.into_new_overload, allOccurrences: false, IntroduceParameterCodeActionKind.Overload)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction( FeaturesResources.into_new_overload, allOccurrences: true, IntroduceParameterCodeActionKind.Overload)); } } return (actionsBuilder.ToImmutableAndClear(), actionsBuilderAllOccurrences.ToImmutableAndClear()); // Local function to create a code action with more ease MyCodeAction CreateNewCodeAction(string actionName, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction) { return new MyCodeAction(actionName, c => IntroduceParameterAsync( document, expression, methodSymbol, containingMethod, allOccurrences, selectedCodeAction, c)); } } /// <summary> /// Determines if the expression is something that should have code actions displayed for it. /// Depends upon the identifiers in the expression mapping back to parameters. /// Does not handle params parameters. /// </summary> private static async Task<(bool shouldDisplay, bool containsClassExpression)> ShouldExpressionDisplayCodeActionAsync( Document document, TExpressionSyntax expression, CancellationToken cancellationToken) { var variablesInExpression = expression.DescendantNodes(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var variable in variablesInExpression) { var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol; // If the expression contains locals or range variables then we do not want to offer // code actions since there will be errors at call sites. if (symbol is IRangeVariableSymbol or ILocalSymbol) { return (false, false); } if (symbol is IParameterSymbol parameter) { // We do not want to offer code actions if the expressions contains references // to params parameters because it is difficult to know what is being referenced // at the callsites. if (parameter.IsParams) { return (false, false); } } } // If expression contains this or base keywords, implicitly or explicitly, // then we do not want to refactor call sites that are not overloads/trampolines // because we do not know if the class specific information is available in other documents. var operation = semanticModel.GetOperation(expression, cancellationToken); var containsClassSpecificStatement = false; if (operation is not null) { containsClassSpecificStatement = operation.Descendants().Any(op => op.Kind == OperationKind.InstanceReference); } return (true, containsClassSpecificStatement); } /// <summary> /// Introduces a new parameter and refactors all the call sites based on the selected code action. /// </summary> private async Task<Solution> IntroduceParameterAsync(Document originalDocument, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction, CancellationToken cancellationToken) { var methodCallSites = await FindCallSitesAsync(originalDocument, methodSymbol, cancellationToken).ConfigureAwait(false); var modifiedSolution = originalDocument.Project.Solution; var rewriter = new IntroduceParameterDocumentRewriter(this, originalDocument, expression, methodSymbol, containingMethod, selectedCodeAction, allOccurrences); foreach (var (project, projectCallSites) in methodCallSites.GroupBy(kvp => kvp.Key.Project)) { var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var (document, invocations) in projectCallSites) { var newRoot = await rewriter.RewriteDocumentAsync(compilation, document, invocations, cancellationToken).ConfigureAwait(false); modifiedSolution = modifiedSolution.WithDocumentSyntaxRoot(originalDocument.Id, newRoot); } } return modifiedSolution; } /// <summary> /// Locates all the call sites of the method that introduced the parameter /// </summary> protected static async Task<Dictionary<Document, List<SyntaxNode>>> FindCallSitesAsync( Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken) { var methodCallSites = new Dictionary<Document, List<SyntaxNode>>(); var progress = new StreamingProgressCollector(); await SymbolFinder.FindReferencesAsync( methodSymbol, document.Project.Solution, progress, documents: null, FindReferencesSearchOptions.Default, cancellationToken).ConfigureAwait(false); var referencedSymbols = progress.GetReferencedSymbols(); // Ordering by descending to sort invocations by starting span to account for nested invocations var referencedLocations = referencedSymbols.SelectMany(referencedSymbol => referencedSymbol.Locations) .Distinct().Where(reference => !reference.IsImplicit) .OrderByDescending(reference => reference.Location.SourceSpan.Start); // Adding the original document to ensure that it will be seen again when processing the call sites // in order to update the original expression and containing method. methodCallSites.Add(document, new List<SyntaxNode>()); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var refLocation in referencedLocations) { // Does not support cross-language references currently if (refLocation.Document.Project.Language == document.Project.Language) { var reference = refLocation.Location.FindNode(cancellationToken).GetRequiredParent(); if (reference is not (TObjectCreationExpressionSyntax or TInvocationExpressionSyntax)) { reference = reference.GetRequiredParent(); } // Only adding items that are of type InvocationExpressionSyntax or TObjectCreationExpressionSyntax var invocationOrCreation = reference as TObjectCreationExpressionSyntax ?? (SyntaxNode?)(reference as TInvocationExpressionSyntax); if (invocationOrCreation is null) { continue; } if (!methodCallSites.TryGetValue(refLocation.Document, out var list)) { list = new List<SyntaxNode>(); methodCallSites.Add(refLocation.Document, list); } list.Add(invocationOrCreation); } } return methodCallSites; } private class MyCodeAction : SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } private enum IntroduceParameterCodeActionKind { Refactor, Trampoline, Overload } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeActions.CodeAction; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal abstract partial class AbstractIntroduceParameterService< TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> : CodeRefactoringProvider where TExpressionSyntax : SyntaxNode where TInvocationExpressionSyntax : TExpressionSyntax where TObjectCreationExpressionSyntax : TExpressionSyntax where TIdentifierNameSyntax : TExpressionSyntax { protected abstract SyntaxNode GenerateExpressionFromOptionalParameter(IParameterSymbol parameterSymbol); protected abstract SyntaxNode UpdateArgumentListSyntax(SyntaxNode argumentList, SeparatedSyntaxList<SyntaxNode> arguments); protected abstract SyntaxNode? GetLocalDeclarationFromDeclarator(SyntaxNode variableDecl); protected abstract bool IsDestructor(IMethodSymbol methodSymbol); public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var expression = await document.TryGetRelevantNodeAsync<TExpressionSyntax>(textSpan, cancellationToken).ConfigureAwait(false); if (expression == null || CodeRefactoringHelpers.IsNodeUnderselected(expression, textSpan)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType is null or IErrorTypeSymbol) { return; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Need to special case for expressions that are contained within a parameter // because it is technically "contained" within a method, but an expression in a parameter does not make // sense to introduce. var parameterNode = expression.FirstAncestorOrSelf<SyntaxNode>(node => syntaxFacts.IsParameter(node)); if (parameterNode is not null) { return; } // Need to special case for highlighting of method types because they are also "contained" within a method, // but it does not make sense to introduce a parameter in that case. if (syntaxFacts.IsInNamespaceOrTypeContext(expression)) { return; } // Need to special case for expressions whose direct parent is a MemberAccessExpression since they will // never introduce a parameter that makes sense in that case. if (syntaxFacts.IsNameOfAnyMemberAccessExpression(expression)) { return; } var generator = SyntaxGenerator.GetGenerator(document); var containingMethod = expression.FirstAncestorOrSelf<SyntaxNode>(node => generator.GetParameterListNode(node) is not null); if (containingMethod is null) { return; } var containingSymbol = semanticModel.GetDeclaredSymbol(containingMethod, cancellationToken); if (containingSymbol is not IMethodSymbol methodSymbol) { return; } // Code actions for trampoline and overloads will not be offered if the method is a constructor. // Code actions for overloads will not be offered if the method if the method is a local function. var methodKind = methodSymbol.MethodKind; if (methodKind is not (MethodKind.Ordinary or MethodKind.LocalFunction or MethodKind.Constructor)) { return; } if (IsDestructor(methodSymbol)) { return; } var actions = await GetActionsAsync(document, expression, methodSymbol, containingMethod, cancellationToken).ConfigureAwait(false); if (actions is null) { return; } var singleLineExpression = syntaxFacts.ConvertToSingleLine(expression); var nodeString = singleLineExpression.ToString(); if (actions.Value.actions.Length > 0) { context.RegisterRefactoring(new CodeActionWithNestedActions( string.Format(FeaturesResources.Introduce_parameter_for_0, nodeString), actions.Value.actions, isInlinable: false), textSpan); } if (actions.Value.actionsAllOccurrences.Length > 0) { context.RegisterRefactoring(new CodeActionWithNestedActions( string.Format(FeaturesResources.Introduce_parameter_for_all_occurrences_of_0, nodeString), actions.Value.actionsAllOccurrences, isInlinable: false), textSpan); } } /// <summary> /// Creates new code actions for each introduce parameter possibility. /// Does not create actions for overloads/trampoline if there are optional parameters or if the methodSymbol /// is a constructor. /// </summary> private async Task<(ImmutableArray<CodeAction> actions, ImmutableArray<CodeAction> actionsAllOccurrences)?> GetActionsAsync(Document document, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, CancellationToken cancellationToken) { var (shouldDisplay, containsClassExpression) = await ShouldExpressionDisplayCodeActionAsync( document, expression, cancellationToken).ConfigureAwait(false); if (!shouldDisplay) { return null; } using var actionsBuilder = TemporaryArray<CodeAction>.Empty; using var actionsBuilderAllOccurrences = TemporaryArray<CodeAction>.Empty; var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); if (!containsClassExpression) { actionsBuilder.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: false, IntroduceParameterCodeActionKind.Refactor)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction(FeaturesResources.and_update_call_sites_directly, allOccurrences: true, IntroduceParameterCodeActionKind.Refactor)); } if (methodSymbol.MethodKind is not MethodKind.Constructor) { actionsBuilder.Add(CreateNewCodeAction( FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: false, IntroduceParameterCodeActionKind.Trampoline)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction( FeaturesResources.into_extracted_method_to_invoke_at_call_sites, allOccurrences: true, IntroduceParameterCodeActionKind.Trampoline)); if (methodSymbol.MethodKind is not MethodKind.LocalFunction) { actionsBuilder.Add(CreateNewCodeAction( FeaturesResources.into_new_overload, allOccurrences: false, IntroduceParameterCodeActionKind.Overload)); actionsBuilderAllOccurrences.Add(CreateNewCodeAction( FeaturesResources.into_new_overload, allOccurrences: true, IntroduceParameterCodeActionKind.Overload)); } } return (actionsBuilder.ToImmutableAndClear(), actionsBuilderAllOccurrences.ToImmutableAndClear()); // Local function to create a code action with more ease MyCodeAction CreateNewCodeAction(string actionName, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction) { return new MyCodeAction(actionName, c => IntroduceParameterAsync( document, expression, methodSymbol, containingMethod, allOccurrences, selectedCodeAction, c)); } } /// <summary> /// Determines if the expression is something that should have code actions displayed for it. /// Depends upon the identifiers in the expression mapping back to parameters. /// Does not handle params parameters. /// </summary> private static async Task<(bool shouldDisplay, bool containsClassExpression)> ShouldExpressionDisplayCodeActionAsync( Document document, TExpressionSyntax expression, CancellationToken cancellationToken) { var variablesInExpression = expression.DescendantNodes(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var variable in variablesInExpression) { var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol; // If the expression contains locals or range variables then we do not want to offer // code actions since there will be errors at call sites. if (symbol is IRangeVariableSymbol or ILocalSymbol) { return (false, false); } if (symbol is IParameterSymbol parameter) { // We do not want to offer code actions if the expressions contains references // to params parameters because it is difficult to know what is being referenced // at the callsites. if (parameter.IsParams) { return (false, false); } } } // If expression contains this or base keywords, implicitly or explicitly, // then we do not want to refactor call sites that are not overloads/trampolines // because we do not know if the class specific information is available in other documents. var operation = semanticModel.GetOperation(expression, cancellationToken); var containsClassSpecificStatement = false; if (operation is not null) { containsClassSpecificStatement = operation.Descendants().Any(op => op.Kind == OperationKind.InstanceReference); } return (true, containsClassSpecificStatement); } /// <summary> /// Introduces a new parameter and refactors all the call sites based on the selected code action. /// </summary> private async Task<Solution> IntroduceParameterAsync(Document originalDocument, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, bool allOccurrences, IntroduceParameterCodeActionKind selectedCodeAction, CancellationToken cancellationToken) { var methodCallSites = await FindCallSitesAsync(originalDocument, methodSymbol, cancellationToken).ConfigureAwait(false); var modifiedSolution = originalDocument.Project.Solution; var rewriter = new IntroduceParameterDocumentRewriter(this, originalDocument, expression, methodSymbol, containingMethod, selectedCodeAction, allOccurrences); foreach (var (project, projectCallSites) in methodCallSites.GroupBy(kvp => kvp.Key.Project)) { var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); foreach (var (document, invocations) in projectCallSites) { var newRoot = await rewriter.RewriteDocumentAsync(compilation, document, invocations, cancellationToken).ConfigureAwait(false); modifiedSolution = modifiedSolution.WithDocumentSyntaxRoot(originalDocument.Id, newRoot); } } return modifiedSolution; } /// <summary> /// Locates all the call sites of the method that introduced the parameter /// </summary> protected static async Task<Dictionary<Document, List<SyntaxNode>>> FindCallSitesAsync( Document document, IMethodSymbol methodSymbol, CancellationToken cancellationToken) { var methodCallSites = new Dictionary<Document, List<SyntaxNode>>(); var progress = new StreamingProgressCollector(); await SymbolFinder.FindReferencesAsync( methodSymbol, document.Project.Solution, progress, documents: null, FindReferencesSearchOptions.Default, cancellationToken).ConfigureAwait(false); var referencedSymbols = progress.GetReferencedSymbols(); // Ordering by descending to sort invocations by starting span to account for nested invocations var referencedLocations = referencedSymbols.SelectMany(referencedSymbol => referencedSymbol.Locations) .Distinct().Where(reference => !reference.IsImplicit) .OrderByDescending(reference => reference.Location.SourceSpan.Start); // Adding the original document to ensure that it will be seen again when processing the call sites // in order to update the original expression and containing method. methodCallSites.Add(document, new List<SyntaxNode>()); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var refLocation in referencedLocations) { // Does not support cross-language references currently if (refLocation.Document.Project.Language == document.Project.Language) { var reference = refLocation.Location.FindNode(cancellationToken).GetRequiredParent(); if (reference is not (TObjectCreationExpressionSyntax or TInvocationExpressionSyntax)) { reference = reference.GetRequiredParent(); } // Only adding items that are of type InvocationExpressionSyntax or TObjectCreationExpressionSyntax var invocationOrCreation = reference as TObjectCreationExpressionSyntax ?? (SyntaxNode?)(reference as TInvocationExpressionSyntax); if (invocationOrCreation is null) { continue; } if (!methodCallSites.TryGetValue(refLocation.Document, out var list)) { list = new List<SyntaxNode>(); methodCallSites.Add(refLocation.Document, list); } list.Add(invocationOrCreation); } } return methodCallSites; } private class MyCodeAction : SolutionChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } private enum IntroduceParameterCodeActionKind { Refactor, Trampoline, Overload } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/EditorFeatures/CSharpTest/TextStructureNavigation/TextStructureNavigatorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.CSharp.TextStructureNavigation; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TextStructureNavigation { [UseExportProvider] public class TextStructureNavigatorTests { [Fact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Empty() { AssertExtent( string.Empty, pos: 0, isSignificant: false, start: 0, length: 0); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Whitespace() { AssertExtent( " ", pos: 0, isSignificant: false, start: 0, length: 3); AssertExtent( " ", pos: 1, isSignificant: false, start: 0, length: 3); AssertExtent( " ", pos: 3, isSignificant: false, start: 0, length: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void EndOfFile() { AssertExtent( "using System;", pos: 13, isSignificant: true, start: 12, length: 1); } [Fact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void NewLine() { AssertExtent( "class Class1 {\r\n\r\n}", pos: 14, isSignificant: false, start: 14, length: 2); AssertExtent( "class Class1 {\r\n\r\n}", pos: 15, isSignificant: false, start: 14, length: 2); AssertExtent( "class Class1 {\r\n\r\n}", pos: 16, isSignificant: false, start: 16, length: 2); AssertExtent( "class Class1 {\r\n\r\n}", pos: 17, isSignificant: false, start: 16, length: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void SingleLineComment() { AssertExtent( "// Comment ", pos: 0, isSignificant: true, start: 0, length: 12); // It is important that this returns just the comment banner. Returning the whole comment // means Ctrl+Right before the slash will cause it to jump across the entire comment AssertExtent( "// Comment ", pos: 1, isSignificant: true, start: 0, length: 2); AssertExtent( "// Comment ", pos: 5, isSignificant: true, start: 3, length: 7); AssertExtent( "// () test", pos: 4, isSignificant: true, start: 3, length: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void MultiLineComment() { AssertExtent( "/* Comment */", pos: 0, isSignificant: true, start: 0, length: 13); // It is important that this returns just the comment banner. Returning the whole comment // means Ctrl+Right before the slash will cause it to jump across the entire comment AssertExtent( "/* Comment */", pos: 1, isSignificant: true, start: 0, length: 2); AssertExtent( "/* Comment */", pos: 5, isSignificant: true, start: 3, length: 7); AssertExtent( "/* () test */", pos: 4, isSignificant: true, start: 3, length: 2); AssertExtent( "/* () test */", pos: 11, isSignificant: true, start: 11, length: 2); // It is important that this returns just the comment banner. Returning the whole comment // means Ctrl+Left after the slash will cause it to jump across the entire comment AssertExtent( "/* () test */", pos: 12, isSignificant: true, start: 11, length: 2); AssertExtent( "/* () test */", pos: 13, isSignificant: true, start: 11, length: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Keyword() { for (var i = 7; i <= 7 + 4; i++) { AssertExtent( "public class Class1", pos: i, isSignificant: true, start: 7, length: 5); } } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Identifier() { for (var i = 13; i <= 13 + 8; i++) { AssertExtent( "public class SomeClass : IDisposable", pos: i, isSignificant: true, start: 13, length: 9); } } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void EscapedIdentifier() { for (var i = 12; i <= 12 + 9; i++) { AssertExtent( "public enum @interface : int", pos: i, isSignificant: true, start: 12, length: 10); } } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Number() { for (var i = 37; i <= 37 + 10; i++) { AssertExtent( "class Test { private double num = -1.234678e10; }", pos: i, isSignificant: true, start: 37, length: 11); } } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void String() { const string TestString = "class Test { private string s1 = \" () test \"; }"; var startOfString = TestString.IndexOf('"'); var lengthOfStringIncludingQuotes = TestString.LastIndexOf('"') - startOfString + 1; AssertExtent( TestString, pos: startOfString, isSignificant: true, start: startOfString, length: 1); // Selects whitespace AssertExtent( TestString, pos: startOfString + 1, isSignificant: false, start: startOfString + 1, length: 1); AssertExtent( TestString, pos: startOfString + 2, isSignificant: true, start: startOfString + 2, length: 2); AssertExtent( TestString, pos: TestString.IndexOf(" \"", StringComparison.Ordinal), isSignificant: false, start: TestString.IndexOf(" \"", StringComparison.Ordinal), length: 2); AssertExtent( TestString, pos: TestString.LastIndexOf('"'), isSignificant: true, start: startOfString + lengthOfStringIncludingQuotes - 1, length: 1); AssertExtent( TestString, pos: TestString.LastIndexOf('"') + 1, isSignificant: true, start: TestString.LastIndexOf('"') + 1, length: 1); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void InterpolatedString1() { const string TestString = "class Test { string x = \"hello\"; string s = $\" { x } hello\"; }"; var startOfFirstString = TestString.IndexOf('"'); var endOfFirstString = TestString.IndexOf('"', startOfFirstString + 1); var startOfString = TestString.IndexOf("$\"", endOfFirstString + 1, StringComparison.Ordinal); // Selects interpolated string start token AssertExtent( TestString, pos: startOfString, isSignificant: true, start: startOfString, length: 2); // Selects whitespace AssertExtent( TestString, pos: startOfString + 2, isSignificant: false, start: startOfString + 2, length: 1); // Selects the opening curly brace AssertExtent( TestString, pos: startOfString + 3, isSignificant: true, start: startOfString + 3, length: 1); // Selects whitespace AssertExtent( TestString, pos: startOfString + 4, isSignificant: false, start: startOfString + 4, length: 1); // Selects identifier AssertExtent( TestString, pos: startOfString + 5, isSignificant: true, start: startOfString + 5, length: 1); // Selects whitespace AssertExtent( TestString, pos: startOfString + 6, isSignificant: false, start: startOfString + 6, length: 1); // Selects the closing curly brace AssertExtent( TestString, pos: startOfString + 7, isSignificant: true, start: startOfString + 7, length: 1); // Selects whitespace AssertExtent( TestString, pos: startOfString + 8, isSignificant: false, start: startOfString + 8, length: 1); // Selects hello AssertExtent( TestString, pos: startOfString + 9, isSignificant: true, start: startOfString + 9, length: 5); // Selects closing quote AssertExtent( TestString, pos: startOfString + 14, isSignificant: true, start: startOfString + 14, length: 1); } private static void AssertExtent(string code, int pos, bool isSignificant, int start, int length) { AssertExtent(code, pos, isSignificant, start, length, null); AssertExtent(code, pos, isSignificant, start, length, Options.Script); } private static void AssertExtent(string code, int pos, bool isSignificant, int start, int length, CSharpParseOptions options) { using var workspace = TestWorkspace.CreateCSharp(code, options); var buffer = workspace.Documents.First().GetTextBuffer(); var provider = Assert.IsType<TextStructureNavigatorProvider>( workspace.GetService<ITextStructureNavigatorProvider>(ContentTypeNames.CSharpContentType)); var navigator = provider.CreateTextStructureNavigator(buffer); var extent = navigator.GetExtentOfWord(new SnapshotPoint(buffer.CurrentSnapshot, pos)); Assert.Equal(isSignificant, extent.IsSignificant); var expectedSpan = new SnapshotSpan(buffer.CurrentSnapshot, start, length); Assert.Equal(expectedSpan, extent.Span); } private static void TestNavigator( string code, Func<ITextStructureNavigator, SnapshotSpan, SnapshotSpan> func, int startPosition, int startLength, int endPosition, int endLength) { TestNavigator(code, func, startPosition, startLength, endPosition, endLength, null); TestNavigator(code, func, startPosition, startLength, endPosition, endLength, Options.Script); } private static void TestNavigator( string code, Func<ITextStructureNavigator, SnapshotSpan, SnapshotSpan> func, int startPosition, int startLength, int endPosition, int endLength, CSharpParseOptions options) { using var workspace = TestWorkspace.CreateCSharp(code, options); var buffer = workspace.Documents.First().GetTextBuffer(); var provider = Assert.IsType<TextStructureNavigatorProvider>( workspace.GetService<ITextStructureNavigatorProvider>(ContentTypeNames.CSharpContentType)); var navigator = provider.CreateTextStructureNavigator(buffer); var actualSpan = func(navigator, new SnapshotSpan(buffer.CurrentSnapshot, startPosition, startLength)); var expectedSpan = new SnapshotSpan(buffer.CurrentSnapshot, endPosition, endLength); Assert.Equal(expectedSpan, actualSpan.Span); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void GetSpanOfEnclosingTest() { // First operation returns span of 'Class1' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 10, 0, 6, 6); // Second operation returns span of 'class Class1 { }' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 6, 6, 0, 16); // Last operation does nothing TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 0, 16, 0, 16); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void GetSpanOfFirstChildTest() { // Go from 'class Class1 { }' to 'class' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfFirstChild(s), 0, 16, 0, 5); // Next operation should do nothing as we're at the bottom TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfFirstChild(s), 0, 5, 0, 5); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void GetSpanOfNextSiblingTest() { // Go from 'class' to 'Class1' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfNextSibling(s), 0, 5, 6, 6); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void GetSpanOfPreviousSiblingTest() { // Go from '{' to 'Class1' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfPreviousSibling(s), 13, 1, 6, 6); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.CSharp.TextStructureNavigation; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TextStructureNavigation { [UseExportProvider] public class TextStructureNavigatorTests { [Fact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Empty() { AssertExtent( string.Empty, pos: 0, isSignificant: false, start: 0, length: 0); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Whitespace() { AssertExtent( " ", pos: 0, isSignificant: false, start: 0, length: 3); AssertExtent( " ", pos: 1, isSignificant: false, start: 0, length: 3); AssertExtent( " ", pos: 3, isSignificant: false, start: 0, length: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void EndOfFile() { AssertExtent( "using System;", pos: 13, isSignificant: true, start: 12, length: 1); } [Fact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void NewLine() { AssertExtent( "class Class1 {\r\n\r\n}", pos: 14, isSignificant: false, start: 14, length: 2); AssertExtent( "class Class1 {\r\n\r\n}", pos: 15, isSignificant: false, start: 14, length: 2); AssertExtent( "class Class1 {\r\n\r\n}", pos: 16, isSignificant: false, start: 16, length: 2); AssertExtent( "class Class1 {\r\n\r\n}", pos: 17, isSignificant: false, start: 16, length: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void SingleLineComment() { AssertExtent( "// Comment ", pos: 0, isSignificant: true, start: 0, length: 12); // It is important that this returns just the comment banner. Returning the whole comment // means Ctrl+Right before the slash will cause it to jump across the entire comment AssertExtent( "// Comment ", pos: 1, isSignificant: true, start: 0, length: 2); AssertExtent( "// Comment ", pos: 5, isSignificant: true, start: 3, length: 7); AssertExtent( "// () test", pos: 4, isSignificant: true, start: 3, length: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void MultiLineComment() { AssertExtent( "/* Comment */", pos: 0, isSignificant: true, start: 0, length: 13); // It is important that this returns just the comment banner. Returning the whole comment // means Ctrl+Right before the slash will cause it to jump across the entire comment AssertExtent( "/* Comment */", pos: 1, isSignificant: true, start: 0, length: 2); AssertExtent( "/* Comment */", pos: 5, isSignificant: true, start: 3, length: 7); AssertExtent( "/* () test */", pos: 4, isSignificant: true, start: 3, length: 2); AssertExtent( "/* () test */", pos: 11, isSignificant: true, start: 11, length: 2); // It is important that this returns just the comment banner. Returning the whole comment // means Ctrl+Left after the slash will cause it to jump across the entire comment AssertExtent( "/* () test */", pos: 12, isSignificant: true, start: 11, length: 2); AssertExtent( "/* () test */", pos: 13, isSignificant: true, start: 11, length: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Keyword() { for (var i = 7; i <= 7 + 4; i++) { AssertExtent( "public class Class1", pos: i, isSignificant: true, start: 7, length: 5); } } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Identifier() { for (var i = 13; i <= 13 + 8; i++) { AssertExtent( "public class SomeClass : IDisposable", pos: i, isSignificant: true, start: 13, length: 9); } } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void EscapedIdentifier() { for (var i = 12; i <= 12 + 9; i++) { AssertExtent( "public enum @interface : int", pos: i, isSignificant: true, start: 12, length: 10); } } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void Number() { for (var i = 37; i <= 37 + 10; i++) { AssertExtent( "class Test { private double num = -1.234678e10; }", pos: i, isSignificant: true, start: 37, length: 11); } } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void String() { const string TestString = "class Test { private string s1 = \" () test \"; }"; var startOfString = TestString.IndexOf('"'); var lengthOfStringIncludingQuotes = TestString.LastIndexOf('"') - startOfString + 1; AssertExtent( TestString, pos: startOfString, isSignificant: true, start: startOfString, length: 1); // Selects whitespace AssertExtent( TestString, pos: startOfString + 1, isSignificant: false, start: startOfString + 1, length: 1); AssertExtent( TestString, pos: startOfString + 2, isSignificant: true, start: startOfString + 2, length: 2); AssertExtent( TestString, pos: TestString.IndexOf(" \"", StringComparison.Ordinal), isSignificant: false, start: TestString.IndexOf(" \"", StringComparison.Ordinal), length: 2); AssertExtent( TestString, pos: TestString.LastIndexOf('"'), isSignificant: true, start: startOfString + lengthOfStringIncludingQuotes - 1, length: 1); AssertExtent( TestString, pos: TestString.LastIndexOf('"') + 1, isSignificant: true, start: TestString.LastIndexOf('"') + 1, length: 1); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void InterpolatedString1() { const string TestString = "class Test { string x = \"hello\"; string s = $\" { x } hello\"; }"; var startOfFirstString = TestString.IndexOf('"'); var endOfFirstString = TestString.IndexOf('"', startOfFirstString + 1); var startOfString = TestString.IndexOf("$\"", endOfFirstString + 1, StringComparison.Ordinal); // Selects interpolated string start token AssertExtent( TestString, pos: startOfString, isSignificant: true, start: startOfString, length: 2); // Selects whitespace AssertExtent( TestString, pos: startOfString + 2, isSignificant: false, start: startOfString + 2, length: 1); // Selects the opening curly brace AssertExtent( TestString, pos: startOfString + 3, isSignificant: true, start: startOfString + 3, length: 1); // Selects whitespace AssertExtent( TestString, pos: startOfString + 4, isSignificant: false, start: startOfString + 4, length: 1); // Selects identifier AssertExtent( TestString, pos: startOfString + 5, isSignificant: true, start: startOfString + 5, length: 1); // Selects whitespace AssertExtent( TestString, pos: startOfString + 6, isSignificant: false, start: startOfString + 6, length: 1); // Selects the closing curly brace AssertExtent( TestString, pos: startOfString + 7, isSignificant: true, start: startOfString + 7, length: 1); // Selects whitespace AssertExtent( TestString, pos: startOfString + 8, isSignificant: false, start: startOfString + 8, length: 1); // Selects hello AssertExtent( TestString, pos: startOfString + 9, isSignificant: true, start: startOfString + 9, length: 5); // Selects closing quote AssertExtent( TestString, pos: startOfString + 14, isSignificant: true, start: startOfString + 14, length: 1); } private static void AssertExtent(string code, int pos, bool isSignificant, int start, int length) { AssertExtent(code, pos, isSignificant, start, length, null); AssertExtent(code, pos, isSignificant, start, length, Options.Script); } private static void AssertExtent(string code, int pos, bool isSignificant, int start, int length, CSharpParseOptions options) { using var workspace = TestWorkspace.CreateCSharp(code, options); var buffer = workspace.Documents.First().GetTextBuffer(); var provider = Assert.IsType<TextStructureNavigatorProvider>( workspace.GetService<ITextStructureNavigatorProvider>(ContentTypeNames.CSharpContentType)); var navigator = provider.CreateTextStructureNavigator(buffer); var extent = navigator.GetExtentOfWord(new SnapshotPoint(buffer.CurrentSnapshot, pos)); Assert.Equal(isSignificant, extent.IsSignificant); var expectedSpan = new SnapshotSpan(buffer.CurrentSnapshot, start, length); Assert.Equal(expectedSpan, extent.Span); } private static void TestNavigator( string code, Func<ITextStructureNavigator, SnapshotSpan, SnapshotSpan> func, int startPosition, int startLength, int endPosition, int endLength) { TestNavigator(code, func, startPosition, startLength, endPosition, endLength, null); TestNavigator(code, func, startPosition, startLength, endPosition, endLength, Options.Script); } private static void TestNavigator( string code, Func<ITextStructureNavigator, SnapshotSpan, SnapshotSpan> func, int startPosition, int startLength, int endPosition, int endLength, CSharpParseOptions options) { using var workspace = TestWorkspace.CreateCSharp(code, options); var buffer = workspace.Documents.First().GetTextBuffer(); var provider = Assert.IsType<TextStructureNavigatorProvider>( workspace.GetService<ITextStructureNavigatorProvider>(ContentTypeNames.CSharpContentType)); var navigator = provider.CreateTextStructureNavigator(buffer); var actualSpan = func(navigator, new SnapshotSpan(buffer.CurrentSnapshot, startPosition, startLength)); var expectedSpan = new SnapshotSpan(buffer.CurrentSnapshot, endPosition, endLength); Assert.Equal(expectedSpan, actualSpan.Span); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void GetSpanOfEnclosingTest() { // First operation returns span of 'Class1' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 10, 0, 6, 6); // Second operation returns span of 'class Class1 { }' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 6, 6, 0, 16); // Last operation does nothing TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfEnclosing(s), 0, 16, 0, 16); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void GetSpanOfFirstChildTest() { // Go from 'class Class1 { }' to 'class' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfFirstChild(s), 0, 16, 0, 5); // Next operation should do nothing as we're at the bottom TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfFirstChild(s), 0, 5, 0, 5); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void GetSpanOfNextSiblingTest() { // Go from 'class' to 'Class1' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfNextSibling(s), 0, 5, 6, 6); } [WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)] public void GetSpanOfPreviousSiblingTest() { // Go from '{' to 'Class1' TestNavigator( @"class Class1 { }", (n, s) => n.GetSpanOfPreviousSibling(s), 13, 1, 6, 6); } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/CSharp/Portable/Compilation/SyntaxTreeSemanticModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Allows asking semantic questions about any node in a SyntaxTree within a Compilation. /// </summary> internal partial class SyntaxTreeSemanticModel : CSharpSemanticModel { private readonly CSharpCompilation _compilation; private readonly SyntaxTree _syntaxTree; /// <summary> /// Note, the name of this field could be somewhat confusing because it is also /// used to store models for attributes and default parameter values, which are /// not members. /// </summary> private ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel> _memberModels = ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel>.Empty; private readonly BinderFactory _binderFactory; private Func<CSharpSyntaxNode, MemberSemanticModel> _createMemberModelFunction; private readonly bool _ignoresAccessibility; private ScriptLocalScopeBinder.Labels _globalStatementLabels; private static readonly Func<CSharpSyntaxNode, bool> s_isMemberDeclarationFunction = IsMemberDeclaration; #nullable enable internal SyntaxTreeSemanticModel(CSharpCompilation compilation, SyntaxTree syntaxTree, bool ignoreAccessibility = false) { _compilation = compilation; _syntaxTree = syntaxTree; _ignoresAccessibility = ignoreAccessibility; if (!this.Compilation.SyntaxTrees.Contains(syntaxTree)) { throw new ArgumentOutOfRangeException(nameof(syntaxTree), CSharpResources.TreeNotPartOfCompilation); } _binderFactory = compilation.GetBinderFactory(SyntaxTree, ignoreAccessibility); } internal SyntaxTreeSemanticModel(CSharpCompilation parentCompilation, SyntaxTree parentSyntaxTree, SyntaxTree speculatedSyntaxTree) { _compilation = parentCompilation; _syntaxTree = speculatedSyntaxTree; _binderFactory = _compilation.GetBinderFactory(parentSyntaxTree); } /// <summary> /// The compilation this object was obtained from. /// </summary> public override CSharpCompilation Compilation { get { return _compilation; } } /// <summary> /// The root node of the syntax tree that this object is associated with. /// </summary> internal override CSharpSyntaxNode Root { get { return (CSharpSyntaxNode)_syntaxTree.GetRoot(); } } /// <summary> /// The SyntaxTree that this object is associated with. /// </summary> public override SyntaxTree SyntaxTree { get { return _syntaxTree; } } /// <summary> /// Returns true if this is a SemanticModel that ignores accessibility rules when answering semantic questions. /// </summary> public override bool IgnoresAccessibility { get { return _ignoresAccessibility; } } private void VerifySpanForGetDiagnostics(TextSpan? span) { if (span.HasValue && !this.Root.FullSpan.Contains(span.Value)) { throw new ArgumentException("span"); } } public override ImmutableArray<Diagnostic> GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Parse, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Declare, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Compile, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Compile, this.SyntaxTree, span, includeEarlierStages: true, cancellationToken: cancellationToken); } #nullable disable /// <summary> /// Gets the enclosing binder associated with the node /// </summary> /// <param name="position"></param> /// <returns></returns> internal override Binder GetEnclosingBinderInternal(int position) { AssertPositionAdjusted(position); SyntaxToken token = this.Root.FindTokenIncludingCrefAndNameAttributes(position); // If we're before the start of the first token, just return // the binder for the compilation unit. if (position == 0 && position != token.SpanStart) { return _binderFactory.GetBinder(this.Root, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); } MemberSemanticModel memberModel = GetMemberModel(position); if (memberModel != null) { return memberModel.GetEnclosingBinder(position); } return _binderFactory.GetBinder((CSharpSyntaxNode)token.Parent, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); } internal override IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { MemberSemanticModel model; switch (node) { case ConstructorDeclarationSyntax constructor: model = (constructor.HasAnyBody() || constructor.Initializer != null) ? GetOrAddModel(node) : null; break; case BaseMethodDeclarationSyntax method: model = method.HasAnyBody() ? GetOrAddModel(node) : null; break; case AccessorDeclarationSyntax accessor: model = (accessor.Body != null || accessor.ExpressionBody != null) ? GetOrAddModel(node) : null; break; case RecordDeclarationSyntax { ParameterList: { }, PrimaryConstructorBaseTypeIfClass: { } } recordDeclaration when TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor: model = GetOrAddModel(recordDeclaration); break; default: model = this.GetMemberModel(node); break; } if (model != null) { return model.GetOperationWorker(node, cancellationToken); } else { return null; } } internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { ValidateSymbolInfoOptions(options); // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); SymbolInfo result; XmlNameAttributeSyntax attrSyntax; CrefSyntax crefSyntax; if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. result = model.GetSymbolInfoWorker(node, options, cancellationToken); // If we didn't get anything and were in Type/Namespace only context, let's bind normally and see // if any symbol comes out. if ((object)result.Symbol == null && result.CandidateReason == CandidateReason.None && node is ExpressionSyntax && SyntaxFacts.IsInNamespaceOrTypeContext((ExpressionSyntax)node)) { var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // Wrap the binder in a LocalScopeBinder because Binder.BindExpression assumes there // will be one in the binder chain and one isn't necessarily required for the batch case. binder = new LocalScopeBinder(binder); BoundExpression bound = binder.BindExpression((ExpressionSyntax)node, BindingDiagnosticBag.Discarded); SymbolInfo info = GetSymbolInfoForNode(options, bound, bound, boundNodeForSyntacticParent: null, binderOpt: null); if ((object)info.Symbol != null) { result = new SymbolInfo(null, ImmutableArray.Create<ISymbol>(info.Symbol), CandidateReason.NotATypeOrNamespace); } else if (!info.CandidateSymbols.IsEmpty) { result = new SymbolInfo(null, info.CandidateSymbols, CandidateReason.NotATypeOrNamespace); } } } } else if (node.Parent.Kind() == SyntaxKind.XmlNameAttribute && (attrSyntax = (XmlNameAttributeSyntax)node.Parent).Identifier == node) { result = SymbolInfo.None; var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var symbols = binder.BindXmlNameAttribute(attrSyntax, ref discardedUseSiteInfo); // NOTE: We don't need to call GetSymbolInfoForSymbol because the symbols // can only be parameters or type parameters. Debug.Assert(symbols.All(s => s.Kind == SymbolKind.TypeParameter || s.Kind == SymbolKind.Parameter)); switch (symbols.Length) { case 0: result = SymbolInfo.None; break; case 1: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Viable, isDynamic: false); break; default: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Ambiguous, isDynamic: false); break; } } } else if ((crefSyntax = node as CrefSyntax) != null) { int adjustedPosition = GetAdjustedNodePosition(crefSyntax); result = GetCrefSymbolInfo(adjustedPosition, crefSyntax, options, HasParameterList(crefSyntax)); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: (options & SymbolInfoOptions.PreserveAliases) != 0); result = (object)symbol != null ? GetSymbolInfoForSymbol(symbol, options) : SymbolInfo.None; } return result; } internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { var model = this.GetMemberModel(collectionInitializer); if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. return model.GetCollectionInitializerSymbolInfoWorker(collectionInitializer, node, cancellationToken); } return SymbolInfo.None; } internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. return model.GetTypeInfoWorker(node, cancellationToken); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: false); // Don't care about aliases here. return (object)symbol != null ? GetTypeInfoForSymbol(symbol) : CSharpTypeInfo.None; } } // Common helper method for GetSymbolInfoWorker and GetTypeInfoWorker, which is called when there is no member model for the given syntax node. // Even if the expression is not part of a member context, the caller may really just have a reference to a type or namespace name. // If so, the methods binds the syntax as a namespace or type or alias symbol. Otherwise, it returns null. private Symbol GetSemanticInfoSymbolInNonMemberContext(CSharpSyntaxNode node, bool bindVarAsAliasFirst) { Debug.Assert(this.GetMemberModel(node) == null); var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var type = node as TypeSyntax; if ((object)type != null) { // determine if this type is part of a base declaration being resolved var basesBeingResolved = GetBasesBeingResolved(type); if (SyntaxFacts.IsNamespaceAliasQualifier(type)) { return binder.BindNamespaceAliasSymbol(node as IdentifierNameSyntax, BindingDiagnosticBag.Discarded); } else if (SyntaxFacts.IsInTypeOnlyContext(type)) { if (!type.IsVar) { return binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; } Symbol result = bindVarAsAliasFirst ? binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol : null; // CONSIDER: we might bind "var" twice - once to see if it is an alias and again // as the type of a declared field. This should only happen for GetAliasInfo // calls on implicitly-typed fields (rare?). If it becomes a problem, then we // probably need to have the FieldSymbol retain alias info when it does its own // binding and expose it to us here. if ((object)result == null || result.Kind == SymbolKind.ErrorType) { // We might be in a field declaration with "var" keyword as the type name. // Implicitly typed field symbols are not allowed in regular C#, // but they are allowed in interactive scenario. // However, we can return fieldSymbol.Type for implicitly typed field symbols in both cases. // Note that for regular C#, fieldSymbol.Type would be an error type. var variableDecl = type.Parent as VariableDeclarationSyntax; if (variableDecl != null && variableDecl.Variables.Any()) { var fieldSymbol = GetDeclaredFieldSymbol(variableDecl.Variables.First()); if ((object)fieldSymbol != null) { result = fieldSymbol.Type; } } } return result ?? binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; } else { return binder.BindNamespaceOrTypeOrAliasSymbol(type, BindingDiagnosticBag.Discarded, basesBeingResolved, basesBeingResolved != null).Symbol; } } } return null; } internal override ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? ImmutableArray<Symbol>.Empty : model.GetMemberGroupWorker(node, options, cancellationToken); } internal override ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? ImmutableArray<IPropertySymbol>.Empty : model.GetIndexerGroupWorker(node, options, cancellationToken); } internal override Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { // in case this is right side of a qualified name or member access node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? default(Optional<object>) : model.GetConstantValueWorker(node, cancellationToken); } public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? default(QueryClauseInfo) : model.GetQueryClauseInfo(node, cancellationToken); } public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? SymbolInfo.None : model.GetSymbolInfo(node, cancellationToken); } public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? CSharpTypeInfo.None : model.GetTypeInfo(node, cancellationToken); } public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? SymbolInfo.None : model.GetSymbolInfo(node, cancellationToken); } private ConsList<TypeSymbol> GetBasesBeingResolved(TypeSyntax expression) { // if the expression is the child of a base-list node, then the expression should be // bound in the context of the containing symbols base being resolved. for (; expression != null && expression.Parent != null; expression = expression.Parent as TypeSyntax) { var parent = expression.Parent; if (parent is BaseTypeSyntax baseType && parent.Parent != null && parent.Parent.Kind() == SyntaxKind.BaseList && baseType.Type == expression) { // we have a winner var decl = (BaseTypeDeclarationSyntax)parent.Parent.Parent; var symbol = this.GetDeclaredSymbol(decl); return ConsList<TypeSymbol>.Empty.Prepend(symbol.GetSymbol().OriginalDefinition); } } return null; } public override Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) { TypeSymbol csdestination = destination.EnsureCSharpSymbolOrNull(nameof(destination)); if (expression.Kind() == SyntaxKind.DeclarationExpression) { // Conversion from a declaration is unspecified. return Conversion.NoConversion; } if (isExplicitInSource) { return ClassifyConversionForCast(expression, csdestination); } CheckSyntaxNode(expression); if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } // TODO(cyrusn): Check arguments. This is a public entrypoint, so we must do appropriate // checks here. However, no other methods in this type do any checking currently. So I'm // going to hold off on this until we do a full sweep of the API. var model = this.GetMemberModel(expression); if (model == null) { // 'expression' must just be reference to a type or namespace name outside of an // expression context. Currently we bail in that case. However, is this a question // that a client would be asking and would expect sensible results for? return Conversion.NoConversion; } return model.ClassifyConversion(expression, destination); } internal override Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination) { CheckSyntaxNode(expression); if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } var model = this.GetMemberModel(expression); if (model == null) { // 'expression' must just be reference to a type or namespace name outside of an // expression context. Currently we bail in that case. However, is this a question // that a client would be asking and would expect sensible results for? return Conversion.NoConversion; } return model.ClassifyConversionForCast(expression, destination); } public override bool IsSpeculativeSemanticModel { get { return false; } } public override int OriginalPositionForSpeculation { get { return 0; } } public override CSharpSemanticModel ParentModel { get { return null; } } internal override SemanticModel ContainingModelOrSelf { get { return this; } } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, type, bindingOption, out speculativeModel); } Binder binder = GetSpeculativeBinder(position, type, bindingOption); if (binder != null) { speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, type, binder, position, bindingOption); return true; } speculativeModel = null; return false; } internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); Binder binder = GetEnclosingBinder(position); if (binder?.InCref == true) { speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, crefSyntax, binder, position); return true; } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, statement, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, method, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, accessor, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, initializer, out speculativeModel); } speculativeModel = null; return false; } internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, expressionBody, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<ConstructorInitializerSyntax>().FirstOrDefault(); if (existingConstructorInitializer != null) { var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); } } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<PrimaryConstructorBaseTypeSyntax>().FirstOrDefault(); if (existingConstructorInitializer != null) { var model = this.GetMemberModel(existingConstructorInitializer); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); } } speculativeModel = null; return false; } internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } // If the given position is in a member that we can get a semantic model for, we want to defer to that implementation // of GetSpeculativelyBoundExpression so it can take nullability into account. if (bindingOption == SpeculativeBindingOption.BindAsExpression) { position = CheckAndAdjustPosition(position); var model = GetMemberModel(position); if (model is object) { return model.GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); } } return GetSpeculativelyBoundExpressionWithoutNullability(position, expression, bindingOption, out binder, out crefSymbols); } internal AttributeSemanticModel CreateSpeculativeAttributeSemanticModel(int position, AttributeSyntax attribute, Binder binder, AliasSymbol aliasOpt, NamedTypeSymbol attributeType) { var memberModel = IsNullableAnalysisEnabledAtSpeculativePosition(position, attribute) ? GetMemberModel(position) : null; return AttributeSemanticModel.CreateSpeculative(this, attribute, attributeType, aliasOpt, binder, memberModel?.GetRemappedSymbols(), position); } internal bool IsNullableAnalysisEnabledAtSpeculativePosition(int position, SyntaxNode speculativeSyntax) { Debug.Assert(speculativeSyntax.SyntaxTree != SyntaxTree); // https://github.com/dotnet/roslyn/issues/50234: CSharpSyntaxTree.IsNullableAnalysisEnabled() does not differentiate // between no '#nullable' directives and '#nullable restore' - it returns null in both cases. Since we fallback to the // directives in the original syntax tree, we're not handling '#nullable restore' correctly in the speculative text. return ((CSharpSyntaxTree)speculativeSyntax.SyntaxTree).IsNullableAnalysisEnabled(speculativeSyntax.Span) ?? Compilation.IsNullableAnalysisEnabledIn((CSharpSyntaxTree)SyntaxTree, new TextSpan(position, 0)); } private MemberSemanticModel GetMemberModel(int position) { AssertPositionAdjusted(position); CSharpSyntaxNode node = (CSharpSyntaxNode)Root.FindTokenIncludingCrefAndNameAttributes(position).Parent; CSharpSyntaxNode memberDecl = GetMemberDeclaration(node); bool outsideMemberDecl = false; if (memberDecl != null) { switch (memberDecl.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: // NOTE: not UnknownAccessorDeclaration since there's no corresponding method symbol from which to build a member model. outsideMemberDecl = !LookupPosition.IsInBody(position, (AccessorDeclarationSyntax)memberDecl); break; case SyntaxKind.ConstructorDeclaration: var constructorDecl = (ConstructorDeclarationSyntax)memberDecl; outsideMemberDecl = !LookupPosition.IsInConstructorParameterScope(position, constructorDecl) && !LookupPosition.IsInParameterList(position, constructorDecl); break; case SyntaxKind.RecordDeclaration: { var recordDecl = (RecordDeclarationSyntax)memberDecl; if (recordDecl.ParameterList is null) { outsideMemberDecl = true; } else { var argumentList = recordDecl.PrimaryConstructorBaseTypeIfClass?.ArgumentList; outsideMemberDecl = argumentList is null || !LookupPosition.IsBetweenTokens(position, argumentList.OpenParenToken, argumentList.CloseParenToken); } } break; case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: var methodDecl = (BaseMethodDeclarationSyntax)memberDecl; outsideMemberDecl = !LookupPosition.IsInBody(position, methodDecl) && !LookupPosition.IsInParameterList(position, methodDecl); break; } } return outsideMemberDecl ? null : GetMemberModel(node); } // Try to get a member semantic model that encloses "node". If there is not an enclosing // member semantic model, return null. internal override MemberSemanticModel GetMemberModel(SyntaxNode node) { // Documentation comments can never legally appear within members, so there's no point // in building out the MemberSemanticModel to handle them. Instead, just say have // SyntaxTreeSemanticModel handle them, regardless of location. if (IsInDocumentationComment(node)) { return null; } var memberDecl = GetMemberDeclaration(node) ?? (node as CompilationUnitSyntax); if (memberDecl != null) { var span = node.Span; switch (memberDecl.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: { var methodDecl = (BaseMethodDeclarationSyntax)memberDecl; var expressionBody = methodDecl.GetExpressionBodySyntax(); return (expressionBody?.FullSpan.Contains(span) == true || methodDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(methodDecl) : null; } case SyntaxKind.ConstructorDeclaration: { ConstructorDeclarationSyntax constructorDecl = (ConstructorDeclarationSyntax)memberDecl; var expressionBody = constructorDecl.GetExpressionBodySyntax(); return (constructorDecl.Initializer?.FullSpan.Contains(span) == true || expressionBody?.FullSpan.Contains(span) == true || constructorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(constructorDecl) : null; } case SyntaxKind.RecordDeclaration: { var recordDecl = (RecordDeclarationSyntax)memberDecl; return recordDecl.ParameterList is object && recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments && (node == baseWithArguments || baseWithArguments.ArgumentList.FullSpan.Contains(span)) ? GetOrAddModel(memberDecl) : null; } case SyntaxKind.DestructorDeclaration: { DestructorDeclarationSyntax destructorDecl = (DestructorDeclarationSyntax)memberDecl; var expressionBody = destructorDecl.GetExpressionBodySyntax(); return (expressionBody?.FullSpan.Contains(span) == true || destructorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(destructorDecl) : null; } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: // NOTE: not UnknownAccessorDeclaration since there's no corresponding method symbol from which to build a member model. { var accessorDecl = (AccessorDeclarationSyntax)memberDecl; return (accessorDecl.ExpressionBody?.FullSpan.Contains(span) == true || accessorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(accessorDecl) : null; } case SyntaxKind.IndexerDeclaration: { var indexerDecl = (IndexerDeclarationSyntax)memberDecl; return GetOrAddModelIfContains(indexerDecl.ExpressionBody, span); } case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: { var fieldDecl = (BaseFieldDeclarationSyntax)memberDecl; foreach (var variableDecl in fieldDecl.Declaration.Variables) { var binding = GetOrAddModelIfContains(variableDecl.Initializer, span); if (binding != null) { return binding; } } } break; case SyntaxKind.EnumMemberDeclaration: { var enumDecl = (EnumMemberDeclarationSyntax)memberDecl; return (enumDecl.EqualsValue != null) ? GetOrAddModelIfContains(enumDecl.EqualsValue, span) : null; } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)memberDecl; return GetOrAddModelIfContains(propertyDecl.Initializer, span) ?? GetOrAddModelIfContains(propertyDecl.ExpressionBody, span); } case SyntaxKind.GlobalStatement: if (SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)memberDecl)) { return GetOrAddModel((CompilationUnitSyntax)memberDecl.Parent); } return GetOrAddModel(memberDecl); case SyntaxKind.CompilationUnit: if (SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)memberDecl, fallbackToMainEntryPoint: false) is object) { return GetOrAddModel(memberDecl); } break; case SyntaxKind.Attribute: return GetOrAddModelForAttribute((AttributeSyntax)memberDecl); case SyntaxKind.Parameter: if (node != memberDecl) { return GetOrAddModelForParameter((ParameterSyntax)memberDecl, span); } else { return GetMemberModel(memberDecl.Parent); } } } return null; } /// <summary> /// Internal for test purposes only /// </summary> internal ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel> TestOnlyMemberModels => _memberModels; private MemberSemanticModel GetOrAddModelForAttribute(AttributeSyntax attribute) { MemberSemanticModel containing = attribute.Parent != null ? GetMemberModel(attribute.Parent) : null; if (containing == null) { return GetOrAddModel(attribute); } return ImmutableInterlocked.GetOrAdd(ref _memberModels, attribute, (node, binderAndModel) => CreateModelForAttribute(binderAndModel.binder, (AttributeSyntax)node, binderAndModel.model), (binder: containing.GetEnclosingBinder(attribute.SpanStart), model: containing)); } private static bool IsInDocumentationComment(SyntaxNode node) { for (SyntaxNode curr = node; curr != null; curr = curr.Parent) { if (SyntaxFacts.IsDocumentationCommentTrivia(curr.Kind())) { return true; } } return false; } // Check parameter for a default value containing span, and create an InitializerSemanticModel for binding the default value if so. // Otherwise, return model for enclosing context. private MemberSemanticModel GetOrAddModelForParameter(ParameterSyntax paramDecl, TextSpan span) { EqualsValueClauseSyntax defaultValueSyntax = paramDecl.Default; MemberSemanticModel containing = paramDecl.Parent != null ? GetMemberModel(paramDecl.Parent) : null; if (containing == null) { return GetOrAddModelIfContains(defaultValueSyntax, span); } if (defaultValueSyntax != null && defaultValueSyntax.FullSpan.Contains(span)) { var parameterSymbol = containing.GetDeclaredSymbol(paramDecl).GetSymbol<ParameterSymbol>(); if ((object)parameterSymbol != null) { return ImmutableInterlocked.GetOrAdd(ref _memberModels, defaultValueSyntax, (equalsValue, tuple) => InitializerSemanticModel.Create( this, tuple.paramDecl, tuple.parameterSymbol, tuple.containing.GetEnclosingBinder(tuple.paramDecl.SpanStart). CreateBinderForParameterDefaultValue(tuple.parameterSymbol, (EqualsValueClauseSyntax)equalsValue), tuple.containing.GetRemappedSymbols()), (compilation: this.Compilation, paramDecl, parameterSymbol, containing) ); } } return containing; } private static CSharpSyntaxNode GetMemberDeclaration(SyntaxNode node) { return node.FirstAncestorOrSelf(s_isMemberDeclarationFunction); } private MemberSemanticModel GetOrAddModelIfContains(CSharpSyntaxNode node, TextSpan span) { if (node != null && node.FullSpan.Contains(span)) { return GetOrAddModel(node); } return null; } private MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node) { var createMemberModelFunction = _createMemberModelFunction ?? (_createMemberModelFunction = this.CreateMemberModel); return GetOrAddModel(node, createMemberModelFunction); } internal MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node, Func<CSharpSyntaxNode, MemberSemanticModel> createMemberModelFunction) { return ImmutableInterlocked.GetOrAdd(ref _memberModels, node, createMemberModelFunction); } // Create a member model for the given declaration syntax. In certain very malformed // syntax trees, there may not be a symbol that can have a member model associated with it // (although we try to minimize such cases). In such cases, null is returned. private MemberSemanticModel CreateMemberModel(CSharpSyntaxNode node) { Binder defaultOuter() => _binderFactory.GetBinder(node).WithAdditionalFlags(this.IgnoresAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None); switch (node.Kind()) { case SyntaxKind.CompilationUnit: return createMethodBodySemanticModel(node, SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)node, fallbackToMainEntryPoint: false)); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: { var memberDecl = (MemberDeclarationSyntax)node; var symbol = GetDeclaredSymbol(memberDecl).GetSymbol<SourceMemberMethodSymbol>(); return createMethodBodySemanticModel(memberDecl, symbol); } case SyntaxKind.RecordDeclaration: { SynthesizedRecordConstructor symbol = TryGetSynthesizedRecordConstructor((RecordDeclarationSyntax)node); if (symbol is null) { return null; } return createMethodBodySemanticModel(node, symbol); } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: { var accessorDecl = (AccessorDeclarationSyntax)node; var symbol = GetDeclaredSymbol(accessorDecl).GetSymbol<SourceMemberMethodSymbol>(); return createMethodBodySemanticModel(accessorDecl, symbol); } case SyntaxKind.Block: // Don't throw, just use for the assert ExceptionUtilities.UnexpectedValue(node.Parent); break; case SyntaxKind.EqualsValueClause: switch (node.Parent.Kind()) { case SyntaxKind.VariableDeclarator: { var variableDecl = (VariableDeclaratorSyntax)node.Parent; FieldSymbol fieldSymbol = GetDeclaredFieldSymbol(variableDecl); return InitializerSemanticModel.Create( this, variableDecl, //pass in the entire field initializer to permit region analysis. fieldSymbol, //if we're in regular C#, then insert an extra binder to perform field initialization checks GetFieldOrPropertyInitializerBinder(fieldSymbol, defaultOuter(), variableDecl.Initializer)); } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)node.Parent; var propertySymbol = GetDeclaredSymbol(propertyDecl).GetSymbol<SourcePropertySymbol>(); return InitializerSemanticModel.Create( this, propertyDecl, propertySymbol, GetFieldOrPropertyInitializerBinder(propertySymbol.BackingField, defaultOuter(), propertyDecl.Initializer)); } case SyntaxKind.Parameter: { // NOTE: we don't need to create a member model for lambda parameter default value // (which is bad code anyway) because lambdas only appear in code with associated // member models. ParameterSyntax parameterDecl = (ParameterSyntax)node.Parent; ParameterSymbol parameterSymbol = GetDeclaredNonLambdaParameterSymbol(parameterDecl); if ((object)parameterSymbol == null) return null; return InitializerSemanticModel.Create( this, parameterDecl, parameterSymbol, defaultOuter().CreateBinderForParameterDefaultValue(parameterSymbol, (EqualsValueClauseSyntax)node), parentRemappedSymbolsOpt: null); } case SyntaxKind.EnumMemberDeclaration: { var enumDecl = (EnumMemberDeclarationSyntax)node.Parent; var enumSymbol = GetDeclaredSymbol(enumDecl).GetSymbol<FieldSymbol>(); if ((object)enumSymbol == null) return null; return InitializerSemanticModel.Create( this, enumDecl, enumSymbol, GetFieldOrPropertyInitializerBinder(enumSymbol, defaultOuter(), enumDecl.EqualsValue)); } default: throw ExceptionUtilities.UnexpectedValue(node.Parent.Kind()); } case SyntaxKind.ArrowExpressionClause: { SourceMemberMethodSymbol symbol = null; var exprDecl = (ArrowExpressionClauseSyntax)node; if (node.Parent is BasePropertyDeclarationSyntax) { symbol = GetDeclaredSymbol(exprDecl).GetSymbol<SourceMemberMethodSymbol>(); } else { // Don't throw, just use for the assert ExceptionUtilities.UnexpectedValue(node.Parent); } ExecutableCodeBinder binder = symbol?.TryGetBodyBinder(_binderFactory, this.IgnoresAccessibility); if (binder == null) { return null; } return MethodBodySemanticModel.Create(this, symbol, new MethodBodySemanticModel.InitialState(exprDecl, binder: binder)); } case SyntaxKind.GlobalStatement: { var parent = node.Parent; // TODO (tomat): handle misplaced global statements if (parent.Kind() == SyntaxKind.CompilationUnit && !this.IsRegularCSharp && (object)_compilation.ScriptClass != null) { var scriptInitializer = _compilation.ScriptClass.GetScriptInitializer(); Debug.Assert((object)scriptInitializer != null); if ((object)scriptInitializer == null) { return null; } // Share labels across all global statements. if (_globalStatementLabels == null) { Interlocked.CompareExchange(ref _globalStatementLabels, new ScriptLocalScopeBinder.Labels(scriptInitializer, (CompilationUnitSyntax)parent), null); } return MethodBodySemanticModel.Create( this, scriptInitializer, new MethodBodySemanticModel.InitialState(node, binder: new ExecutableCodeBinder(node, scriptInitializer, new ScriptLocalScopeBinder(_globalStatementLabels, defaultOuter())))); } } break; case SyntaxKind.Attribute: return CreateModelForAttribute(defaultOuter(), (AttributeSyntax)node, containingModel: null); } return null; MemberSemanticModel createMethodBodySemanticModel(CSharpSyntaxNode memberDecl, SourceMemberMethodSymbol symbol) { ExecutableCodeBinder binder = symbol?.TryGetBodyBinder(_binderFactory, this.IgnoresAccessibility); if (binder == null) { return null; } return MethodBodySemanticModel.Create(this, symbol, new MethodBodySemanticModel.InitialState(memberDecl, binder: binder)); } } private SynthesizedRecordConstructor TryGetSynthesizedRecordConstructor(RecordDeclarationSyntax node) { NamedTypeSymbol recordType = GetDeclaredType(node); var symbol = recordType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().SingleOrDefault(); if (symbol?.SyntaxRef.SyntaxTree != node.SyntaxTree || symbol.GetSyntax() != node) { return null; } return symbol; } private AttributeSemanticModel CreateModelForAttribute(Binder enclosingBinder, AttributeSyntax attribute, MemberSemanticModel containingModel) { AliasSymbol aliasOpt; var attributeType = (NamedTypeSymbol)enclosingBinder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type; return AttributeSemanticModel.Create( this, attribute, attributeType, aliasOpt, enclosingBinder.WithAdditionalFlags(BinderFlags.AttributeArgument), containingModel?.GetRemappedSymbols()); } private FieldSymbol GetDeclaredFieldSymbol(VariableDeclaratorSyntax variableDecl) { var declaredSymbol = GetDeclaredSymbol(variableDecl); if ((object)declaredSymbol != null) { switch (variableDecl.Parent.Parent.Kind()) { case SyntaxKind.FieldDeclaration: return declaredSymbol.GetSymbol<FieldSymbol>(); case SyntaxKind.EventFieldDeclaration: return (declaredSymbol.GetSymbol<EventSymbol>()).AssociatedField; } } return null; } private Binder GetFieldOrPropertyInitializerBinder(FieldSymbol symbol, Binder outer, EqualsValueClauseSyntax initializer) { // NOTE: checking for a containing script class is sufficient, but the regular C# test is quick and easy. outer = outer.GetFieldInitializerBinder(symbol, suppressBinderFlagsFieldInitializer: !this.IsRegularCSharp && symbol.ContainingType.IsScriptClass); if (initializer != null) { outer = new ExecutableCodeBinder(initializer, symbol, outer); } return outer; } private static bool IsMemberDeclaration(CSharpSyntaxNode node) { return (node is MemberDeclarationSyntax) || (node is AccessorDeclarationSyntax) || (node.Kind() == SyntaxKind.Attribute) || (node.Kind() == SyntaxKind.Parameter); } private bool IsRegularCSharp { get { return this.SyntaxTree.Options.Kind == SourceCodeKind.Regular; } } #region "GetDeclaredSymbol overloads for MemberDeclarationSyntax and its subtypes" /// <inheritdoc/> public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); } /// <inheritdoc/> public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default) { CheckSyntaxNode(declarationSyntax); return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); } private NamespaceSymbol GetDeclaredNamespace(BaseNamespaceDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); NamespaceOrTypeSymbol container; if (declarationSyntax.Parent.Kind() == SyntaxKind.CompilationUnit) { container = _compilation.Assembly.GlobalNamespace; } else { container = GetDeclaredNamespaceOrType(declarationSyntax.Parent); } Debug.Assert((object)container != null); // We should get a namespace symbol since we match the symbol location with a namespace declaration syntax location. var symbol = (NamespaceSymbol)GetDeclaredMember(container, declarationSyntax.Span, declarationSyntax.Name); Debug.Assert((object)symbol != null); // Map to compilation-scoped namespace (Roslyn bug 9538) symbol = _compilation.GetCompilationNamespace(symbol); Debug.Assert((object)symbol != null); return symbol; } /// <summary> /// Given a type declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a type.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseTypeDeclarationSyntax as all of them return a NamedTypeSymbol. /// </remarks> public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredType(declarationSyntax).GetPublicSymbol(); } /// <summary> /// Given a delegate declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a delegate.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredType(declarationSyntax).GetPublicSymbol(); } private NamedTypeSymbol GetDeclaredType(BaseTypeDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); var name = declarationSyntax.Identifier.ValueText; return GetDeclaredNamedType(declarationSyntax, name); } private NamedTypeSymbol GetDeclaredType(DelegateDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); var name = declarationSyntax.Identifier.ValueText; return GetDeclaredNamedType(declarationSyntax, name); } private NamedTypeSymbol GetDeclaredNamedType(CSharpSyntaxNode declarationSyntax, string name) { Debug.Assert(declarationSyntax != null); var container = GetDeclaredTypeMemberContainer(declarationSyntax); Debug.Assert((object)container != null); // try cast as we might get a non-type in error recovery scenarios: return GetDeclaredMember(container, declarationSyntax.Span, name) as NamedTypeSymbol; } private NamespaceOrTypeSymbol GetDeclaredNamespaceOrType(CSharpSyntaxNode declarationSyntax) { var namespaceDeclarationSyntax = declarationSyntax as BaseNamespaceDeclarationSyntax; if (namespaceDeclarationSyntax != null) { return GetDeclaredNamespace(namespaceDeclarationSyntax); } var typeDeclarationSyntax = declarationSyntax as BaseTypeDeclarationSyntax; if (typeDeclarationSyntax != null) { return GetDeclaredType(typeDeclarationSyntax); } var delegateDeclarationSyntax = declarationSyntax as DelegateDeclarationSyntax; if (delegateDeclarationSyntax != null) { return GetDeclaredType(delegateDeclarationSyntax); } return null; } /// <summary> /// Given a member declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for following subtypes of MemberDeclarationSyntax: /// NOTE: (1) GlobalStatementSyntax as they don't declare any symbols. /// NOTE: (2) IncompleteMemberSyntax as there are no symbols for incomplete members. /// NOTE: (3) BaseFieldDeclarationSyntax or its subtypes as these declarations can contain multiple variable declarators. /// NOTE: GetDeclaredSymbol should be called on the variable declarators directly. /// </remarks> public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); switch (declarationSyntax.Kind()) { // Few subtypes of MemberDeclarationSyntax don't declare any symbols or declare multiple symbols, return null for these cases. case SyntaxKind.GlobalStatement: // Global statements don't declare anything, even though they inherit from MemberDeclarationSyntax. return null; case SyntaxKind.IncompleteMember: // Incomplete members don't declare any symbols. return null; case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FieldDeclaration: // these declarations can contain multiple variable declarators. GetDeclaredSymbol should be called on them directly. return null; default: return (GetDeclaredNamespaceOrType(declarationSyntax) ?? GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } } public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default) { CheckSyntaxNode(declarationSyntax); return SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, declarationSyntax, fallbackToMainEntryPoint: false).GetPublicSymbol(); } /// <summary> /// Given a local function declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return this.GetMemberModel(declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a enum member declaration, get the corresponding field symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an enum member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((FieldSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a base method declaration syntax, get the corresponding method symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a method.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseMethodDeclarationSyntax as all of them return a MethodSymbol. /// </remarks> public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((MethodSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } #region "GetDeclaredSymbol overloads for BasePropertyDeclarationSyntax and its subtypes" /// <summary> /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return GetDeclaredMemberSymbol(declarationSyntax).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares a property, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares an indexer, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an indexer.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares a (custom) event, get the corresponding event symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((EventSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } #endregion #endregion /// <summary> /// Given a syntax node that declares a property or member accessor, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an accessor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Kind() == SyntaxKind.UnknownAccessorDeclaration) { // this is not a real accessor, so we shouldn't return anything. return null; } var propertyOrEventDecl = declarationSyntax.Parent.Parent; switch (propertyOrEventDecl.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: // NOTE: it's an error for field-like events to have accessors, // but we want to bind them anyway for error tolerance reasons. var container = GetDeclaredTypeMemberContainer(propertyOrEventDecl); Debug.Assert((object)container != null); Debug.Assert(declarationSyntax.Keyword.Kind() != SyntaxKind.IdentifierToken); return (this.GetDeclaredMember(container, declarationSyntax.Span) as MethodSymbol).GetPublicSymbol(); default: throw ExceptionUtilities.UnexpectedValue(propertyOrEventDecl.Kind()); } } public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var containingMemberSyntax = declarationSyntax.Parent; NamespaceOrTypeSymbol container; switch (containingMemberSyntax.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: container = GetDeclaredTypeMemberContainer(containingMemberSyntax); Debug.Assert((object)container != null); // We are looking for the SourcePropertyAccessorSymbol here, // not the SourcePropertySymbol, so use declarationSyntax // to exclude the property symbol from being retrieved. return (this.GetDeclaredMember(container, declarationSyntax.Span) as MethodSymbol).GetPublicSymbol(); default: // Don't throw, use only for the assert ExceptionUtilities.UnexpectedValue(containingMemberSyntax.Kind()); return null; } } private string GetDeclarationName(CSharpSyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: { var methodDecl = (MethodDeclarationSyntax)declaration; return GetDeclarationName(declaration, methodDecl.ExplicitInterfaceSpecifier, methodDecl.Identifier.ValueText); } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)declaration; return GetDeclarationName(declaration, propertyDecl.ExplicitInterfaceSpecifier, propertyDecl.Identifier.ValueText); } case SyntaxKind.IndexerDeclaration: { var indexerDecl = (IndexerDeclarationSyntax)declaration; return GetDeclarationName(declaration, indexerDecl.ExplicitInterfaceSpecifier, WellKnownMemberNames.Indexer); } case SyntaxKind.EventDeclaration: { var eventDecl = (EventDeclarationSyntax)declaration; return GetDeclarationName(declaration, eventDecl.ExplicitInterfaceSpecifier, eventDecl.Identifier.ValueText); } case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: return ((BaseTypeDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Identifier.ValueText; case SyntaxKind.EnumMemberDeclaration: return ((EnumMemberDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.DestructorDeclaration: return WellKnownMemberNames.DestructorName; case SyntaxKind.ConstructorDeclaration: if (((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword)) { return WellKnownMemberNames.StaticConstructorName; } else { return WellKnownMemberNames.InstanceConstructorName; } case SyntaxKind.OperatorDeclaration: { var operatorDecl = (OperatorDeclarationSyntax)declaration; return GetDeclarationName(declaration, operatorDecl.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDecl)); } case SyntaxKind.ConversionOperatorDeclaration: { var operatorDecl = (ConversionOperatorDeclarationSyntax)declaration; return GetDeclarationName(declaration, operatorDecl.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDecl)); } case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FieldDeclaration: throw new ArgumentException(CSharpResources.InvalidGetDeclarationNameMultipleDeclarators); case SyntaxKind.IncompleteMember: // There is no name - that's why it's an incomplete member. return null; default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind()); } } private string GetDeclarationName(CSharpSyntaxNode declaration, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string memberName) { if (explicitInterfaceSpecifierOpt == null) { return memberName; } // For an explicit interface implementation, we actually have several options: // Option 1: do nothing - it will retry without the name // Option 2: detect explicit impl and return null // Option 3: get a binder and figure out the name // For now, we're going with Option 3 return ExplicitInterfaceHelpers.GetMemberName(_binderFactory.GetBinder(declaration), explicitInterfaceSpecifierOpt, memberName); } private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: case SyntaxKind.IdentifierName: return GetDeclaredMember(container, declarationSpan, ((SimpleNameSyntax)name).Identifier.ValueText); case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)name; var left = GetDeclaredMember(container, declarationSpan, qn.Left) as NamespaceOrTypeSymbol; Debug.Assert((object)left != null); return GetDeclaredMember(left, declarationSpan, qn.Right); case SyntaxKind.AliasQualifiedName: // this is not supposed to happen, but we allow for errors don't we! var an = (AliasQualifiedNameSyntax)name; return GetDeclaredMember(container, declarationSpan, an.Name); default: throw ExceptionUtilities.UnexpectedValue(name.Kind()); } } /// <summary> /// Finds the member in the containing symbol which is inside the given declaration span. /// </summary> private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, string name = null) { if ((object)container == null) { return null; } // look for any member with same declaration location var collection = name != null ? container.GetMembers(name) : container.GetMembersUnordered(); Symbol zeroWidthMatch = null; foreach (var symbol in collection) { var namedType = symbol as ImplicitNamedTypeSymbol; if ((object)namedType != null && namedType.IsImplicitClass) { // look inside wrapper around illegally placed members in namespaces var result = GetDeclaredMember(namedType, declarationSpan, name); if ((object)result != null) { return result; } } foreach (var loc in symbol.Locations) { if (loc.IsInSource && loc.SourceTree == this.SyntaxTree && declarationSpan.Contains(loc.SourceSpan)) { if (loc.SourceSpan.IsEmpty && loc.SourceSpan.End == declarationSpan.Start) { // exclude decls created via syntax recovery zeroWidthMatch = symbol; } else { return symbol; } } } // Handle the case of the implementation of a partial method. var partial = symbol.Kind == SymbolKind.Method ? ((MethodSymbol)symbol).PartialImplementationPart : null; if ((object)partial != null) { var loc = partial.Locations[0]; if (loc.IsInSource && loc.SourceTree == this.SyntaxTree && declarationSpan.Contains(loc.SourceSpan)) { return partial; } } } // If we didn't find anything better than the symbol that matched because of syntax error recovery, then return that. // Otherwise, if there's a name, try again without a name. // Otherwise, give up. return zeroWidthMatch ?? (name != null ? GetDeclaredMember(container, declarationSpan) : null); } /// <summary> /// Given a variable declarator syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a variable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var field = declarationSyntax.Parent == null ? null : declarationSyntax.Parent.Parent as BaseFieldDeclarationSyntax; if (field != null) { var container = GetDeclaredTypeMemberContainer(field); Debug.Assert((object)container != null); var result = this.GetDeclaredMember(container, declarationSyntax.Span, declarationSyntax.Identifier.ValueText); Debug.Assert((object)result != null); return result.GetPublicSymbol(); } // Might be a local variable. var memberModel = this.GetMemberModel(declarationSyntax); return memberModel?.GetDeclaredSymbol(declarationSyntax, cancellationToken); } public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { // Might be a local variable. var memberModel = this.GetMemberModel(declarationSyntax); ISymbol local = memberModel?.GetDeclaredSymbol(declarationSyntax, cancellationToken); if (local != null) { return local; } // Might be a field Binder binder = GetEnclosingBinder(declarationSyntax.Position); return binder?.LookupDeclaredField(declarationSyntax).GetPublicSymbol(); } internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol originalSymbol) { var position = originalSymbol.IdentifierToken.SpanStart; return GetMemberModel(position)?.GetAdjustedLocalSymbol(originalSymbol) ?? originalSymbol; } /// <summary> /// Given a labeled statement syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the labeled statement.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var memberModel = this.GetMemberModel(declarationSyntax); return memberModel == null ? null : memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a switch label syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the switch label.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var memberModel = this.GetMemberModel(declarationSyntax); return memberModel == null ? null : memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a using declaration get the corresponding symbol for the using alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared.</returns> /// <remarks> /// If the using directive is an error because it attempts to introduce an alias for which an existing alias was /// previously declared in the same scope, the result is a newly-constructed AliasSymbol (i.e. not one from the /// symbol table). /// </remarks> public override IAliasSymbol GetDeclaredSymbol( UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Alias == null) { return null; } Binder binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); for (; binder != null; binder = binder.Next) { var usingAliases = binder.UsingAliases; if (!usingAliases.IsDefault) { foreach (var alias in usingAliases) { if (alias.Alias.Locations[0].SourceSpan == declarationSyntax.Alias.Name.Span) { return alias.Alias.GetPublicSymbol(); } } break; } } return null; } /// <summary> /// Given an extern alias declaration get the corresponding symbol for the alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared, or null if a duplicate alias symbol was declared.</returns> public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); for (; binder != null; binder = binder.Next) { var externAliases = binder.ExternAliases; if (!externAliases.IsDefault) { foreach (var alias in externAliases) { if (alias.Alias.Locations[0].SourceSpan == declarationSyntax.Identifier.Span) { return alias.Alias.GetPublicSymbol(); } } break; } } return null; } /// <summary> /// Given a base field declaration syntax, get the corresponding symbols. /// </summary> /// <param name="declarationSyntax">The syntax node that declares one or more fields or events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The field symbols that were declared.</returns> internal override ImmutableArray<ISymbol> GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var builder = new ArrayBuilder<ISymbol>(); foreach (var declarator in declarationSyntax.Declaration.Variables) { var field = this.GetDeclaredSymbol(declarator, cancellationToken) as ISymbol; if (field != null) { builder.Add(field); } } return builder.ToImmutableAndFree(); } private ParameterSymbol GetMethodParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as ParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as MemberDeclarationSyntax; if (memberDecl == null) { return null; } MethodSymbol method; if (memberDecl is RecordDeclarationSyntax recordDecl && recordDecl.ParameterList == paramList) { method = TryGetSynthesizedRecordConstructor(recordDecl); } else { method = (GetDeclaredSymbol(memberDecl, cancellationToken) as IMethodSymbol).GetSymbol(); } if ((object)method == null) { return null; } return GetParameterSymbol(method.Parameters, parameter, cancellationToken) ?? ((object)method.PartialDefinitionPart == null ? null : GetParameterSymbol(method.PartialDefinitionPart.Parameters, parameter, cancellationToken)); } private ParameterSymbol GetIndexerParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as BracketedParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as MemberDeclarationSyntax; if (memberDecl == null) { return null; } var property = (GetDeclaredSymbol(memberDecl, cancellationToken) as IPropertySymbol).GetSymbol(); if ((object)property == null) { return null; } return GetParameterSymbol(property.Parameters, parameter, cancellationToken); } private ParameterSymbol GetDelegateParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as ParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as DelegateDeclarationSyntax; if (memberDecl == null) { return null; } var delegateType = (GetDeclaredSymbol(memberDecl, cancellationToken) as INamedTypeSymbol).GetSymbol(); if ((object)delegateType == null) { return null; } var delegateInvoke = delegateType.DelegateInvokeMethod; if ((object)delegateInvoke == null || delegateInvoke.HasUseSiteError) { return null; } return GetParameterSymbol(delegateInvoke.Parameters, parameter, cancellationToken); } /// <summary> /// Given a parameter declaration syntax node, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a parameter.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The parameter that was declared.</returns> public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); MemberSemanticModel memberModel = this.GetMemberModel(declarationSyntax); if (memberModel != null) { // Could be parameter of lambda. return memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } return GetDeclaredNonLambdaParameterSymbol(declarationSyntax, cancellationToken).GetPublicSymbol(); } private ParameterSymbol GetDeclaredNonLambdaParameterSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return GetMethodParameterSymbol(declarationSyntax, cancellationToken) ?? GetIndexerParameterSymbol(declarationSyntax, cancellationToken) ?? GetDelegateParameterSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a type parameter declaration (field or method), get the corresponding symbol /// </summary> /// <param name="typeParameter"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)) { if (typeParameter == null) { throw new ArgumentNullException(nameof(typeParameter)); } if (!IsInTree(typeParameter)) { throw new ArgumentException("typeParameter not within tree"); } if (typeParameter.Parent is TypeParameterListSyntax typeParamList) { ISymbol parameterizedSymbol = null; switch (typeParamList.Parent) { case MemberDeclarationSyntax memberDecl: parameterizedSymbol = GetDeclaredSymbol(memberDecl, cancellationToken); break; case LocalFunctionStatementSyntax localDecl: parameterizedSymbol = GetDeclaredSymbol(localDecl, cancellationToken); break; default: throw ExceptionUtilities.UnexpectedValue(typeParameter.Parent.Kind()); } switch (parameterizedSymbol.GetSymbol()) { case NamedTypeSymbol typeSymbol: return this.GetTypeParameterSymbol(typeSymbol.TypeParameters, typeParameter).GetPublicSymbol(); case MethodSymbol methodSymbol: return (this.GetTypeParameterSymbol(methodSymbol.TypeParameters, typeParameter) ?? ((object)methodSymbol.PartialDefinitionPart == null ? null : this.GetTypeParameterSymbol(methodSymbol.PartialDefinitionPart.TypeParameters, typeParameter))).GetPublicSymbol(); } } return null; } private TypeParameterSymbol GetTypeParameterSymbol(ImmutableArray<TypeParameterSymbol> parameters, TypeParameterSyntax parameter) { foreach (var symbol in parameters) { foreach (var location in symbol.Locations) { if (location.SourceTree == this.SyntaxTree && parameter.Span.Contains(location.SourceSpan)) { return symbol; } } } return null; } public override ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { ValidateStatementRange(firstStatement, lastStatement); var context = RegionAnalysisContext(firstStatement, lastStatement); var result = new CSharpControlFlowAnalysis(context); return result; } private void ValidateStatementRange(StatementSyntax firstStatement, StatementSyntax lastStatement) { if (firstStatement == null) { throw new ArgumentNullException(nameof(firstStatement)); } if (lastStatement == null) { throw new ArgumentNullException(nameof(lastStatement)); } if (!IsInTree(firstStatement)) { throw new ArgumentException("statements not within tree"); } // Global statements don't have their parent in common, but should belong to the same compilation unit bool isGlobalStatement = firstStatement.Parent is GlobalStatementSyntax; if (isGlobalStatement && (lastStatement.Parent is not GlobalStatementSyntax || firstStatement.Parent.Parent != lastStatement.Parent.Parent)) { throw new ArgumentException("global statements not within the same compilation unit"); } // Non-global statements, the parents should be the same if (!isGlobalStatement && (firstStatement.Parent == null || firstStatement.Parent != lastStatement.Parent)) { throw new ArgumentException("statements not within the same statement list"); } if (firstStatement.SpanStart > lastStatement.SpanStart) { throw new ArgumentException("first statement does not precede last statement"); } } public override DataFlowAnalysis AnalyzeDataFlow(ExpressionSyntax expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (!IsInTree(expression)) { throw new ArgumentException("expression not within tree"); } var context = RegionAnalysisContext(expression); var result = new CSharpDataFlowAnalysis(context); return result; } public override DataFlowAnalysis AnalyzeDataFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { ValidateStatementRange(firstStatement, lastStatement); var context = RegionAnalysisContext(firstStatement, lastStatement); var result = new CSharpDataFlowAnalysis(context); return result; } private static BoundNode GetBoundRoot(MemberSemanticModel memberModel, out Symbol member) { member = memberModel.MemberSymbol; return memberModel.GetBoundRoot(); } private NamespaceOrTypeSymbol GetDeclaredTypeMemberContainer(CSharpSyntaxNode memberDeclaration) { if (memberDeclaration.Parent.Kind() == SyntaxKind.CompilationUnit) { // top-level namespace: if (memberDeclaration.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration) { return _compilation.Assembly.GlobalNamespace; } // top-level members in script or interactive code: if (this.SyntaxTree.Options.Kind != SourceCodeKind.Regular) { return this.Compilation.ScriptClass; } // top-level type in an explicitly declared namespace: if (SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) { return _compilation.Assembly.GlobalNamespace; } // other top-level members: return _compilation.Assembly.GlobalNamespace.ImplicitType; } var container = GetDeclaredNamespaceOrType(memberDeclaration.Parent); Debug.Assert((object)container != null); // member in a type: if (!container.IsNamespace) { return container; } // a namespace or a type in an explicitly declared namespace: if (memberDeclaration.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) { return container; } // another member in a namespace: return ((NamespaceSymbol)container).ImplicitType; } private Symbol GetDeclaredMemberSymbol(CSharpSyntaxNode declarationSyntax) { CheckSyntaxNode(declarationSyntax); var container = GetDeclaredTypeMemberContainer(declarationSyntax); var name = GetDeclarationName(declarationSyntax); return this.GetDeclaredMember(container, declarationSyntax.Span, name); } public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(AwaitExpressionInfo) : memberModel.GetAwaitExpressionInfo(node); } public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node); } public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node); } public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel?.GetDeconstructionInfo(node) ?? default; } public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel?.GetDeconstructionInfo(node) ?? default; } internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol) { Debug.Assert(symbol is LocalSymbol or ParameterSymbol or MethodSymbol { MethodKind: MethodKind.LambdaMethod }); if (symbol.Locations.IsDefaultOrEmpty) { return symbol; } var location = symbol.Locations[0]; // The symbol may be from a distinct syntax tree - perhaps the // symbol was returned from LookupSymbols() for instance. if (location.SourceTree != this.SyntaxTree) { return symbol; } var position = CheckAndAdjustPosition(location.SourceSpan.Start); var memberModel = GetMemberModel(position); return memberModel?.RemapSymbolIfNecessaryCore(symbol) ?? symbol; } internal override Func<SyntaxNode, bool> GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) { switch (declaredNode) { case CompilationUnitSyntax unit when SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, unit, fallbackToMainEntryPoint: false) is SynthesizedSimpleProgramEntryPointSymbol entryPoint: switch (declaredSymbol.Kind) { case SymbolKind.Namespace: Debug.Assert(((INamespaceSymbol)declaredSymbol).IsGlobalNamespace); // Do not include top level global statements into a global namespace return (node) => node.Kind() != SyntaxKind.GlobalStatement || node.Parent != unit; case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)entryPoint); // Include only global statements at the top level return (node) => node.Parent != unit || node.Kind() == SyntaxKind.GlobalStatement; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)entryPoint.ContainingSymbol); return (node) => false; default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } break; case RecordDeclarationSyntax recordDeclaration when TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor ctor: if (recordDeclaration.IsKind(SyntaxKind.RecordDeclaration)) { switch (declaredSymbol.Kind) { case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor); return (node) => { // Accept only nodes that either match, or above/below of a 'parameter list'/'base arguments list'. if (node.Parent == recordDeclaration) { return node == recordDeclaration.ParameterList || node == recordDeclaration.BaseList; } else if (node.Parent is BaseListSyntax baseList) { return node == recordDeclaration.PrimaryConstructorBaseTypeIfClass; } else if (node.Parent is PrimaryConstructorBaseTypeSyntax baseType && baseType == recordDeclaration.PrimaryConstructorBaseTypeIfClass) { return node == baseType.ArgumentList; } return true; }; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor.ContainingSymbol); // Accept nodes that do not match a 'parameter list'/'base arguments list'. return (node) => node != recordDeclaration.ParameterList && !(node.Kind() == SyntaxKind.ArgumentList && node == recordDeclaration.PrimaryConstructorBaseTypeIfClass?.ArgumentList); default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } } else { switch (declaredSymbol.Kind) { case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor); return (node) => { // Accept only nodes that either match, or above/below of a 'parameter list'. if (node.Parent == recordDeclaration) { return node == recordDeclaration.ParameterList; } return true; }; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor.ContainingSymbol); // Accept nodes that do not match a 'parameter list'. return (node) => node != recordDeclaration.ParameterList; default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } } break; case PrimaryConstructorBaseTypeSyntax { Parent: BaseListSyntax { Parent: RecordDeclarationSyntax recordDeclaration } } baseType when recordDeclaration.PrimaryConstructorBaseTypeIfClass == declaredNode && TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor ctor: if ((object)declaredSymbol.GetSymbol() == (object)ctor) { // Only 'base arguments list' or nodes below it return (node) => node != baseType.Type; } break; case ParameterSyntax param when declaredSymbol.Kind == SymbolKind.Property && param.Parent?.Parent is RecordDeclarationSyntax recordDeclaration && recordDeclaration.ParameterList == param.Parent: Debug.Assert(declaredSymbol.GetSymbol() is SynthesizedRecordPropertySymbol); return (node) => false; } 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.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Allows asking semantic questions about any node in a SyntaxTree within a Compilation. /// </summary> internal partial class SyntaxTreeSemanticModel : CSharpSemanticModel { private readonly CSharpCompilation _compilation; private readonly SyntaxTree _syntaxTree; /// <summary> /// Note, the name of this field could be somewhat confusing because it is also /// used to store models for attributes and default parameter values, which are /// not members. /// </summary> private ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel> _memberModels = ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel>.Empty; private readonly BinderFactory _binderFactory; private Func<CSharpSyntaxNode, MemberSemanticModel> _createMemberModelFunction; private readonly bool _ignoresAccessibility; private ScriptLocalScopeBinder.Labels _globalStatementLabels; private static readonly Func<CSharpSyntaxNode, bool> s_isMemberDeclarationFunction = IsMemberDeclaration; #nullable enable internal SyntaxTreeSemanticModel(CSharpCompilation compilation, SyntaxTree syntaxTree, bool ignoreAccessibility = false) { _compilation = compilation; _syntaxTree = syntaxTree; _ignoresAccessibility = ignoreAccessibility; if (!this.Compilation.SyntaxTrees.Contains(syntaxTree)) { throw new ArgumentOutOfRangeException(nameof(syntaxTree), CSharpResources.TreeNotPartOfCompilation); } _binderFactory = compilation.GetBinderFactory(SyntaxTree, ignoreAccessibility); } internal SyntaxTreeSemanticModel(CSharpCompilation parentCompilation, SyntaxTree parentSyntaxTree, SyntaxTree speculatedSyntaxTree) { _compilation = parentCompilation; _syntaxTree = speculatedSyntaxTree; _binderFactory = _compilation.GetBinderFactory(parentSyntaxTree); } /// <summary> /// The compilation this object was obtained from. /// </summary> public override CSharpCompilation Compilation { get { return _compilation; } } /// <summary> /// The root node of the syntax tree that this object is associated with. /// </summary> internal override CSharpSyntaxNode Root { get { return (CSharpSyntaxNode)_syntaxTree.GetRoot(); } } /// <summary> /// The SyntaxTree that this object is associated with. /// </summary> public override SyntaxTree SyntaxTree { get { return _syntaxTree; } } /// <summary> /// Returns true if this is a SemanticModel that ignores accessibility rules when answering semantic questions. /// </summary> public override bool IgnoresAccessibility { get { return _ignoresAccessibility; } } private void VerifySpanForGetDiagnostics(TextSpan? span) { if (span.HasValue && !this.Root.FullSpan.Contains(span.Value)) { throw new ArgumentException("span"); } } public override ImmutableArray<Diagnostic> GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Parse, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Declare, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Compile, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Compile, this.SyntaxTree, span, includeEarlierStages: true, cancellationToken: cancellationToken); } #nullable disable /// <summary> /// Gets the enclosing binder associated with the node /// </summary> /// <param name="position"></param> /// <returns></returns> internal override Binder GetEnclosingBinderInternal(int position) { AssertPositionAdjusted(position); SyntaxToken token = this.Root.FindTokenIncludingCrefAndNameAttributes(position); // If we're before the start of the first token, just return // the binder for the compilation unit. if (position == 0 && position != token.SpanStart) { return _binderFactory.GetBinder(this.Root, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); } MemberSemanticModel memberModel = GetMemberModel(position); if (memberModel != null) { return memberModel.GetEnclosingBinder(position); } return _binderFactory.GetBinder((CSharpSyntaxNode)token.Parent, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); } internal override IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { MemberSemanticModel model; switch (node) { case ConstructorDeclarationSyntax constructor: model = (constructor.HasAnyBody() || constructor.Initializer != null) ? GetOrAddModel(node) : null; break; case BaseMethodDeclarationSyntax method: model = method.HasAnyBody() ? GetOrAddModel(node) : null; break; case AccessorDeclarationSyntax accessor: model = (accessor.Body != null || accessor.ExpressionBody != null) ? GetOrAddModel(node) : null; break; case RecordDeclarationSyntax { ParameterList: { }, PrimaryConstructorBaseTypeIfClass: { } } recordDeclaration when TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor: model = GetOrAddModel(recordDeclaration); break; default: model = this.GetMemberModel(node); break; } if (model != null) { return model.GetOperationWorker(node, cancellationToken); } else { return null; } } internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { ValidateSymbolInfoOptions(options); // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); SymbolInfo result; XmlNameAttributeSyntax attrSyntax; CrefSyntax crefSyntax; if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. result = model.GetSymbolInfoWorker(node, options, cancellationToken); // If we didn't get anything and were in Type/Namespace only context, let's bind normally and see // if any symbol comes out. if ((object)result.Symbol == null && result.CandidateReason == CandidateReason.None && node is ExpressionSyntax && SyntaxFacts.IsInNamespaceOrTypeContext((ExpressionSyntax)node)) { var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // Wrap the binder in a LocalScopeBinder because Binder.BindExpression assumes there // will be one in the binder chain and one isn't necessarily required for the batch case. binder = new LocalScopeBinder(binder); BoundExpression bound = binder.BindExpression((ExpressionSyntax)node, BindingDiagnosticBag.Discarded); SymbolInfo info = GetSymbolInfoForNode(options, bound, bound, boundNodeForSyntacticParent: null, binderOpt: null); if ((object)info.Symbol != null) { result = new SymbolInfo(null, ImmutableArray.Create<ISymbol>(info.Symbol), CandidateReason.NotATypeOrNamespace); } else if (!info.CandidateSymbols.IsEmpty) { result = new SymbolInfo(null, info.CandidateSymbols, CandidateReason.NotATypeOrNamespace); } } } } else if (node.Parent.Kind() == SyntaxKind.XmlNameAttribute && (attrSyntax = (XmlNameAttributeSyntax)node.Parent).Identifier == node) { result = SymbolInfo.None; var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var symbols = binder.BindXmlNameAttribute(attrSyntax, ref discardedUseSiteInfo); // NOTE: We don't need to call GetSymbolInfoForSymbol because the symbols // can only be parameters or type parameters. Debug.Assert(symbols.All(s => s.Kind == SymbolKind.TypeParameter || s.Kind == SymbolKind.Parameter)); switch (symbols.Length) { case 0: result = SymbolInfo.None; break; case 1: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Viable, isDynamic: false); break; default: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Ambiguous, isDynamic: false); break; } } } else if ((crefSyntax = node as CrefSyntax) != null) { int adjustedPosition = GetAdjustedNodePosition(crefSyntax); result = GetCrefSymbolInfo(adjustedPosition, crefSyntax, options, HasParameterList(crefSyntax)); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: (options & SymbolInfoOptions.PreserveAliases) != 0); result = (object)symbol != null ? GetSymbolInfoForSymbol(symbol, options) : SymbolInfo.None; } return result; } internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { var model = this.GetMemberModel(collectionInitializer); if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. return model.GetCollectionInitializerSymbolInfoWorker(collectionInitializer, node, cancellationToken); } return SymbolInfo.None; } internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. return model.GetTypeInfoWorker(node, cancellationToken); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: false); // Don't care about aliases here. return (object)symbol != null ? GetTypeInfoForSymbol(symbol) : CSharpTypeInfo.None; } } // Common helper method for GetSymbolInfoWorker and GetTypeInfoWorker, which is called when there is no member model for the given syntax node. // Even if the expression is not part of a member context, the caller may really just have a reference to a type or namespace name. // If so, the methods binds the syntax as a namespace or type or alias symbol. Otherwise, it returns null. private Symbol GetSemanticInfoSymbolInNonMemberContext(CSharpSyntaxNode node, bool bindVarAsAliasFirst) { Debug.Assert(this.GetMemberModel(node) == null); var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var type = node as TypeSyntax; if ((object)type != null) { // determine if this type is part of a base declaration being resolved var basesBeingResolved = GetBasesBeingResolved(type); if (SyntaxFacts.IsNamespaceAliasQualifier(type)) { return binder.BindNamespaceAliasSymbol(node as IdentifierNameSyntax, BindingDiagnosticBag.Discarded); } else if (SyntaxFacts.IsInTypeOnlyContext(type)) { if (!type.IsVar) { return binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; } Symbol result = bindVarAsAliasFirst ? binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol : null; // CONSIDER: we might bind "var" twice - once to see if it is an alias and again // as the type of a declared field. This should only happen for GetAliasInfo // calls on implicitly-typed fields (rare?). If it becomes a problem, then we // probably need to have the FieldSymbol retain alias info when it does its own // binding and expose it to us here. if ((object)result == null || result.Kind == SymbolKind.ErrorType) { // We might be in a field declaration with "var" keyword as the type name. // Implicitly typed field symbols are not allowed in regular C#, // but they are allowed in interactive scenario. // However, we can return fieldSymbol.Type for implicitly typed field symbols in both cases. // Note that for regular C#, fieldSymbol.Type would be an error type. var variableDecl = type.Parent as VariableDeclarationSyntax; if (variableDecl != null && variableDecl.Variables.Any()) { var fieldSymbol = GetDeclaredFieldSymbol(variableDecl.Variables.First()); if ((object)fieldSymbol != null) { result = fieldSymbol.Type; } } } return result ?? binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; } else { return binder.BindNamespaceOrTypeOrAliasSymbol(type, BindingDiagnosticBag.Discarded, basesBeingResolved, basesBeingResolved != null).Symbol; } } } return null; } internal override ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? ImmutableArray<Symbol>.Empty : model.GetMemberGroupWorker(node, options, cancellationToken); } internal override ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? ImmutableArray<IPropertySymbol>.Empty : model.GetIndexerGroupWorker(node, options, cancellationToken); } internal override Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { // in case this is right side of a qualified name or member access node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? default(Optional<object>) : model.GetConstantValueWorker(node, cancellationToken); } public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? default(QueryClauseInfo) : model.GetQueryClauseInfo(node, cancellationToken); } public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? SymbolInfo.None : model.GetSymbolInfo(node, cancellationToken); } public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? CSharpTypeInfo.None : model.GetTypeInfo(node, cancellationToken); } public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? SymbolInfo.None : model.GetSymbolInfo(node, cancellationToken); } private ConsList<TypeSymbol> GetBasesBeingResolved(TypeSyntax expression) { // if the expression is the child of a base-list node, then the expression should be // bound in the context of the containing symbols base being resolved. for (; expression != null && expression.Parent != null; expression = expression.Parent as TypeSyntax) { var parent = expression.Parent; if (parent is BaseTypeSyntax baseType && parent.Parent != null && parent.Parent.Kind() == SyntaxKind.BaseList && baseType.Type == expression) { // we have a winner var decl = (BaseTypeDeclarationSyntax)parent.Parent.Parent; var symbol = this.GetDeclaredSymbol(decl); return ConsList<TypeSymbol>.Empty.Prepend(symbol.GetSymbol().OriginalDefinition); } } return null; } public override Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) { TypeSymbol csdestination = destination.EnsureCSharpSymbolOrNull(nameof(destination)); if (expression.Kind() == SyntaxKind.DeclarationExpression) { // Conversion from a declaration is unspecified. return Conversion.NoConversion; } if (isExplicitInSource) { return ClassifyConversionForCast(expression, csdestination); } CheckSyntaxNode(expression); if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } // TODO(cyrusn): Check arguments. This is a public entrypoint, so we must do appropriate // checks here. However, no other methods in this type do any checking currently. So I'm // going to hold off on this until we do a full sweep of the API. var model = this.GetMemberModel(expression); if (model == null) { // 'expression' must just be reference to a type or namespace name outside of an // expression context. Currently we bail in that case. However, is this a question // that a client would be asking and would expect sensible results for? return Conversion.NoConversion; } return model.ClassifyConversion(expression, destination); } internal override Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination) { CheckSyntaxNode(expression); if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } var model = this.GetMemberModel(expression); if (model == null) { // 'expression' must just be reference to a type or namespace name outside of an // expression context. Currently we bail in that case. However, is this a question // that a client would be asking and would expect sensible results for? return Conversion.NoConversion; } return model.ClassifyConversionForCast(expression, destination); } public override bool IsSpeculativeSemanticModel { get { return false; } } public override int OriginalPositionForSpeculation { get { return 0; } } public override CSharpSemanticModel ParentModel { get { return null; } } internal override SemanticModel ContainingModelOrSelf { get { return this; } } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, type, bindingOption, out speculativeModel); } Binder binder = GetSpeculativeBinder(position, type, bindingOption); if (binder != null) { speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, type, binder, position, bindingOption); return true; } speculativeModel = null; return false; } internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); Binder binder = GetEnclosingBinder(position); if (binder?.InCref == true) { speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, crefSyntax, binder, position); return true; } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, statement, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, method, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, accessor, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, initializer, out speculativeModel); } speculativeModel = null; return false; } internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, expressionBody, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<ConstructorInitializerSyntax>().FirstOrDefault(); if (existingConstructorInitializer != null) { var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); } } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<PrimaryConstructorBaseTypeSyntax>().FirstOrDefault(); if (existingConstructorInitializer != null) { var model = this.GetMemberModel(existingConstructorInitializer); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); } } speculativeModel = null; return false; } internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } // If the given position is in a member that we can get a semantic model for, we want to defer to that implementation // of GetSpeculativelyBoundExpression so it can take nullability into account. if (bindingOption == SpeculativeBindingOption.BindAsExpression) { position = CheckAndAdjustPosition(position); var model = GetMemberModel(position); if (model is object) { return model.GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); } } return GetSpeculativelyBoundExpressionWithoutNullability(position, expression, bindingOption, out binder, out crefSymbols); } internal AttributeSemanticModel CreateSpeculativeAttributeSemanticModel(int position, AttributeSyntax attribute, Binder binder, AliasSymbol aliasOpt, NamedTypeSymbol attributeType) { var memberModel = IsNullableAnalysisEnabledAtSpeculativePosition(position, attribute) ? GetMemberModel(position) : null; return AttributeSemanticModel.CreateSpeculative(this, attribute, attributeType, aliasOpt, binder, memberModel?.GetRemappedSymbols(), position); } internal bool IsNullableAnalysisEnabledAtSpeculativePosition(int position, SyntaxNode speculativeSyntax) { Debug.Assert(speculativeSyntax.SyntaxTree != SyntaxTree); // https://github.com/dotnet/roslyn/issues/50234: CSharpSyntaxTree.IsNullableAnalysisEnabled() does not differentiate // between no '#nullable' directives and '#nullable restore' - it returns null in both cases. Since we fallback to the // directives in the original syntax tree, we're not handling '#nullable restore' correctly in the speculative text. return ((CSharpSyntaxTree)speculativeSyntax.SyntaxTree).IsNullableAnalysisEnabled(speculativeSyntax.Span) ?? Compilation.IsNullableAnalysisEnabledIn((CSharpSyntaxTree)SyntaxTree, new TextSpan(position, 0)); } private MemberSemanticModel GetMemberModel(int position) { AssertPositionAdjusted(position); CSharpSyntaxNode node = (CSharpSyntaxNode)Root.FindTokenIncludingCrefAndNameAttributes(position).Parent; CSharpSyntaxNode memberDecl = GetMemberDeclaration(node); bool outsideMemberDecl = false; if (memberDecl != null) { switch (memberDecl.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: // NOTE: not UnknownAccessorDeclaration since there's no corresponding method symbol from which to build a member model. outsideMemberDecl = !LookupPosition.IsInBody(position, (AccessorDeclarationSyntax)memberDecl); break; case SyntaxKind.ConstructorDeclaration: var constructorDecl = (ConstructorDeclarationSyntax)memberDecl; outsideMemberDecl = !LookupPosition.IsInConstructorParameterScope(position, constructorDecl) && !LookupPosition.IsInParameterList(position, constructorDecl); break; case SyntaxKind.RecordDeclaration: { var recordDecl = (RecordDeclarationSyntax)memberDecl; if (recordDecl.ParameterList is null) { outsideMemberDecl = true; } else { var argumentList = recordDecl.PrimaryConstructorBaseTypeIfClass?.ArgumentList; outsideMemberDecl = argumentList is null || !LookupPosition.IsBetweenTokens(position, argumentList.OpenParenToken, argumentList.CloseParenToken); } } break; case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: var methodDecl = (BaseMethodDeclarationSyntax)memberDecl; outsideMemberDecl = !LookupPosition.IsInBody(position, methodDecl) && !LookupPosition.IsInParameterList(position, methodDecl); break; } } return outsideMemberDecl ? null : GetMemberModel(node); } // Try to get a member semantic model that encloses "node". If there is not an enclosing // member semantic model, return null. internal override MemberSemanticModel GetMemberModel(SyntaxNode node) { // Documentation comments can never legally appear within members, so there's no point // in building out the MemberSemanticModel to handle them. Instead, just say have // SyntaxTreeSemanticModel handle them, regardless of location. if (IsInDocumentationComment(node)) { return null; } var memberDecl = GetMemberDeclaration(node) ?? (node as CompilationUnitSyntax); if (memberDecl != null) { var span = node.Span; switch (memberDecl.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: { var methodDecl = (BaseMethodDeclarationSyntax)memberDecl; var expressionBody = methodDecl.GetExpressionBodySyntax(); return (expressionBody?.FullSpan.Contains(span) == true || methodDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(methodDecl) : null; } case SyntaxKind.ConstructorDeclaration: { ConstructorDeclarationSyntax constructorDecl = (ConstructorDeclarationSyntax)memberDecl; var expressionBody = constructorDecl.GetExpressionBodySyntax(); return (constructorDecl.Initializer?.FullSpan.Contains(span) == true || expressionBody?.FullSpan.Contains(span) == true || constructorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(constructorDecl) : null; } case SyntaxKind.RecordDeclaration: { var recordDecl = (RecordDeclarationSyntax)memberDecl; return recordDecl.ParameterList is object && recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments && (node == baseWithArguments || baseWithArguments.ArgumentList.FullSpan.Contains(span)) ? GetOrAddModel(memberDecl) : null; } case SyntaxKind.DestructorDeclaration: { DestructorDeclarationSyntax destructorDecl = (DestructorDeclarationSyntax)memberDecl; var expressionBody = destructorDecl.GetExpressionBodySyntax(); return (expressionBody?.FullSpan.Contains(span) == true || destructorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(destructorDecl) : null; } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: // NOTE: not UnknownAccessorDeclaration since there's no corresponding method symbol from which to build a member model. { var accessorDecl = (AccessorDeclarationSyntax)memberDecl; return (accessorDecl.ExpressionBody?.FullSpan.Contains(span) == true || accessorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(accessorDecl) : null; } case SyntaxKind.IndexerDeclaration: { var indexerDecl = (IndexerDeclarationSyntax)memberDecl; return GetOrAddModelIfContains(indexerDecl.ExpressionBody, span); } case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: { var fieldDecl = (BaseFieldDeclarationSyntax)memberDecl; foreach (var variableDecl in fieldDecl.Declaration.Variables) { var binding = GetOrAddModelIfContains(variableDecl.Initializer, span); if (binding != null) { return binding; } } } break; case SyntaxKind.EnumMemberDeclaration: { var enumDecl = (EnumMemberDeclarationSyntax)memberDecl; return (enumDecl.EqualsValue != null) ? GetOrAddModelIfContains(enumDecl.EqualsValue, span) : null; } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)memberDecl; return GetOrAddModelIfContains(propertyDecl.Initializer, span) ?? GetOrAddModelIfContains(propertyDecl.ExpressionBody, span); } case SyntaxKind.GlobalStatement: if (SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)memberDecl)) { return GetOrAddModel((CompilationUnitSyntax)memberDecl.Parent); } return GetOrAddModel(memberDecl); case SyntaxKind.CompilationUnit: if (SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)memberDecl, fallbackToMainEntryPoint: false) is object) { return GetOrAddModel(memberDecl); } break; case SyntaxKind.Attribute: return GetOrAddModelForAttribute((AttributeSyntax)memberDecl); case SyntaxKind.Parameter: if (node != memberDecl) { return GetOrAddModelForParameter((ParameterSyntax)memberDecl, span); } else { return GetMemberModel(memberDecl.Parent); } } } return null; } /// <summary> /// Internal for test purposes only /// </summary> internal ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel> TestOnlyMemberModels => _memberModels; private MemberSemanticModel GetOrAddModelForAttribute(AttributeSyntax attribute) { MemberSemanticModel containing = attribute.Parent != null ? GetMemberModel(attribute.Parent) : null; if (containing == null) { return GetOrAddModel(attribute); } return ImmutableInterlocked.GetOrAdd(ref _memberModels, attribute, (node, binderAndModel) => CreateModelForAttribute(binderAndModel.binder, (AttributeSyntax)node, binderAndModel.model), (binder: containing.GetEnclosingBinder(attribute.SpanStart), model: containing)); } private static bool IsInDocumentationComment(SyntaxNode node) { for (SyntaxNode curr = node; curr != null; curr = curr.Parent) { if (SyntaxFacts.IsDocumentationCommentTrivia(curr.Kind())) { return true; } } return false; } // Check parameter for a default value containing span, and create an InitializerSemanticModel for binding the default value if so. // Otherwise, return model for enclosing context. private MemberSemanticModel GetOrAddModelForParameter(ParameterSyntax paramDecl, TextSpan span) { EqualsValueClauseSyntax defaultValueSyntax = paramDecl.Default; MemberSemanticModel containing = paramDecl.Parent != null ? GetMemberModel(paramDecl.Parent) : null; if (containing == null) { return GetOrAddModelIfContains(defaultValueSyntax, span); } if (defaultValueSyntax != null && defaultValueSyntax.FullSpan.Contains(span)) { var parameterSymbol = containing.GetDeclaredSymbol(paramDecl).GetSymbol<ParameterSymbol>(); if ((object)parameterSymbol != null) { return ImmutableInterlocked.GetOrAdd(ref _memberModels, defaultValueSyntax, (equalsValue, tuple) => InitializerSemanticModel.Create( this, tuple.paramDecl, tuple.parameterSymbol, tuple.containing.GetEnclosingBinder(tuple.paramDecl.SpanStart). CreateBinderForParameterDefaultValue(tuple.parameterSymbol, (EqualsValueClauseSyntax)equalsValue), tuple.containing.GetRemappedSymbols()), (compilation: this.Compilation, paramDecl, parameterSymbol, containing) ); } } return containing; } private static CSharpSyntaxNode GetMemberDeclaration(SyntaxNode node) { return node.FirstAncestorOrSelf(s_isMemberDeclarationFunction); } private MemberSemanticModel GetOrAddModelIfContains(CSharpSyntaxNode node, TextSpan span) { if (node != null && node.FullSpan.Contains(span)) { return GetOrAddModel(node); } return null; } private MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node) { var createMemberModelFunction = _createMemberModelFunction ?? (_createMemberModelFunction = this.CreateMemberModel); return GetOrAddModel(node, createMemberModelFunction); } internal MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node, Func<CSharpSyntaxNode, MemberSemanticModel> createMemberModelFunction) { return ImmutableInterlocked.GetOrAdd(ref _memberModels, node, createMemberModelFunction); } // Create a member model for the given declaration syntax. In certain very malformed // syntax trees, there may not be a symbol that can have a member model associated with it // (although we try to minimize such cases). In such cases, null is returned. private MemberSemanticModel CreateMemberModel(CSharpSyntaxNode node) { Binder defaultOuter() => _binderFactory.GetBinder(node).WithAdditionalFlags(this.IgnoresAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None); switch (node.Kind()) { case SyntaxKind.CompilationUnit: return createMethodBodySemanticModel(node, SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)node, fallbackToMainEntryPoint: false)); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: { var memberDecl = (MemberDeclarationSyntax)node; var symbol = GetDeclaredSymbol(memberDecl).GetSymbol<SourceMemberMethodSymbol>(); return createMethodBodySemanticModel(memberDecl, symbol); } case SyntaxKind.RecordDeclaration: { SynthesizedRecordConstructor symbol = TryGetSynthesizedRecordConstructor((RecordDeclarationSyntax)node); if (symbol is null) { return null; } return createMethodBodySemanticModel(node, symbol); } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: { var accessorDecl = (AccessorDeclarationSyntax)node; var symbol = GetDeclaredSymbol(accessorDecl).GetSymbol<SourceMemberMethodSymbol>(); return createMethodBodySemanticModel(accessorDecl, symbol); } case SyntaxKind.Block: // Don't throw, just use for the assert ExceptionUtilities.UnexpectedValue(node.Parent); break; case SyntaxKind.EqualsValueClause: switch (node.Parent.Kind()) { case SyntaxKind.VariableDeclarator: { var variableDecl = (VariableDeclaratorSyntax)node.Parent; FieldSymbol fieldSymbol = GetDeclaredFieldSymbol(variableDecl); return InitializerSemanticModel.Create( this, variableDecl, //pass in the entire field initializer to permit region analysis. fieldSymbol, //if we're in regular C#, then insert an extra binder to perform field initialization checks GetFieldOrPropertyInitializerBinder(fieldSymbol, defaultOuter(), variableDecl.Initializer)); } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)node.Parent; var propertySymbol = GetDeclaredSymbol(propertyDecl).GetSymbol<SourcePropertySymbol>(); return InitializerSemanticModel.Create( this, propertyDecl, propertySymbol, GetFieldOrPropertyInitializerBinder(propertySymbol.BackingField, defaultOuter(), propertyDecl.Initializer)); } case SyntaxKind.Parameter: { // NOTE: we don't need to create a member model for lambda parameter default value // (which is bad code anyway) because lambdas only appear in code with associated // member models. ParameterSyntax parameterDecl = (ParameterSyntax)node.Parent; ParameterSymbol parameterSymbol = GetDeclaredNonLambdaParameterSymbol(parameterDecl); if ((object)parameterSymbol == null) return null; return InitializerSemanticModel.Create( this, parameterDecl, parameterSymbol, defaultOuter().CreateBinderForParameterDefaultValue(parameterSymbol, (EqualsValueClauseSyntax)node), parentRemappedSymbolsOpt: null); } case SyntaxKind.EnumMemberDeclaration: { var enumDecl = (EnumMemberDeclarationSyntax)node.Parent; var enumSymbol = GetDeclaredSymbol(enumDecl).GetSymbol<FieldSymbol>(); if ((object)enumSymbol == null) return null; return InitializerSemanticModel.Create( this, enumDecl, enumSymbol, GetFieldOrPropertyInitializerBinder(enumSymbol, defaultOuter(), enumDecl.EqualsValue)); } default: throw ExceptionUtilities.UnexpectedValue(node.Parent.Kind()); } case SyntaxKind.ArrowExpressionClause: { SourceMemberMethodSymbol symbol = null; var exprDecl = (ArrowExpressionClauseSyntax)node; if (node.Parent is BasePropertyDeclarationSyntax) { symbol = GetDeclaredSymbol(exprDecl).GetSymbol<SourceMemberMethodSymbol>(); } else { // Don't throw, just use for the assert ExceptionUtilities.UnexpectedValue(node.Parent); } ExecutableCodeBinder binder = symbol?.TryGetBodyBinder(_binderFactory, this.IgnoresAccessibility); if (binder == null) { return null; } return MethodBodySemanticModel.Create(this, symbol, new MethodBodySemanticModel.InitialState(exprDecl, binder: binder)); } case SyntaxKind.GlobalStatement: { var parent = node.Parent; // TODO (tomat): handle misplaced global statements if (parent.Kind() == SyntaxKind.CompilationUnit && !this.IsRegularCSharp && (object)_compilation.ScriptClass != null) { var scriptInitializer = _compilation.ScriptClass.GetScriptInitializer(); Debug.Assert((object)scriptInitializer != null); if ((object)scriptInitializer == null) { return null; } // Share labels across all global statements. if (_globalStatementLabels == null) { Interlocked.CompareExchange(ref _globalStatementLabels, new ScriptLocalScopeBinder.Labels(scriptInitializer, (CompilationUnitSyntax)parent), null); } return MethodBodySemanticModel.Create( this, scriptInitializer, new MethodBodySemanticModel.InitialState(node, binder: new ExecutableCodeBinder(node, scriptInitializer, new ScriptLocalScopeBinder(_globalStatementLabels, defaultOuter())))); } } break; case SyntaxKind.Attribute: return CreateModelForAttribute(defaultOuter(), (AttributeSyntax)node, containingModel: null); } return null; MemberSemanticModel createMethodBodySemanticModel(CSharpSyntaxNode memberDecl, SourceMemberMethodSymbol symbol) { ExecutableCodeBinder binder = symbol?.TryGetBodyBinder(_binderFactory, this.IgnoresAccessibility); if (binder == null) { return null; } return MethodBodySemanticModel.Create(this, symbol, new MethodBodySemanticModel.InitialState(memberDecl, binder: binder)); } } private SynthesizedRecordConstructor TryGetSynthesizedRecordConstructor(RecordDeclarationSyntax node) { NamedTypeSymbol recordType = GetDeclaredType(node); var symbol = recordType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().SingleOrDefault(); if (symbol?.SyntaxRef.SyntaxTree != node.SyntaxTree || symbol.GetSyntax() != node) { return null; } return symbol; } private AttributeSemanticModel CreateModelForAttribute(Binder enclosingBinder, AttributeSyntax attribute, MemberSemanticModel containingModel) { AliasSymbol aliasOpt; var attributeType = (NamedTypeSymbol)enclosingBinder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type; return AttributeSemanticModel.Create( this, attribute, attributeType, aliasOpt, enclosingBinder.WithAdditionalFlags(BinderFlags.AttributeArgument), containingModel?.GetRemappedSymbols()); } private FieldSymbol GetDeclaredFieldSymbol(VariableDeclaratorSyntax variableDecl) { var declaredSymbol = GetDeclaredSymbol(variableDecl); if ((object)declaredSymbol != null) { switch (variableDecl.Parent.Parent.Kind()) { case SyntaxKind.FieldDeclaration: return declaredSymbol.GetSymbol<FieldSymbol>(); case SyntaxKind.EventFieldDeclaration: return (declaredSymbol.GetSymbol<EventSymbol>()).AssociatedField; } } return null; } private Binder GetFieldOrPropertyInitializerBinder(FieldSymbol symbol, Binder outer, EqualsValueClauseSyntax initializer) { // NOTE: checking for a containing script class is sufficient, but the regular C# test is quick and easy. outer = outer.GetFieldInitializerBinder(symbol, suppressBinderFlagsFieldInitializer: !this.IsRegularCSharp && symbol.ContainingType.IsScriptClass); if (initializer != null) { outer = new ExecutableCodeBinder(initializer, symbol, outer); } return outer; } private static bool IsMemberDeclaration(CSharpSyntaxNode node) { return (node is MemberDeclarationSyntax) || (node is AccessorDeclarationSyntax) || (node.Kind() == SyntaxKind.Attribute) || (node.Kind() == SyntaxKind.Parameter); } private bool IsRegularCSharp { get { return this.SyntaxTree.Options.Kind == SourceCodeKind.Regular; } } #region "GetDeclaredSymbol overloads for MemberDeclarationSyntax and its subtypes" /// <inheritdoc/> public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); } /// <inheritdoc/> public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default) { CheckSyntaxNode(declarationSyntax); return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); } private NamespaceSymbol GetDeclaredNamespace(BaseNamespaceDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); NamespaceOrTypeSymbol container; if (declarationSyntax.Parent.Kind() == SyntaxKind.CompilationUnit) { container = _compilation.Assembly.GlobalNamespace; } else { container = GetDeclaredNamespaceOrType(declarationSyntax.Parent); } Debug.Assert((object)container != null); // We should get a namespace symbol since we match the symbol location with a namespace declaration syntax location. var symbol = (NamespaceSymbol)GetDeclaredMember(container, declarationSyntax.Span, declarationSyntax.Name); Debug.Assert((object)symbol != null); // Map to compilation-scoped namespace (Roslyn bug 9538) symbol = _compilation.GetCompilationNamespace(symbol); Debug.Assert((object)symbol != null); return symbol; } /// <summary> /// Given a type declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a type.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseTypeDeclarationSyntax as all of them return a NamedTypeSymbol. /// </remarks> public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredType(declarationSyntax).GetPublicSymbol(); } /// <summary> /// Given a delegate declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a delegate.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredType(declarationSyntax).GetPublicSymbol(); } private NamedTypeSymbol GetDeclaredType(BaseTypeDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); var name = declarationSyntax.Identifier.ValueText; return GetDeclaredNamedType(declarationSyntax, name); } private NamedTypeSymbol GetDeclaredType(DelegateDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); var name = declarationSyntax.Identifier.ValueText; return GetDeclaredNamedType(declarationSyntax, name); } private NamedTypeSymbol GetDeclaredNamedType(CSharpSyntaxNode declarationSyntax, string name) { Debug.Assert(declarationSyntax != null); var container = GetDeclaredTypeMemberContainer(declarationSyntax); Debug.Assert((object)container != null); // try cast as we might get a non-type in error recovery scenarios: return GetDeclaredMember(container, declarationSyntax.Span, name) as NamedTypeSymbol; } private NamespaceOrTypeSymbol GetDeclaredNamespaceOrType(CSharpSyntaxNode declarationSyntax) { var namespaceDeclarationSyntax = declarationSyntax as BaseNamespaceDeclarationSyntax; if (namespaceDeclarationSyntax != null) { return GetDeclaredNamespace(namespaceDeclarationSyntax); } var typeDeclarationSyntax = declarationSyntax as BaseTypeDeclarationSyntax; if (typeDeclarationSyntax != null) { return GetDeclaredType(typeDeclarationSyntax); } var delegateDeclarationSyntax = declarationSyntax as DelegateDeclarationSyntax; if (delegateDeclarationSyntax != null) { return GetDeclaredType(delegateDeclarationSyntax); } return null; } /// <summary> /// Given a member declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for following subtypes of MemberDeclarationSyntax: /// NOTE: (1) GlobalStatementSyntax as they don't declare any symbols. /// NOTE: (2) IncompleteMemberSyntax as there are no symbols for incomplete members. /// NOTE: (3) BaseFieldDeclarationSyntax or its subtypes as these declarations can contain multiple variable declarators. /// NOTE: GetDeclaredSymbol should be called on the variable declarators directly. /// </remarks> public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); switch (declarationSyntax.Kind()) { // Few subtypes of MemberDeclarationSyntax don't declare any symbols or declare multiple symbols, return null for these cases. case SyntaxKind.GlobalStatement: // Global statements don't declare anything, even though they inherit from MemberDeclarationSyntax. return null; case SyntaxKind.IncompleteMember: // Incomplete members don't declare any symbols. return null; case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FieldDeclaration: // these declarations can contain multiple variable declarators. GetDeclaredSymbol should be called on them directly. return null; default: return (GetDeclaredNamespaceOrType(declarationSyntax) ?? GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } } public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default) { CheckSyntaxNode(declarationSyntax); return SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, declarationSyntax, fallbackToMainEntryPoint: false).GetPublicSymbol(); } /// <summary> /// Given a local function declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return this.GetMemberModel(declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a enum member declaration, get the corresponding field symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an enum member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((FieldSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a base method declaration syntax, get the corresponding method symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a method.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseMethodDeclarationSyntax as all of them return a MethodSymbol. /// </remarks> public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((MethodSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } #region "GetDeclaredSymbol overloads for BasePropertyDeclarationSyntax and its subtypes" /// <summary> /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return GetDeclaredMemberSymbol(declarationSyntax).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares a property, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares an indexer, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an indexer.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares a (custom) event, get the corresponding event symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((EventSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } #endregion #endregion /// <summary> /// Given a syntax node that declares a property or member accessor, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an accessor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Kind() == SyntaxKind.UnknownAccessorDeclaration) { // this is not a real accessor, so we shouldn't return anything. return null; } var propertyOrEventDecl = declarationSyntax.Parent.Parent; switch (propertyOrEventDecl.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: // NOTE: it's an error for field-like events to have accessors, // but we want to bind them anyway for error tolerance reasons. var container = GetDeclaredTypeMemberContainer(propertyOrEventDecl); Debug.Assert((object)container != null); Debug.Assert(declarationSyntax.Keyword.Kind() != SyntaxKind.IdentifierToken); return (this.GetDeclaredMember(container, declarationSyntax.Span) as MethodSymbol).GetPublicSymbol(); default: throw ExceptionUtilities.UnexpectedValue(propertyOrEventDecl.Kind()); } } public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var containingMemberSyntax = declarationSyntax.Parent; NamespaceOrTypeSymbol container; switch (containingMemberSyntax.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: container = GetDeclaredTypeMemberContainer(containingMemberSyntax); Debug.Assert((object)container != null); // We are looking for the SourcePropertyAccessorSymbol here, // not the SourcePropertySymbol, so use declarationSyntax // to exclude the property symbol from being retrieved. return (this.GetDeclaredMember(container, declarationSyntax.Span) as MethodSymbol).GetPublicSymbol(); default: // Don't throw, use only for the assert ExceptionUtilities.UnexpectedValue(containingMemberSyntax.Kind()); return null; } } private string GetDeclarationName(CSharpSyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: { var methodDecl = (MethodDeclarationSyntax)declaration; return GetDeclarationName(declaration, methodDecl.ExplicitInterfaceSpecifier, methodDecl.Identifier.ValueText); } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)declaration; return GetDeclarationName(declaration, propertyDecl.ExplicitInterfaceSpecifier, propertyDecl.Identifier.ValueText); } case SyntaxKind.IndexerDeclaration: { var indexerDecl = (IndexerDeclarationSyntax)declaration; return GetDeclarationName(declaration, indexerDecl.ExplicitInterfaceSpecifier, WellKnownMemberNames.Indexer); } case SyntaxKind.EventDeclaration: { var eventDecl = (EventDeclarationSyntax)declaration; return GetDeclarationName(declaration, eventDecl.ExplicitInterfaceSpecifier, eventDecl.Identifier.ValueText); } case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: return ((BaseTypeDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Identifier.ValueText; case SyntaxKind.EnumMemberDeclaration: return ((EnumMemberDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.DestructorDeclaration: return WellKnownMemberNames.DestructorName; case SyntaxKind.ConstructorDeclaration: if (((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword)) { return WellKnownMemberNames.StaticConstructorName; } else { return WellKnownMemberNames.InstanceConstructorName; } case SyntaxKind.OperatorDeclaration: { var operatorDecl = (OperatorDeclarationSyntax)declaration; return GetDeclarationName(declaration, operatorDecl.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDecl)); } case SyntaxKind.ConversionOperatorDeclaration: { var operatorDecl = (ConversionOperatorDeclarationSyntax)declaration; return GetDeclarationName(declaration, operatorDecl.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDecl)); } case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FieldDeclaration: throw new ArgumentException(CSharpResources.InvalidGetDeclarationNameMultipleDeclarators); case SyntaxKind.IncompleteMember: // There is no name - that's why it's an incomplete member. return null; default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind()); } } private string GetDeclarationName(CSharpSyntaxNode declaration, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string memberName) { if (explicitInterfaceSpecifierOpt == null) { return memberName; } // For an explicit interface implementation, we actually have several options: // Option 1: do nothing - it will retry without the name // Option 2: detect explicit impl and return null // Option 3: get a binder and figure out the name // For now, we're going with Option 3 return ExplicitInterfaceHelpers.GetMemberName(_binderFactory.GetBinder(declaration), explicitInterfaceSpecifierOpt, memberName); } private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: case SyntaxKind.IdentifierName: return GetDeclaredMember(container, declarationSpan, ((SimpleNameSyntax)name).Identifier.ValueText); case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)name; var left = GetDeclaredMember(container, declarationSpan, qn.Left) as NamespaceOrTypeSymbol; Debug.Assert((object)left != null); return GetDeclaredMember(left, declarationSpan, qn.Right); case SyntaxKind.AliasQualifiedName: // this is not supposed to happen, but we allow for errors don't we! var an = (AliasQualifiedNameSyntax)name; return GetDeclaredMember(container, declarationSpan, an.Name); default: throw ExceptionUtilities.UnexpectedValue(name.Kind()); } } /// <summary> /// Finds the member in the containing symbol which is inside the given declaration span. /// </summary> private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, string name = null) { if ((object)container == null) { return null; } // look for any member with same declaration location var collection = name != null ? container.GetMembers(name) : container.GetMembersUnordered(); Symbol zeroWidthMatch = null; foreach (var symbol in collection) { var namedType = symbol as ImplicitNamedTypeSymbol; if ((object)namedType != null && namedType.IsImplicitClass) { // look inside wrapper around illegally placed members in namespaces var result = GetDeclaredMember(namedType, declarationSpan, name); if ((object)result != null) { return result; } } foreach (var loc in symbol.Locations) { if (loc.IsInSource && loc.SourceTree == this.SyntaxTree && declarationSpan.Contains(loc.SourceSpan)) { if (loc.SourceSpan.IsEmpty && loc.SourceSpan.End == declarationSpan.Start) { // exclude decls created via syntax recovery zeroWidthMatch = symbol; } else { return symbol; } } } // Handle the case of the implementation of a partial method. var partial = symbol.Kind == SymbolKind.Method ? ((MethodSymbol)symbol).PartialImplementationPart : null; if ((object)partial != null) { var loc = partial.Locations[0]; if (loc.IsInSource && loc.SourceTree == this.SyntaxTree && declarationSpan.Contains(loc.SourceSpan)) { return partial; } } } // If we didn't find anything better than the symbol that matched because of syntax error recovery, then return that. // Otherwise, if there's a name, try again without a name. // Otherwise, give up. return zeroWidthMatch ?? (name != null ? GetDeclaredMember(container, declarationSpan) : null); } /// <summary> /// Given a variable declarator syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a variable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var field = declarationSyntax.Parent == null ? null : declarationSyntax.Parent.Parent as BaseFieldDeclarationSyntax; if (field != null) { var container = GetDeclaredTypeMemberContainer(field); Debug.Assert((object)container != null); var result = this.GetDeclaredMember(container, declarationSyntax.Span, declarationSyntax.Identifier.ValueText); Debug.Assert((object)result != null); return result.GetPublicSymbol(); } // Might be a local variable. var memberModel = this.GetMemberModel(declarationSyntax); return memberModel?.GetDeclaredSymbol(declarationSyntax, cancellationToken); } public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { // Might be a local variable. var memberModel = this.GetMemberModel(declarationSyntax); ISymbol local = memberModel?.GetDeclaredSymbol(declarationSyntax, cancellationToken); if (local != null) { return local; } // Might be a field Binder binder = GetEnclosingBinder(declarationSyntax.Position); return binder?.LookupDeclaredField(declarationSyntax).GetPublicSymbol(); } internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol originalSymbol) { var position = originalSymbol.IdentifierToken.SpanStart; return GetMemberModel(position)?.GetAdjustedLocalSymbol(originalSymbol) ?? originalSymbol; } /// <summary> /// Given a labeled statement syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the labeled statement.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var memberModel = this.GetMemberModel(declarationSyntax); return memberModel == null ? null : memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a switch label syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the switch label.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var memberModel = this.GetMemberModel(declarationSyntax); return memberModel == null ? null : memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a using declaration get the corresponding symbol for the using alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared.</returns> /// <remarks> /// If the using directive is an error because it attempts to introduce an alias for which an existing alias was /// previously declared in the same scope, the result is a newly-constructed AliasSymbol (i.e. not one from the /// symbol table). /// </remarks> public override IAliasSymbol GetDeclaredSymbol( UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Alias == null) { return null; } Binder binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); for (; binder != null; binder = binder.Next) { var usingAliases = binder.UsingAliases; if (!usingAliases.IsDefault) { foreach (var alias in usingAliases) { if (alias.Alias.Locations[0].SourceSpan == declarationSyntax.Alias.Name.Span) { return alias.Alias.GetPublicSymbol(); } } break; } } return null; } /// <summary> /// Given an extern alias declaration get the corresponding symbol for the alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared, or null if a duplicate alias symbol was declared.</returns> public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); for (; binder != null; binder = binder.Next) { var externAliases = binder.ExternAliases; if (!externAliases.IsDefault) { foreach (var alias in externAliases) { if (alias.Alias.Locations[0].SourceSpan == declarationSyntax.Identifier.Span) { return alias.Alias.GetPublicSymbol(); } } break; } } return null; } /// <summary> /// Given a base field declaration syntax, get the corresponding symbols. /// </summary> /// <param name="declarationSyntax">The syntax node that declares one or more fields or events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The field symbols that were declared.</returns> internal override ImmutableArray<ISymbol> GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var builder = new ArrayBuilder<ISymbol>(); foreach (var declarator in declarationSyntax.Declaration.Variables) { var field = this.GetDeclaredSymbol(declarator, cancellationToken) as ISymbol; if (field != null) { builder.Add(field); } } return builder.ToImmutableAndFree(); } private ParameterSymbol GetMethodParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as ParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as MemberDeclarationSyntax; if (memberDecl == null) { return null; } MethodSymbol method; if (memberDecl is RecordDeclarationSyntax recordDecl && recordDecl.ParameterList == paramList) { method = TryGetSynthesizedRecordConstructor(recordDecl); } else { method = (GetDeclaredSymbol(memberDecl, cancellationToken) as IMethodSymbol).GetSymbol(); } if ((object)method == null) { return null; } return GetParameterSymbol(method.Parameters, parameter, cancellationToken) ?? ((object)method.PartialDefinitionPart == null ? null : GetParameterSymbol(method.PartialDefinitionPart.Parameters, parameter, cancellationToken)); } private ParameterSymbol GetIndexerParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as BracketedParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as MemberDeclarationSyntax; if (memberDecl == null) { return null; } var property = (GetDeclaredSymbol(memberDecl, cancellationToken) as IPropertySymbol).GetSymbol(); if ((object)property == null) { return null; } return GetParameterSymbol(property.Parameters, parameter, cancellationToken); } private ParameterSymbol GetDelegateParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as ParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as DelegateDeclarationSyntax; if (memberDecl == null) { return null; } var delegateType = (GetDeclaredSymbol(memberDecl, cancellationToken) as INamedTypeSymbol).GetSymbol(); if ((object)delegateType == null) { return null; } var delegateInvoke = delegateType.DelegateInvokeMethod; if ((object)delegateInvoke == null || delegateInvoke.HasUseSiteError) { return null; } return GetParameterSymbol(delegateInvoke.Parameters, parameter, cancellationToken); } /// <summary> /// Given a parameter declaration syntax node, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a parameter.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The parameter that was declared.</returns> public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); MemberSemanticModel memberModel = this.GetMemberModel(declarationSyntax); if (memberModel != null) { // Could be parameter of lambda. return memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } return GetDeclaredNonLambdaParameterSymbol(declarationSyntax, cancellationToken).GetPublicSymbol(); } private ParameterSymbol GetDeclaredNonLambdaParameterSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return GetMethodParameterSymbol(declarationSyntax, cancellationToken) ?? GetIndexerParameterSymbol(declarationSyntax, cancellationToken) ?? GetDelegateParameterSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a type parameter declaration (field or method), get the corresponding symbol /// </summary> /// <param name="typeParameter"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)) { if (typeParameter == null) { throw new ArgumentNullException(nameof(typeParameter)); } if (!IsInTree(typeParameter)) { throw new ArgumentException("typeParameter not within tree"); } if (typeParameter.Parent is TypeParameterListSyntax typeParamList) { ISymbol parameterizedSymbol = null; switch (typeParamList.Parent) { case MemberDeclarationSyntax memberDecl: parameterizedSymbol = GetDeclaredSymbol(memberDecl, cancellationToken); break; case LocalFunctionStatementSyntax localDecl: parameterizedSymbol = GetDeclaredSymbol(localDecl, cancellationToken); break; default: throw ExceptionUtilities.UnexpectedValue(typeParameter.Parent.Kind()); } switch (parameterizedSymbol.GetSymbol()) { case NamedTypeSymbol typeSymbol: return this.GetTypeParameterSymbol(typeSymbol.TypeParameters, typeParameter).GetPublicSymbol(); case MethodSymbol methodSymbol: return (this.GetTypeParameterSymbol(methodSymbol.TypeParameters, typeParameter) ?? ((object)methodSymbol.PartialDefinitionPart == null ? null : this.GetTypeParameterSymbol(methodSymbol.PartialDefinitionPart.TypeParameters, typeParameter))).GetPublicSymbol(); } } return null; } private TypeParameterSymbol GetTypeParameterSymbol(ImmutableArray<TypeParameterSymbol> parameters, TypeParameterSyntax parameter) { foreach (var symbol in parameters) { foreach (var location in symbol.Locations) { if (location.SourceTree == this.SyntaxTree && parameter.Span.Contains(location.SourceSpan)) { return symbol; } } } return null; } public override ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { ValidateStatementRange(firstStatement, lastStatement); var context = RegionAnalysisContext(firstStatement, lastStatement); var result = new CSharpControlFlowAnalysis(context); return result; } private void ValidateStatementRange(StatementSyntax firstStatement, StatementSyntax lastStatement) { if (firstStatement == null) { throw new ArgumentNullException(nameof(firstStatement)); } if (lastStatement == null) { throw new ArgumentNullException(nameof(lastStatement)); } if (!IsInTree(firstStatement)) { throw new ArgumentException("statements not within tree"); } // Global statements don't have their parent in common, but should belong to the same compilation unit bool isGlobalStatement = firstStatement.Parent is GlobalStatementSyntax; if (isGlobalStatement && (lastStatement.Parent is not GlobalStatementSyntax || firstStatement.Parent.Parent != lastStatement.Parent.Parent)) { throw new ArgumentException("global statements not within the same compilation unit"); } // Non-global statements, the parents should be the same if (!isGlobalStatement && (firstStatement.Parent == null || firstStatement.Parent != lastStatement.Parent)) { throw new ArgumentException("statements not within the same statement list"); } if (firstStatement.SpanStart > lastStatement.SpanStart) { throw new ArgumentException("first statement does not precede last statement"); } } public override DataFlowAnalysis AnalyzeDataFlow(ExpressionSyntax expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (!IsInTree(expression)) { throw new ArgumentException("expression not within tree"); } var context = RegionAnalysisContext(expression); var result = new CSharpDataFlowAnalysis(context); return result; } public override DataFlowAnalysis AnalyzeDataFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { ValidateStatementRange(firstStatement, lastStatement); var context = RegionAnalysisContext(firstStatement, lastStatement); var result = new CSharpDataFlowAnalysis(context); return result; } private static BoundNode GetBoundRoot(MemberSemanticModel memberModel, out Symbol member) { member = memberModel.MemberSymbol; return memberModel.GetBoundRoot(); } private NamespaceOrTypeSymbol GetDeclaredTypeMemberContainer(CSharpSyntaxNode memberDeclaration) { if (memberDeclaration.Parent.Kind() == SyntaxKind.CompilationUnit) { // top-level namespace: if (memberDeclaration.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration) { return _compilation.Assembly.GlobalNamespace; } // top-level members in script or interactive code: if (this.SyntaxTree.Options.Kind != SourceCodeKind.Regular) { return this.Compilation.ScriptClass; } // top-level type in an explicitly declared namespace: if (SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) { return _compilation.Assembly.GlobalNamespace; } // other top-level members: return _compilation.Assembly.GlobalNamespace.ImplicitType; } var container = GetDeclaredNamespaceOrType(memberDeclaration.Parent); Debug.Assert((object)container != null); // member in a type: if (!container.IsNamespace) { return container; } // a namespace or a type in an explicitly declared namespace: if (memberDeclaration.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) { return container; } // another member in a namespace: return ((NamespaceSymbol)container).ImplicitType; } private Symbol GetDeclaredMemberSymbol(CSharpSyntaxNode declarationSyntax) { CheckSyntaxNode(declarationSyntax); var container = GetDeclaredTypeMemberContainer(declarationSyntax); var name = GetDeclarationName(declarationSyntax); return this.GetDeclaredMember(container, declarationSyntax.Span, name); } public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(AwaitExpressionInfo) : memberModel.GetAwaitExpressionInfo(node); } public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node); } public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node); } public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel?.GetDeconstructionInfo(node) ?? default; } public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel?.GetDeconstructionInfo(node) ?? default; } internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol) { Debug.Assert(symbol is LocalSymbol or ParameterSymbol or MethodSymbol { MethodKind: MethodKind.LambdaMethod }); if (symbol.Locations.IsDefaultOrEmpty) { return symbol; } var location = symbol.Locations[0]; // The symbol may be from a distinct syntax tree - perhaps the // symbol was returned from LookupSymbols() for instance. if (location.SourceTree != this.SyntaxTree) { return symbol; } var position = CheckAndAdjustPosition(location.SourceSpan.Start); var memberModel = GetMemberModel(position); return memberModel?.RemapSymbolIfNecessaryCore(symbol) ?? symbol; } internal override Func<SyntaxNode, bool> GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) { switch (declaredNode) { case CompilationUnitSyntax unit when SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, unit, fallbackToMainEntryPoint: false) is SynthesizedSimpleProgramEntryPointSymbol entryPoint: switch (declaredSymbol.Kind) { case SymbolKind.Namespace: Debug.Assert(((INamespaceSymbol)declaredSymbol).IsGlobalNamespace); // Do not include top level global statements into a global namespace return (node) => node.Kind() != SyntaxKind.GlobalStatement || node.Parent != unit; case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)entryPoint); // Include only global statements at the top level return (node) => node.Parent != unit || node.Kind() == SyntaxKind.GlobalStatement; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)entryPoint.ContainingSymbol); return (node) => false; default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } break; case RecordDeclarationSyntax recordDeclaration when TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor ctor: if (recordDeclaration.IsKind(SyntaxKind.RecordDeclaration)) { switch (declaredSymbol.Kind) { case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor); return (node) => { // Accept only nodes that either match, or above/below of a 'parameter list'/'base arguments list'. if (node.Parent == recordDeclaration) { return node == recordDeclaration.ParameterList || node == recordDeclaration.BaseList; } else if (node.Parent is BaseListSyntax baseList) { return node == recordDeclaration.PrimaryConstructorBaseTypeIfClass; } else if (node.Parent is PrimaryConstructorBaseTypeSyntax baseType && baseType == recordDeclaration.PrimaryConstructorBaseTypeIfClass) { return node == baseType.ArgumentList; } return true; }; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor.ContainingSymbol); // Accept nodes that do not match a 'parameter list'/'base arguments list'. return (node) => node != recordDeclaration.ParameterList && !(node.Kind() == SyntaxKind.ArgumentList && node == recordDeclaration.PrimaryConstructorBaseTypeIfClass?.ArgumentList); default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } } else { switch (declaredSymbol.Kind) { case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor); return (node) => { // Accept only nodes that either match, or above/below of a 'parameter list'. if (node.Parent == recordDeclaration) { return node == recordDeclaration.ParameterList; } return true; }; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor.ContainingSymbol); // Accept nodes that do not match a 'parameter list'. return (node) => node != recordDeclaration.ParameterList; default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } } break; case PrimaryConstructorBaseTypeSyntax { Parent: BaseListSyntax { Parent: RecordDeclarationSyntax recordDeclaration } } baseType when recordDeclaration.PrimaryConstructorBaseTypeIfClass == declaredNode && TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor ctor: if ((object)declaredSymbol.GetSymbol() == (object)ctor) { // Only 'base arguments list' or nodes below it return (node) => node != baseType.Type; } break; case ParameterSyntax param when declaredSymbol.Kind == SymbolKind.Property && param.Parent?.Parent is RecordDeclarationSyntax recordDeclaration && recordDeclaration.ParameterList == param.Parent: Debug.Assert(declaredSymbol.GetSymbol() is SynthesizedRecordPropertySymbol); return (node) => false; } return null; } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/WithBlockTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class WithBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterWithStatement() VerifyStatementEndConstructApplied( before:="Class c1 Sub goo() With variable End Sub End Class", beforeCaret:={2, -1}, after:="Class c1 Sub goo() With variable End With End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyForMatchedWith() VerifyStatementEndConstructNotApplied( text:="Class c1 Sub goo() With variable End With End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNestedWith() VerifyStatementEndConstructApplied( before:="Class C Sub S With K With K End With End Sub End Class", beforeCaret:={3, -1}, after:="Class C Sub S With K With K End With End With End Sub End Class", afterCaret:={4, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyWithFollowsCode() VerifyStatementEndConstructApplied( before:="Class C Sub S With K Dim x = 5 End Sub End Class", beforeCaret:={2, -1}, after:="Class C Sub S With K End With Dim x = 5 End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidWithSyntax() VerifyStatementEndConstructNotApplied( text:="Class EC Sub S With using End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidWithLocation() VerifyStatementEndConstructNotApplied( text:="Class EC With True End Class", caret:={1, -1}) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class WithBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub ApplyAfterWithStatement() VerifyStatementEndConstructApplied( before:="Class c1 Sub goo() With variable End Sub End Class", beforeCaret:={2, -1}, after:="Class c1 Sub goo() With variable End With End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyForMatchedWith() VerifyStatementEndConstructNotApplied( text:="Class c1 Sub goo() With variable End With End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNestedWith() VerifyStatementEndConstructApplied( before:="Class C Sub S With K With K End With End Sub End Class", beforeCaret:={3, -1}, after:="Class C Sub S With K With K End With End With End Sub End Class", afterCaret:={4, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyWithFollowsCode() VerifyStatementEndConstructApplied( before:="Class C Sub S With K Dim x = 5 End Sub End Class", beforeCaret:={2, -1}, after:="Class C Sub S With K End With Dim x = 5 End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidWithSyntax() VerifyStatementEndConstructNotApplied( text:="Class EC Sub S With using End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidWithLocation() VerifyStatementEndConstructNotApplied( text:="Class EC With True End Class", caret:={1, -1}) End Sub End Class End Namespace
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Features/Core/Portable/GenerateMember/GenerateEnumMember/AbstractGenerateEnumMemberService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember { internal abstract partial class AbstractGenerateEnumMemberService<TService, TSimpleNameSyntax, TExpressionSyntax> { private partial class State { // public TypeDeclarationSyntax ContainingTypeDeclaration { get; private set; } public INamedTypeSymbol TypeToGenerateIn { get; private set; } // Just the name of the method. i.e. "Goo" in "Goo" or "X.Goo" public SyntaxToken IdentifierToken { get; private set; } public TSimpleNameSyntax SimpleName { get; private set; } public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; private set; } public static async Task<State> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { if (service.IsIdentifierNameGeneration(node)) { if (!TryInitializeIdentifierName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { return false; } } else { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a field. In // the latter case, we want to generate a field *unless* there's an existing member // with the same name. Note: it's ok if there's an existing field with the same // name. var existingMembers = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText); if (existingMembers.Any()) { // TODO: Code coverage There was an existing member that the new member would // clash with. return false; } cancellationToken.ThrowIfCancellationRequested(); TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (!ValidateTypeToGenerateIn(TypeToGenerateIn, true, EnumType)) { return false; } return CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken); } private bool TryInitializeIdentifierName( TService service, SemanticDocument semanticDocument, TSimpleNameSyntax identifierName, CancellationToken cancellationToken) { SimpleName = identifierName; if (!service.TryInitializeIdentifierNameState(semanticDocument, identifierName, cancellationToken, out var identifierToken, out var simpleNameOrMemberAccessExpression)) { return false; } IdentifierToken = identifierToken; SimpleNameOrMemberAccessExpression = simpleNameOrMemberAccessExpression; var semanticModel = semanticDocument.SemanticModel; var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); if (semanticFacts.IsWrittenTo(semanticModel, SimpleNameOrMemberAccessExpression, cancellationToken) || syntaxFacts.IsInNamespaceOrTypeContext(SimpleNameOrMemberAccessExpression)) { return false; } // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and // binds uniquely, then we don't need to offer this quick fix. cancellationToken.ThrowIfCancellationRequested(); var containingType = semanticModel.GetEnclosingNamedType(identifierToken.SpanStart, cancellationToken); if (containingType == null) { return false; } var semanticInfo = semanticModel.GetSymbolInfo(SimpleNameOrMemberAccessExpression, cancellationToken); if (cancellationToken.IsCancellationRequested) { return false; } if (semanticInfo.Symbol != null) { return false; } // Either we found no matches, or this was ambiguous. Either way, we might be able // to generate a method here. Determine where the user wants to generate the method // into, and if it's valid then proceed. if (!TryDetermineTypeToGenerateIn( semanticDocument, containingType, simpleNameOrMemberAccessExpression, cancellationToken, out var typeToGenerateIn, out var isStatic)) { return false; } if (!isStatic) { return false; } TypeToGenerateIn = typeToGenerateIn; 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateEnumMember { internal abstract partial class AbstractGenerateEnumMemberService<TService, TSimpleNameSyntax, TExpressionSyntax> { private partial class State { // public TypeDeclarationSyntax ContainingTypeDeclaration { get; private set; } public INamedTypeSymbol TypeToGenerateIn { get; private set; } // Just the name of the method. i.e. "Goo" in "Goo" or "X.Goo" public SyntaxToken IdentifierToken { get; private set; } public TSimpleNameSyntax SimpleName { get; private set; } public TExpressionSyntax SimpleNameOrMemberAccessExpression { get; private set; } public static async Task<State> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { if (service.IsIdentifierNameGeneration(node)) { if (!TryInitializeIdentifierName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { return false; } } else { return false; } // Ok. It either didn't bind to any symbols, or it bound to a symbol but with // errors. In the former case we definitely want to offer to generate a field. In // the latter case, we want to generate a field *unless* there's an existing member // with the same name. Note: it's ok if there's an existing field with the same // name. var existingMembers = TypeToGenerateIn.GetMembers(IdentifierToken.ValueText); if (existingMembers.Any()) { // TODO: Code coverage There was an existing member that the new member would // clash with. return false; } cancellationToken.ThrowIfCancellationRequested(); TypeToGenerateIn = await SymbolFinder.FindSourceDefinitionAsync(TypeToGenerateIn, document.Project.Solution, cancellationToken).ConfigureAwait(false) as INamedTypeSymbol; if (!ValidateTypeToGenerateIn(TypeToGenerateIn, true, EnumType)) { return false; } return CodeGenerator.CanAdd(document.Project.Solution, TypeToGenerateIn, cancellationToken); } private bool TryInitializeIdentifierName( TService service, SemanticDocument semanticDocument, TSimpleNameSyntax identifierName, CancellationToken cancellationToken) { SimpleName = identifierName; if (!service.TryInitializeIdentifierNameState(semanticDocument, identifierName, cancellationToken, out var identifierToken, out var simpleNameOrMemberAccessExpression)) { return false; } IdentifierToken = identifierToken; SimpleNameOrMemberAccessExpression = simpleNameOrMemberAccessExpression; var semanticModel = semanticDocument.SemanticModel; var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); var syntaxFacts = semanticDocument.Document.GetLanguageService<ISyntaxFactsService>(); if (semanticFacts.IsWrittenTo(semanticModel, SimpleNameOrMemberAccessExpression, cancellationToken) || syntaxFacts.IsInNamespaceOrTypeContext(SimpleNameOrMemberAccessExpression)) { return false; } // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and // binds uniquely, then we don't need to offer this quick fix. cancellationToken.ThrowIfCancellationRequested(); var containingType = semanticModel.GetEnclosingNamedType(identifierToken.SpanStart, cancellationToken); if (containingType == null) { return false; } var semanticInfo = semanticModel.GetSymbolInfo(SimpleNameOrMemberAccessExpression, cancellationToken); if (cancellationToken.IsCancellationRequested) { return false; } if (semanticInfo.Symbol != null) { return false; } // Either we found no matches, or this was ambiguous. Either way, we might be able // to generate a method here. Determine where the user wants to generate the method // into, and if it's valid then proceed. if (!TryDetermineTypeToGenerateIn( semanticDocument, containingType, simpleNameOrMemberAccessExpression, cancellationToken, out var typeToGenerateIn, out var isStatic)) { return false; } if (!isStatic) { return false; } TypeToGenerateIn = typeToGenerateIn; return true; } } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/EditorFeatures/Test2/NavigationBar/CSharpNavigationBarTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar <[UseExportProvider]> Partial Public Class CSharpNavigationBarTests <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545021")> Public Async Function TestGenericTypeVariance(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[interface C<in I, out O> { }]]></Document> </Project> </Workspace>, host, Item("C<in I, out O>", Glyph.InterfaceInternal, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545284, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545284")> Public Async Function TestGenericMember(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[class Program { static void Swap<T>(T lhs, T rhs) { }}]]></Document> </Project> </Workspace>, host, Item("Program", Glyph.ClassInternal, children:={ Item("Swap<T>(T lhs, T rhs)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545023")> Public Async Function TestNestedClasses(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { class Nested { } }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={}), Item("C.Nested", Glyph.ClassPrivate, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545023")> Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { class Nested { $$ } }</Document> </Project> </Workspace>, host, Item("C.Nested", Glyph.ClassPrivate), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545019")> Public Async Function TestSelectedItemForEnumAfterComma(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>enum E { A,$$ B }</Document> </Project> </Workspace>, host, Item("E", Glyph.EnumInternal), False, Item("A", Glyph.EnumMemberPublic), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestSelectedItemForFieldAfterSemicolon(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { int goo;$$ }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestSelectedItemForFieldInType(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { in$$t goo; }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545267")> Public Async Function TestSelectedItemAtEndOfFile(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { int goo; } $$</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), True, Item("goo", Glyph.FieldPrivate), True) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545012")> Public Async Function TestExplicitInterfaceImplementation(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class C : IDisposable { void IDisposable.Dispose() { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("IDisposable.Dispose()", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545007")> Public Async Function TestRefAndOutParameters(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(out string goo, ref string bar) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(out string goo, ref string bar)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545001")> Public Async Function TestOptionalParameter(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(int i = 0) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(int i = 0)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestOptionalParameter2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(CancellationToken cancellationToken = default)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545274")> Public Async Function TestProperties(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { private int Number { get; set; } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("Number", Glyph.PropertyPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestEnum(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum Goo { A, B, C } </Document> </Project> </Workspace>, host, Item("Goo", Glyph.EnumInternal, children:={ Item("A", Glyph.EnumMemberPublic), Item("B", Glyph.EnumMemberPublic), Item("C", Glyph.EnumMemberPublic)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestDelegate(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void Goo(); </Document> </Project> </Workspace>, host, Item("Goo", Glyph.DelegateInternal, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestPartialClassWithFieldInOtherFile(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$ }</Document> <Document>partial class C { int goo; }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate, grayed:=True), True) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothPartialMethodParts1(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$partial void M(); }</Document> <Document>partial class C { partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPrivate), Item("M()", Glyph.MethodPrivate, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothPartialMethodParts2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { partial void M(); }</Document> <Document>partial class C { $$partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPrivate), Item("M()", Glyph.MethodPrivate, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothExtendedPartialMethodParts1(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$public partial void M(); }</Document> <Document>partial class C { public partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPublic), Item("M()", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothExtendedPartialMethodParts2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { public partial void M(); }</Document> <Document>partial class C { $$public partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPublic), Item("M()", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37183, "https://github.com/dotnet/roslyn/issues/37183")> Public Async Function TestNullableReferenceTypesInParameters(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>#nullable enable using System.Collections.Generic; class C { void M(string? s, IEnumerable&lt;string?&gt; e) { }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(string? s, IEnumerable<string?> e)", Glyph.MethodPrivate)})) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar <[UseExportProvider]> Partial Public Class CSharpNavigationBarTests <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545021")> Public Async Function TestGenericTypeVariance(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[interface C<in I, out O> { }]]></Document> </Project> </Workspace>, host, Item("C<in I, out O>", Glyph.InterfaceInternal, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545284, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545284")> Public Async Function TestGenericMember(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[class Program { static void Swap<T>(T lhs, T rhs) { }}]]></Document> </Project> </Workspace>, host, Item("Program", Glyph.ClassInternal, children:={ Item("Swap<T>(T lhs, T rhs)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545023")> Public Async Function TestNestedClasses(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { class Nested { } }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={}), Item("C.Nested", Glyph.ClassPrivate, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545023")> Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { class Nested { $$ } }</Document> </Project> </Workspace>, host, Item("C.Nested", Glyph.ClassPrivate), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545019")> Public Async Function TestSelectedItemForEnumAfterComma(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>enum E { A,$$ B }</Document> </Project> </Workspace>, host, Item("E", Glyph.EnumInternal), False, Item("A", Glyph.EnumMemberPublic), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestSelectedItemForFieldAfterSemicolon(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { int goo;$$ }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestSelectedItemForFieldInType(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { in$$t goo; }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545267")> Public Async Function TestSelectedItemAtEndOfFile(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { int goo; } $$</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), True, Item("goo", Glyph.FieldPrivate), True) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545012")> Public Async Function TestExplicitInterfaceImplementation(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class C : IDisposable { void IDisposable.Dispose() { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("IDisposable.Dispose()", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545007")> Public Async Function TestRefAndOutParameters(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(out string goo, ref string bar) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(out string goo, ref string bar)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545001")> Public Async Function TestOptionalParameter(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(int i = 0) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(int i = 0)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestOptionalParameter2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(CancellationToken cancellationToken = default)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545274")> Public Async Function TestProperties(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { private int Number { get; set; } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("Number", Glyph.PropertyPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestEnum(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum Goo { A, B, C } </Document> </Project> </Workspace>, host, Item("Goo", Glyph.EnumInternal, children:={ Item("A", Glyph.EnumMemberPublic), Item("B", Glyph.EnumMemberPublic), Item("C", Glyph.EnumMemberPublic)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestDelegate(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void Goo(); </Document> </Project> </Workspace>, host, Item("Goo", Glyph.DelegateInternal, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestPartialClassWithFieldInOtherFile(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$ }</Document> <Document>partial class C { int goo; }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate, grayed:=True), True) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothPartialMethodParts1(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$partial void M(); }</Document> <Document>partial class C { partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPrivate), Item("M()", Glyph.MethodPrivate, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothPartialMethodParts2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { partial void M(); }</Document> <Document>partial class C { $$partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPrivate), Item("M()", Glyph.MethodPrivate, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothExtendedPartialMethodParts1(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$public partial void M(); }</Document> <Document>partial class C { public partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPublic), Item("M()", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothExtendedPartialMethodParts2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { public partial void M(); }</Document> <Document>partial class C { $$public partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPublic), Item("M()", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37183, "https://github.com/dotnet/roslyn/issues/37183")> Public Async Function TestNullableReferenceTypesInParameters(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>#nullable enable using System.Collections.Generic; class C { void M(string? s, IEnumerable&lt;string?&gt; e) { }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(string? s, IEnumerable<string?> e)", Glyph.MethodPrivate)})) End Function End Class End Namespace
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Workspaces/Core/Portable/ExternalAccess/Pythia/Api/PythiaSemanticModelExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal static class PythiaSemanticModelExtensions { public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => SemanticModelExtensions.GetEnclosingNamedTypeOrAssembly(semanticModel, position, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal static class PythiaSemanticModelExtensions { public static ISymbol GetEnclosingNamedTypeOrAssembly(this SemanticModel semanticModel, int position, CancellationToken cancellationToken) => SemanticModelExtensions.GetEnclosingNamedTypeOrAssembly(semanticModel, position, cancellationToken); } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/VisualBasic/Portable/Semantics/TypeInference/TypeArgumentInference.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The only public entry point is the Infer method. ''' </summary> Friend MustInherit Class TypeArgumentInference Public Shared Function Infer( candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, ByRef typeArguments As ImmutableArray(Of TypeSymbol), ByRef inferenceLevel As InferenceLevel, ByRef allFailedInferenceIsDueToObject As Boolean, ByRef someInferenceFailed As Boolean, ByRef inferenceErrorReasons As InferenceErrorReasons, <Out> ByRef inferredTypeByAssumption As BitVector, <Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken), <[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), ByRef diagnostic As BindingDiagnosticBag, Optional inferTheseTypeParameters As BitVector = Nothing ) As Boolean Debug.Assert(candidate Is candidate.ConstructedFrom) Return InferenceGraph.Infer(candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode, typeArguments, inferenceLevel, allFailedInferenceIsDueToObject, someInferenceFailed, inferenceErrorReasons, inferredTypeByAssumption, typeArgumentsLocation, asyncLambdaSubToFunctionMismatch, useSiteInfo, diagnostic, inferTheseTypeParameters) End Function ' No-one should create instances of this class. Private Sub New() End Sub Public Enum InferenceLevel As Byte None = 0 ' None is used to indicate uninitialized but semantically it should not matter if there is a whidbey delegate ' or no delegate in the overload resolution hence both have value 0 such that overload resolution ' will not prefer a non inferred method over an inferred one. Whidbey = 0 Orcas = 1 ' Keep invalid the biggest number Invalid = 2 End Enum ' MatchGenericArgumentParameter: ' This is used in type inference, when matching an argument e.g. Arg(Of String) against a parameter Parm(Of T). ' In covariant contexts e.g. Action(Of _), the two match if Arg <= Parm (i.e. Arg inherits/implements Parm). ' In contravariant contexts e.g. IEnumerable(Of _), the two match if Parm <= Arg (i.e. Parm inherits/implements Arg). ' In invariant contexts e.g. List(Of _), the two match only if Arg and Parm are identical. ' Note: remember that rank-1 arrays T() implement IEnumerable(Of T), IList(Of T) and ICollection(Of T). Public Enum MatchGenericArgumentToParameter MatchBaseOfGenericArgumentToParameter MatchArgumentToBaseOfGenericParameter MatchGenericArgumentToParameterExactly End Enum Private Enum InferenceNodeType As Byte ArgumentNode TypeParameterNode End Enum Private MustInherit Class InferenceNode Inherits GraphNode(Of InferenceNode) Public ReadOnly NodeType As InferenceNodeType Public InferenceComplete As Boolean Protected Sub New(graph As InferenceGraph, nodeType As InferenceNodeType) MyBase.New(graph) Me.NodeType = nodeType End Sub Public Shadows ReadOnly Property Graph As InferenceGraph Get Return DirectCast(MyBase.Graph, InferenceGraph) End Get End Property ''' <summary> ''' Returns True if the inference algorithm should be restarted. ''' </summary> Public MustOverride Function InferTypeAndPropagateHints() As Boolean <Conditional("DEBUG")> Public Sub VerifyIncomingInferenceComplete( ByVal nodeType As InferenceNodeType ) If Not Graph.SomeInferenceHasFailed() Then For Each current As InferenceNode In IncomingEdges Debug.Assert(current.NodeType = nodeType, "Should only have expected incoming edges.") Debug.Assert(current.InferenceComplete, "Should have inferred type already") Next End If End Sub End Class Private Class DominantTypeDataTypeInference Inherits DominantTypeData ' Fields needed for error reporting Public ByAssumption As Boolean ' was ResultType chosen by assumption or intention? Public Parameter As ParameterSymbol Public InferredFromObject As Boolean Public TypeParameter As TypeParameterSymbol Public ArgumentLocation As SyntaxNode End Class Private Class TypeParameterNode Inherits InferenceNode Public ReadOnly DeclaredTypeParam As TypeParameterSymbol Public ReadOnly InferenceTypeCollection As TypeInferenceCollection(Of DominantTypeDataTypeInference) Private _inferredType As TypeSymbol Private _inferredFromLocation As SyntaxNodeOrToken Private _inferredTypeByAssumption As Boolean ' TODO: Dev10 has two locations to track type inferred so far. ' One that can be changed with time and the other one that cannot be changed. ' This one, cannot be changed once set. We need to clean this up later. Private _candidateInferredType As TypeSymbol Private _parameter As ParameterSymbol Public Sub New(graph As InferenceGraph, typeParameter As TypeParameterSymbol) MyBase.New(graph, InferenceNodeType.TypeParameterNode) DeclaredTypeParam = typeParameter InferenceTypeCollection = New TypeInferenceCollection(Of DominantTypeDataTypeInference)() End Sub Public ReadOnly Property InferredType As TypeSymbol Get Return _inferredType End Get End Property Public ReadOnly Property CandidateInferredType As TypeSymbol Get Return _candidateInferredType End Get End Property Public ReadOnly Property InferredFromLocation As SyntaxNodeOrToken Get Return _inferredFromLocation End Get End Property Public ReadOnly Property InferredTypeByAssumption As Boolean Get Return _inferredTypeByAssumption End Get End Property Public Sub RegisterInferredType(inferredType As TypeSymbol, inferredFromLocation As SyntaxNodeOrToken, inferredTypeByAssumption As Boolean) ' Make sure ArrayLiteralTypeSymbol does not leak out Dim arrayLiteralType = TryCast(inferredType, ArrayLiteralTypeSymbol) If arrayLiteralType IsNot Nothing Then Dim arrayLiteral = arrayLiteralType.ArrayLiteral Dim arrayType = arrayLiteral.InferredType If Not (arrayLiteral.HasDominantType AndAlso arrayLiteral.NumberOfCandidates = 1) AndAlso arrayType.ElementType.SpecialType = SpecialType.System_Object Then ' ReportArrayLiteralInferredTypeDiagnostics in ReclassifyArrayLiteralExpression reports an error ' when option strict is on and the array type is object() and there wasn't a dominant type. However, ' Dev10 does not report this error when inferring a type parameter's type. Create a new object() type ' to suppress the error. inferredType = ArrayTypeSymbol.CreateVBArray(arrayType.ElementType, Nothing, arrayType.Rank, arrayLiteral.Binder.Compilation.Assembly) Else inferredType = arrayLiteral.InferredType End If End If Debug.Assert(Not (TypeOf inferredType Is ArrayLiteralTypeSymbol)) _inferredType = inferredType _inferredFromLocation = inferredFromLocation _inferredTypeByAssumption = inferredTypeByAssumption ' TODO: Dev10 has two locations to track type inferred so far. ' One that can be changed with time and the other one that cannot be changed. ' We need to clean this up. If _candidateInferredType Is Nothing Then _candidateInferredType = inferredType End If End Sub Public ReadOnly Property Parameter As ParameterSymbol Get Return _parameter End Get End Property Public Sub SetParameter(parameter As ParameterSymbol) Debug.Assert(_parameter Is Nothing) _parameter = parameter End Sub Public Overrides Function InferTypeAndPropagateHints() As Boolean Dim numberOfIncomingEdges As Integer = IncomingEdges.Count Dim restartAlgorithm As Boolean = False Dim argumentLocation As SyntaxNode Dim numberOfIncomingWithNothing As Integer = 0 If numberOfIncomingEdges > 0 Then argumentLocation = DirectCast(IncomingEdges(0), ArgumentNode).Expression.Syntax Else argumentLocation = Nothing End If Dim numberOfAssertions As Integer = 0 Dim incomingFromObject As Boolean = False Dim list As ArrayBuilder(Of InferenceNode) = IncomingEdges For Each currentGraphNode As InferenceNode In IncomingEdges Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.ArgumentNode, "Should only have named nodes as incoming edges.") Dim currentNamedNode = DirectCast(currentGraphNode, ArgumentNode) If currentNamedNode.Expression.Type IsNot Nothing AndAlso currentNamedNode.Expression.Type.IsObjectType() Then incomingFromObject = True End If If Not currentNamedNode.InferenceComplete Then Graph.RemoveEdge(currentNamedNode, Me) restartAlgorithm = True numberOfAssertions += 1 Else ' We should not infer from a Nothing literal. If currentNamedNode.Expression.IsStrictNothingLiteral() Then numberOfIncomingWithNothing += 1 End If End If Next If numberOfIncomingEdges > 0 AndAlso numberOfIncomingEdges = numberOfIncomingWithNothing Then ' !! Inference has failed: All incoming type hints, were based on 'Nothing' Graph.MarkInferenceFailure() Graph.ReportNotFailedInferenceDueToObject() End If Dim numberOfTypeHints As Integer = InferenceTypeCollection.GetTypeDataList().Count() If numberOfTypeHints = 0 Then If numberOfAssertions = numberOfIncomingEdges Then Graph.MarkInferenceLevel(InferenceLevel.Orcas) Else ' !! Inference has failed. No Type hints, and some, not all were assertions, otherwise we would have picked object for strict. RegisterInferredType(Nothing, Nothing, False) Graph.MarkInferenceFailure() If Not incomingFromObject Then Graph.ReportNotFailedInferenceDueToObject() End If End If ElseIf numberOfTypeHints = 1 Then Dim typeData As DominantTypeDataTypeInference = InferenceTypeCollection.GetTypeDataList()(0) If argumentLocation Is Nothing AndAlso typeData.ArgumentLocation IsNot Nothing Then argumentLocation = typeData.ArgumentLocation End If RegisterInferredType(typeData.ResultType, argumentLocation, typeData.ByAssumption) Else ' Run the whidbey algorithm to see if we are smarter now. Dim firstInferredType As TypeSymbol = Nothing Dim allTypeData As ArrayBuilder(Of DominantTypeDataTypeInference) = InferenceTypeCollection.GetTypeDataList() For Each currentTypeInfo As DominantTypeDataTypeInference In allTypeData If firstInferredType Is Nothing Then firstInferredType = currentTypeInfo.ResultType ElseIf Not firstInferredType.IsSameTypeIgnoringAll(currentTypeInfo.ResultType) Then ' Whidbey failed hard here, in Orcas we added dominant type information. Graph.MarkInferenceLevel(InferenceLevel.Orcas) End If Next Dim dominantTypeDataList = ArrayBuilder(Of DominantTypeDataTypeInference).GetInstance() Dim errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other InferenceTypeCollection.FindDominantType(dominantTypeDataList, errorReasons, Graph.UseSiteInfo) If dominantTypeDataList.Count = 1 Then ' //consider: scottwis ' // This seems dangerous to me, that we ' // remove error reasons here. ' // Instead of clearing these, what we should be doing is ' // asserting that they are not set. ' // If for some reason they get set, but ' // we enter this path, then we have a bug. ' // This code is just masking any such bugs. errorReasons = errorReasons And (Not (InferenceErrorReasons.Ambiguous Or InferenceErrorReasons.NoBest)) Dim typeData As DominantTypeDataTypeInference = dominantTypeDataList(0) RegisterInferredType(typeData.ResultType, typeData.ArgumentLocation, typeData.ByAssumption) ' // Also update the location of the argument for constraint error reporting later on. Else If (errorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then ' !! Inference has failed. Dominant type algorithm found ambiguous types. Graph.ReportAmbiguousInferenceError(dominantTypeDataList) Else ' //consider: scottwis ' // This code appears to be operating under the assumption that if the error reason is not due to an ' // ambiguity then it must be because there was no best match. ' // We should be asserting here to verify that assertion. ' !! Inference has failed. Dominant type algorithm could not find a dominant type. Graph.ReportIncompatibleInferenceError(allTypeData) End If RegisterInferredType(allTypeData(0).ResultType, argumentLocation, False) Graph.MarkInferenceFailure() End If Graph.RegisterErrorReasons(errorReasons) dominantTypeDataList.Free() End If InferenceComplete = True Return restartAlgorithm End Function Public Sub AddTypeHint( type As TypeSymbol, typeByAssumption As Boolean, argumentLocation As SyntaxNode, parameter As ParameterSymbol, inferredFromObject As Boolean, inferenceRestrictions As RequiredConversion ) Debug.Assert(Not typeByAssumption OrElse type.IsObjectType() OrElse TypeOf type Is ArrayLiteralTypeSymbol, "unexpected: a type which was 'by assumption', but isn't object or array literal") ' Don't add error types to the type argument inference collection. If type.IsErrorType Then Return End If Dim foundInList As Boolean = False ' Do not merge array literals with other expressions If TypeOf type IsNot ArrayLiteralTypeSymbol Then For Each competitor As DominantTypeDataTypeInference In InferenceTypeCollection.GetTypeDataList() ' Do not merge array literals with other expressions If TypeOf competitor.ResultType IsNot ArrayLiteralTypeSymbol AndAlso type.IsSameTypeIgnoringAll(competitor.ResultType) Then competitor.ResultType = TypeInferenceCollection.MergeTupleNames(competitor.ResultType, type) competitor.InferenceRestrictions = Conversions.CombineConversionRequirements( competitor.InferenceRestrictions, inferenceRestrictions) competitor.ByAssumption = competitor.ByAssumption AndAlso typeByAssumption Debug.Assert(Not foundInList, "List is supposed to be unique: how can we already find two of the same type in this list.") foundInList = True ' TODO: Should we simply exit the loop for RELEASE build? End If Next End If If Not foundInList Then Dim typeData As DominantTypeDataTypeInference = New DominantTypeDataTypeInference() typeData.ResultType = type typeData.ByAssumption = typeByAssumption typeData.InferenceRestrictions = inferenceRestrictions typeData.ArgumentLocation = argumentLocation typeData.Parameter = parameter typeData.InferredFromObject = inferredFromObject typeData.TypeParameter = DeclaredTypeParam InferenceTypeCollection.GetTypeDataList().Add(typeData) End If End Sub End Class Private Class ArgumentNode Inherits InferenceNode Public ReadOnly ParameterType As TypeSymbol Public ReadOnly Expression As BoundExpression Public ReadOnly Parameter As ParameterSymbol Public Sub New(graph As InferenceGraph, expression As BoundExpression, parameterType As TypeSymbol, parameter As ParameterSymbol) MyBase.New(graph, InferenceNodeType.ArgumentNode) Me.Expression = expression Me.ParameterType = parameterType Me.Parameter = parameter End Sub Public Overrides Function InferTypeAndPropagateHints() As Boolean #If DEBUG Then VerifyIncomingInferenceComplete(InferenceNodeType.TypeParameterNode) #End If ' Check if all incoming are ok, otherwise skip inference. For Each currentGraphNode As InferenceNode In IncomingEdges Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.TypeParameterNode, "Should only have typed nodes as incoming edges.") Dim currentTypedNode As TypeParameterNode = DirectCast(currentGraphNode, TypeParameterNode) If currentTypedNode.InferredType Is Nothing Then Dim skipThisNode As Boolean = True If Expression.Kind = BoundKind.UnboundLambda AndAlso ParameterType.IsDelegateType() Then ' Check here if we need to infer Object for some of the parameters of the Lambda if we weren't able ' to infer these otherwise. This is only the case for arguments of the lambda that have a GenericParam ' of the method we are inferring that is not yet inferred. ' Now find the invoke method of the delegate Dim delegateType = DirectCast(ParameterType, NamedTypeSymbol) Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod IsNot Nothing AndAlso invokeMethod.GetUseSiteInfo().DiagnosticInfo Is Nothing Then Dim unboundLambda = DirectCast(Expression, UnboundLambda) Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) = unboundLambda.Parameters Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters For i As Integer = 0 To Math.Min(lambdaParameters.Length, delegateParameters.Length) - 1 Step 1 Dim lambdaParameter = DirectCast(lambdaParameters(i), UnboundLambdaParameterSymbol) Dim delegateParam As ParameterSymbol = delegateParameters(i) If lambdaParameter.Type Is Nothing AndAlso delegateParam.Type.Equals(currentTypedNode.DeclaredTypeParam) Then If Graph.Diagnostic Is Nothing Then Graph.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Graph.UseSiteInfo.AccumulatesDependencies) End If ' If this was an argument to the unbound Lambda, infer Object. If Graph.ObjectType Is Nothing Then Debug.Assert(Graph.Diagnostic IsNot Nothing) Graph.ObjectType = unboundLambda.Binder.GetSpecialType(SpecialType.System_Object, lambdaParameter.IdentifierSyntax, Graph.Diagnostic) End If currentTypedNode.RegisterInferredType(Graph.ObjectType, lambdaParameter.TypeSyntax, currentTypedNode.InferredTypeByAssumption) ' ' Port SP1 CL 2941063 to VS10 ' Bug 153317 ' Report an error if Option Strict On or a warning if Option Strict Off ' because we have no hints about the lambda parameter ' and we are assuming that it is an object. ' e.g. "Sub f(Of T, U)(ByVal x As Func(Of T, U))" invoked with "f(function(z)z)" ' needs to put the squiggly on the first "z". Debug.Assert(Graph.Diagnostic IsNot Nothing) unboundLambda.Binder.ReportLambdaParameterInferredToBeObject(lambdaParameter, Graph.Diagnostic) skipThisNode = False Exit For End If Next End If End If If skipThisNode Then InferenceComplete = True Return False ' DOn't restart the algorithm. End If End If Next Dim argumentType As TypeSymbol = Nothing Dim inferenceOk As Boolean = False Select Case Expression.Kind Case BoundKind.AddressOfOperator inferenceOk = Graph.InferTypeArgumentsFromAddressOfArgument( Expression, ParameterType, Parameter) Case BoundKind.LateAddressOfOperator ' We can not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference ' as not failed due to object. Graph.ReportNotFailedInferenceDueToObject() inferenceOk = True Case BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda, BoundKind.UnboundLambda ' TODO: Not sure if this is applicable to Roslyn, need to try this out when all required features are available. ' BUG: 131359 If the lambda is wrapped in a delegate constructor the resultType ' will be set and not be Void. In this case the lambda argument should be treated as a regular ' argument so fall through in this case. Debug.Assert(Expression.Type Is Nothing) ' TODO: We are setting inference level before ' even trying to infer something from the lambda. It is possible ' that we won't infer anything, should consider changing the ' inference level after. Graph.MarkInferenceLevel(InferenceLevel.Orcas) inferenceOk = Graph.InferTypeArgumentsFromLambdaArgument( Expression, ParameterType, Parameter) Case Else HandleAsAGeneralExpression: ' We should not infer from a Nothing literal. If Expression.IsStrictNothingLiteral() Then InferenceComplete = True ' continue without restarting, if all hints are Nothing the InferenceTypeNode will mark ' the inference as failed. Return False End If Dim inferenceRestrictions As RequiredConversion = RequiredConversion.Any If Parameter IsNot Nothing AndAlso Parameter.IsByRef AndAlso (Expression.IsLValue() OrElse Expression.IsPropertySupportingAssignment()) Then ' A ByRef parameter needs (if the argument was an lvalue) to be copy-backable into ' that argument. Debug.Assert(inferenceRestrictions = RequiredConversion.Any, "there should have been no prior restrictions by the time we encountered ByRef") inferenceRestrictions = Conversions.CombineConversionRequirements( inferenceRestrictions, Conversions.InvertConversionRequirement(inferenceRestrictions)) Debug.Assert(inferenceRestrictions = RequiredConversion.AnyAndReverse, "expected ByRef to require AnyAndReverseConversion") End If Dim arrayLiteral As BoundArrayLiteral = Nothing Dim argumentTypeByAssumption As Boolean = False Dim expressionType As TypeSymbol If Expression.Kind = BoundKind.ArrayLiteral Then arrayLiteral = DirectCast(Expression, BoundArrayLiteral) argumentTypeByAssumption = arrayLiteral.NumberOfCandidates <> 1 expressionType = New ArrayLiteralTypeSymbol(arrayLiteral) ElseIf Expression.Kind = BoundKind.TupleLiteral Then expressionType = DirectCast(Expression, BoundTupleLiteral).InferredType Else expressionType = Expression.Type End If ' Need to create an ArrayLiteralTypeSymbol inferenceOk = Graph.InferTypeArgumentsFromArgument( Expression.Syntax, expressionType, argumentTypeByAssumption, ParameterType, Parameter, MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions) End Select If Not inferenceOk Then ' !! Inference has failed. Mismatch of Argument and Parameter signature, so could not find type hints. Graph.MarkInferenceFailure() If Not (Expression.Type IsNot Nothing AndAlso Expression.Type.IsObjectType()) Then Graph.ReportNotFailedInferenceDueToObject() End If End If InferenceComplete = True Return False ' // Don't restart the algorithm; End Function End Class Private Class InferenceGraph Inherits Graph(Of InferenceNode) Public Diagnostic As BindingDiagnosticBag Public ObjectType As NamedTypeSymbol Public ReadOnly Candidate As MethodSymbol Public ReadOnly Arguments As ImmutableArray(Of BoundExpression) Public ReadOnly ParameterToArgumentMap As ArrayBuilder(Of Integer) Public ReadOnly ParamArrayItems As ArrayBuilder(Of Integer) Public ReadOnly DelegateReturnType As TypeSymbol Public ReadOnly DelegateReturnTypeReferenceBoundNode As BoundNode Public UseSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) Private _someInferenceFailed As Boolean Private _inferenceErrorReasons As InferenceErrorReasons Private _allFailedInferenceIsDueToObject As Boolean = True ' remains true until proven otherwise. Private _typeInferenceLevel As InferenceLevel = InferenceLevel.None Private _asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) Private ReadOnly _typeParameterNodes As ImmutableArray(Of TypeParameterNode) Private ReadOnly _verifyingAssertions As Boolean Private Sub New( diagnostic As BindingDiagnosticBag, candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(delegateReturnType Is Nothing OrElse delegateReturnTypeReferenceBoundNode IsNot Nothing) Me.Diagnostic = diagnostic Me.Candidate = candidate Me.Arguments = arguments Me.ParameterToArgumentMap = parameterToArgumentMap Me.ParamArrayItems = paramArrayItems Me.DelegateReturnType = delegateReturnType Me.DelegateReturnTypeReferenceBoundNode = delegateReturnTypeReferenceBoundNode Me._asyncLambdaSubToFunctionMismatch = asyncLambdaSubToFunctionMismatch Me.UseSiteInfo = useSiteInfo ' Allocate the array of TypeParameter nodes. Dim arity As Integer = candidate.Arity Dim typeParameterNodes(arity - 1) As TypeParameterNode For i As Integer = 0 To arity - 1 Step 1 typeParameterNodes(i) = New TypeParameterNode(Me, candidate.TypeParameters(i)) Next _typeParameterNodes = typeParameterNodes.AsImmutableOrNull() End Sub Public ReadOnly Property SomeInferenceHasFailed As Boolean Get Return _someInferenceFailed End Get End Property Public Sub MarkInferenceFailure() _someInferenceFailed = True End Sub Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean Get Return _allFailedInferenceIsDueToObject End Get End Property Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons Get Return _inferenceErrorReasons End Get End Property Public Sub ReportNotFailedInferenceDueToObject() _allFailedInferenceIsDueToObject = False End Sub Public ReadOnly Property TypeInferenceLevel As InferenceLevel Get Return _typeInferenceLevel End Get End Property Public Sub MarkInferenceLevel(typeInferenceLevel As InferenceLevel) If _typeInferenceLevel < typeInferenceLevel Then _typeInferenceLevel = typeInferenceLevel End If End Sub Public Shared Function Infer( candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, ByRef typeArguments As ImmutableArray(Of TypeSymbol), ByRef inferenceLevel As InferenceLevel, ByRef allFailedInferenceIsDueToObject As Boolean, ByRef someInferenceFailed As Boolean, ByRef inferenceErrorReasons As InferenceErrorReasons, <Out> ByRef inferredTypeByAssumption As BitVector, <Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken), <[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), ByRef diagnostic As BindingDiagnosticBag, inferTheseTypeParameters As BitVector ) As Boolean Dim graph As New InferenceGraph(diagnostic, candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode, asyncLambdaSubToFunctionMismatch, useSiteInfo) ' Build a graph describing the flow of type inference data. ' This creates edges from "regular" arguments to type parameters and from type parameters to lambda arguments. ' In the rest of this function that graph is then processed (see below for more details). Essentially, for each ' "type parameter" node a list of "type hints" (possible candidates for type inference) is collected. The dominant ' type algorithm is then performed over the list of hints associated with each node. ' ' The process of populating the graph also seeds type hints for type parameters referenced by explicitly typed ' lambda parameters. Also, hints sometimes have restrictions placed on them that limit what conversions the dominant type ' algorithm can consider when it processes them. The restrictions are generally driven by the context in which type ' parameters are used. For example if a type parameter is used as a type parameter of another type (something like IGoo(of T)), ' then the dominant type algorithm is not allowed to consider any conversions. There are similar restrictions for ' Array co-variance. graph.PopulateGraph() Dim topoSortedGraph = ArrayBuilder(Of StronglyConnectedComponent(Of InferenceNode)).GetInstance() ' This is the restart point of the algorithm Do Dim restartAlgorithm As Boolean = False Dim stronglyConnectedComponents As Graph(Of StronglyConnectedComponent(Of InferenceNode)) = graph.BuildStronglyConnectedComponents() topoSortedGraph.Clear() stronglyConnectedComponents.TopoSort(topoSortedGraph) ' We now iterate over the topologically-sorted strongly connected components of the graph, and generate ' type hints as appropriate. ' ' When we find a node for an argument (or an ArgumentNode as it's referred to in the code), we infer ' types for all type parameters referenced by that argument and then propagate those types as hints ' to the referenced type parameters. If there are incoming edges into the argument node, they correspond ' to parameters of lambda arguments that get their value from the delegate type that contains type ' parameters that would have been inferred during a previous iteration of the loop. Those types are ' flowed into the lambda argument. ' ' When we encounter a "type parameter" node (or TypeParameterNode as it is called in the code), we run ' the dominant type algorithm over all of it's hints and use the resulting type as the value for the ' referenced type parameter. ' ' If we find a strongly connected component with more than one node, it means we ' have a cycle and cannot simply run the inference algorithm. When this happens, ' we look through the nodes in the cycle for a type parameter node with at least ' one type hint. If we find one, we remove all incoming edges to that node, ' infer the type using its hints, and then restart the whole algorithm from the ' beginning (recompute the strongly connected components, resort them, and then ' iterate over the graph again). The source nodes of the incoming edges we ' removed are added to an "assertion list". After graph traversal is done we ' then run inference on any "assertion nodes" we may have created. For Each sccNode As StronglyConnectedComponent(Of InferenceNode) In topoSortedGraph Dim childNodes As ArrayBuilder(Of InferenceNode) = sccNode.ChildNodes ' Small optimization if one node If childNodes.Count = 1 Then If childNodes(0).InferTypeAndPropagateHints() Then ' consider: scottwis ' We should be asserting here, because this code is unreachable.. ' There are two implementations of InferTypeAndPropagateHints, ' one for "named nodes" (nodes corresponding to arguments) and another ' for "type nodes" (nodes corresponding to types). ' The implementation for "named nodes" always returns false, which means ' "don't restart the algorithm". The implementation for "type nodes" only returns true ' if a node has incoming edges that have not been visited previously. In order for that ' to happen the node must be inside a strongly connected component with more than one node ' (i.e. it must be involved in a cycle). If it wasn't we would be visiting it in ' topological order, which means all incoming edges should have already been visited. ' That means that if we reach this code, there is probably a bug in the traversal process. We ' don't want to silently mask the bug. At a minimum we should either assert or generate a compiler error. ' ' An argument could be made that it is good to have this because ' InferTypeAndPropagateHints is virtual, and should some new node type be ' added it's implementation may return true, and so this would follow that ' path. That argument does make some tiny amount of sense, and so we ' should keep this code here to make it easier to make any such ' modifications in the future. However, we still need an assert to guard ' against graph traversal bugs, and in the event that such changes are ' made, leave it to the modifier to remove the assert if necessary. Throw ExceptionUtilities.Unreachable End If Else Dim madeInferenceProgress As Boolean = False For Each child As InferenceNode In childNodes If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso DirectCast(child, TypeParameterNode).InferenceTypeCollection.GetTypeDataList().Count > 0 Then If child.InferTypeAndPropagateHints() Then ' If edges were broken, restart algorithm to recompute strongly connected components. restartAlgorithm = True End If madeInferenceProgress = True End If Next If Not madeInferenceProgress Then ' Did not make progress trying to force incoming edges for nodes with TypesHints, just inferring all now, ' will infer object if no type hints. For Each child As InferenceNode In childNodes If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso child.InferTypeAndPropagateHints() Then ' If edges were broken, restart algorithm to recompute strongly connected components. restartAlgorithm = True End If Next End If If restartAlgorithm Then Exit For ' For Each sccNode End If End If Next If restartAlgorithm Then Continue Do End If Exit Do Loop 'The commented code below is from Dev10, but it looks like 'it doesn't do anything useful because topoSortedGraph contains 'StronglyConnectedComponents, which have NodeType=None. ' 'graph.m_VerifyingAssertions = True 'GraphNodeListIterator assertionIter(&topoSortedGraph); ' While (assertionIter.MoveNext()) '{ ' GraphNode* currentNode = assertionIter.Current(); ' if (currentNode->m_NodeType == TypedNodeType) ' { ' InferenceTypeNode* currentTypeNode = (InferenceTypeNode*)currentNode; ' currentTypeNode->VerifyTypeAssertions(); ' } '} 'graph.m_VerifyingAssertions = False topoSortedGraph.Free() Dim succeeded As Boolean = Not graph.SomeInferenceHasFailed someInferenceFailed = graph.SomeInferenceHasFailed allFailedInferenceIsDueToObject = graph.AllFailedInferenceIsDueToObject inferenceErrorReasons = graph.InferenceErrorReasons ' Make sure that allFailedInferenceIsDueToObject only stays set, ' if there was an actual inference failure. If Not someInferenceFailed OrElse delegateReturnType IsNot Nothing Then allFailedInferenceIsDueToObject = False End If Dim arity As Integer = candidate.Arity Dim inferredTypes(arity - 1) As TypeSymbol Dim inferredFromLocation(arity - 1) As SyntaxNodeOrToken For i As Integer = 0 To arity - 1 Step 1 ' TODO: Should we use InferredType or CandidateInferredType here? It looks like Dev10 is using the latter, ' it might not be cleaned in case of a failure. Will use the former for now. Dim typeParameterNode = graph._typeParameterNodes(i) Dim inferredType As TypeSymbol = typeParameterNode.InferredType If inferredType Is Nothing AndAlso (inferTheseTypeParameters.IsNull OrElse inferTheseTypeParameters(i)) Then succeeded = False End If If typeParameterNode.InferredTypeByAssumption Then If inferredTypeByAssumption.IsNull Then inferredTypeByAssumption = BitVector.Create(arity) End If inferredTypeByAssumption(i) = True End If inferredTypes(i) = inferredType inferredFromLocation(i) = typeParameterNode.InferredFromLocation Next typeArguments = inferredTypes.AsImmutableOrNull() typeArgumentsLocation = inferredFromLocation.AsImmutableOrNull() inferenceLevel = graph._typeInferenceLevel Debug.Assert(diagnostic Is Nothing OrElse diagnostic Is graph.Diagnostic) diagnostic = graph.Diagnostic asyncLambdaSubToFunctionMismatch = graph._asyncLambdaSubToFunctionMismatch useSiteInfo = graph.UseSiteInfo Return succeeded End Function Private Sub PopulateGraph() Dim candidate As MethodSymbol = Me.Candidate Dim arguments As ImmutableArray(Of BoundExpression) = Me.Arguments Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Me.ParameterToArgumentMap Dim paramArrayItems As ArrayBuilder(Of Integer) = Me.ParamArrayItems Dim isExpandedParamArrayForm As Boolean = (paramArrayItems IsNot Nothing) Dim argIndex As Integer For paramIndex = 0 To candidate.ParameterCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Parameters(paramIndex) Dim targetType As TypeSymbol = param.Type If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then If targetType.Kind <> SymbolKind.ArrayType Then Continue For End If If Not isExpandedParamArrayForm Then argIndex = parameterToArgumentMap(paramIndex) Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex)) Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument) '§11.8.2 Applicable Methods 'If the conversion from the type of the argument expression to the paramarray type is narrowing, 'then the method is only applicable in its expanded form. '!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!! If paramArrayArgument Is Nothing OrElse paramArrayArgument.HasErrors OrElse Not ArgumentTypePossiblyMatchesParamarrayShape(paramArrayArgument, targetType) Then Continue For End If RegisterArgument(paramArrayArgument, targetType, param) Else Debug.Assert(isExpandedParamArrayForm) '§11.8.2 Applicable Methods 'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form. ' Note, that explicitly converted NOTHING is treated the same way by Dev10. If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() Then Continue For End If ' Otherwise, for a ParamArray parameter, all the matching arguments are passed ' ByVal as instances of the element type of the ParamArray. ' Perform the conversions to the element type of the ParamArray here. Dim arrayType = DirectCast(targetType, ArrayTypeSymbol) If Not arrayType.IsSZArray Then Continue For End If targetType = arrayType.ElementType If targetType.Kind = SymbolKind.ErrorType Then Continue For End If For j As Integer = 0 To paramArrayItems.Count - 1 Step 1 If arguments(paramArrayItems(j)).HasErrors Then Continue For End If RegisterArgument(arguments(paramArrayItems(j)), targetType, param) Next End If Continue For End If argIndex = parameterToArgumentMap(paramIndex) Dim argument = If(argIndex = -1, Nothing, arguments(argIndex)) If argument Is Nothing OrElse argument.HasErrors OrElse targetType.IsErrorType() OrElse argument.Kind = BoundKind.OmittedArgument Then Continue For End If RegisterArgument(argument, targetType, param) Next AddDelegateReturnTypeToGraph() End Sub Private Sub AddDelegateReturnTypeToGraph() If Me.DelegateReturnType IsNot Nothing AndAlso Not Me.DelegateReturnType.IsVoidType() Then Dim fakeArgument As New BoundRValuePlaceholder(Me.DelegateReturnTypeReferenceBoundNode.Syntax, Me.DelegateReturnType) Dim returnNode As New ArgumentNode(Me, fakeArgument, Me.Candidate.ReturnType, parameter:=Nothing) ' Add the edges from all the current generic parameters to this named node. For Each current As InferenceNode In Vertices If current.NodeType = InferenceNodeType.TypeParameterNode Then AddEdge(current, returnNode) End If Next ' Add the edges from the resultType outgoing to the generic parameters. AddTypeToGraph(returnNode, isOutgoingEdge:=True) End If End Sub Private Sub RegisterArgument( argument As BoundExpression, targetType As TypeSymbol, param As ParameterSymbol ) ' Dig through parenthesized. If Not argument.IsNothingLiteral Then argument = argument.GetMostEnclosedParenthesizedExpression() End If Dim argNode As New ArgumentNode(Me, argument, targetType, param) Select Case argument.Kind Case BoundKind.UnboundLambda, BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda AddLambdaToGraph(argNode, argument.GetBinderFromLambda()) Case BoundKind.AddressOfOperator AddAddressOfToGraph(argNode, DirectCast(argument, BoundAddressOfOperator).Binder) Case BoundKind.TupleLiteral AddTupleLiteralToGraph(argNode) Case Else AddTypeToGraph(argNode, isOutgoingEdge:=True) End Select End Sub Private Sub AddTypeToGraph( node As ArgumentNode, isOutgoingEdge As Boolean ) AddTypeToGraph(node.ParameterType, node, isOutgoingEdge, BitVector.Create(_typeParameterNodes.Length)) End Sub Private Function FindTypeParameterNode(typeParameter As TypeParameterSymbol) As TypeParameterNode Dim ordinal As Integer = typeParameter.Ordinal If ordinal < _typeParameterNodes.Length AndAlso _typeParameterNodes(ordinal) IsNot Nothing AndAlso typeParameter.Equals(_typeParameterNodes(ordinal).DeclaredTypeParam) Then Return _typeParameterNodes(ordinal) End If Return Nothing End Function Private Sub AddTypeToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, isOutgoingEdge As Boolean, ByRef haveSeenTypeParameters As BitVector ) Select Case parameterType.Kind Case SymbolKind.TypeParameter Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol) Dim typeParameterNode As TypeParameterNode = FindTypeParameterNode(typeParameter) If typeParameterNode IsNot Nothing AndAlso Not haveSeenTypeParameters(typeParameter.Ordinal) Then If typeParameterNode.Parameter Is Nothing Then typeParameterNode.SetParameter(argNode.Parameter) End If If (isOutgoingEdge) Then AddEdge(argNode, typeParameterNode) Else AddEdge(typeParameterNode, argNode) End If haveSeenTypeParameters(typeParameter.Ordinal) = True End If Case SymbolKind.ArrayType AddTypeToGraph(DirectCast(parameterType, ArrayTypeSymbol).ElementType, argNode, isOutgoingEdge, haveSeenTypeParameters) Case SymbolKind.NamedType Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol) Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then For Each elementType In elementTypes AddTypeToGraph(elementType, argNode, isOutgoingEdge, haveSeenTypeParameters) Next Else Do For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) AddTypeToGraph(typeArgument, argNode, isOutgoingEdge, haveSeenTypeParameters) Next possiblyGenericType = possiblyGenericType.ContainingType Loop While possiblyGenericType IsNot Nothing End If End Select End Sub Private Sub AddTupleLiteralToGraph(argNode As ArgumentNode) AddTupleLiteralToGraph(argNode.ParameterType, argNode) End Sub Private Sub AddTupleLiteralToGraph( parameterType As TypeSymbol, argNode As ArgumentNode ) Debug.Assert(argNode.Expression.Kind = BoundKind.TupleLiteral) Dim tupleLiteral = DirectCast(argNode.Expression, BoundTupleLiteral) Dim tupleArguments = tupleLiteral.Arguments If parameterType.IsTupleOrCompatibleWithTupleOfCardinality(tupleArguments.Length) Then Dim parameterElementTypes = parameterType.GetElementTypesOfTupleOrCompatible For i As Integer = 0 To tupleArguments.Length - 1 RegisterArgument(tupleArguments(i), parameterElementTypes(i), argNode.Parameter) Next Return End If AddTypeToGraph(argNode, isOutgoingEdge:=True) End Sub Private Sub AddAddressOfToGraph(argNode As ArgumentNode, binder As Binder) AddAddressOfToGraph(argNode.ParameterType, argNode, binder) End Sub Private Sub AddAddressOfToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, binder As Binder ) Debug.Assert(argNode.Expression.Kind = BoundKind.AddressOfOperator) If parameterType.IsTypeParameter() Then AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length)) ElseIf parameterType.IsDelegateType() Then Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol) Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length) AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) ' outgoing (name->type) edge haveSeenTypeParameters.Clear() For Each delegateParameter As ParameterSymbol In invoke.Parameters AddTypeToGraph(delegateParameter.Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) ' incoming (type->name) edge Next End If ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T AddAddressOfToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder) End If End Sub Private Sub AddLambdaToGraph(argNode As ArgumentNode, binder As Binder) AddLambdaToGraph(argNode.ParameterType, argNode, binder) End Sub Private Sub AddLambdaToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, binder As Binder ) If parameterType.IsTypeParameter() Then ' Lambda is bound to a generic typeParam, just infer anonymous delegate AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length)) ElseIf parameterType.IsDelegateType() Then Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol) Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invoke.Parameters Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) Select Case argNode.Expression.Kind Case BoundKind.QueryLambda lambdaParameters = DirectCast(argNode.Expression, BoundQueryLambda).LambdaSymbol.Parameters Case BoundKind.GroupTypeInferenceLambda lambdaParameters = DirectCast(argNode.Expression, GroupTypeInferenceLambda).Parameters Case BoundKind.UnboundLambda lambdaParameters = DirectCast(argNode.Expression, UnboundLambda).Parameters Case Else Throw ExceptionUtilities.UnexpectedValue(argNode.Expression.Kind) End Select Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length) For i As Integer = 0 To Math.Min(delegateParameters.Length, lambdaParameters.Length) - 1 Step 1 If lambdaParameters(i).Type IsNot Nothing Then ' Prepopulate the hint from the lambda's parameter. ' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic ' !!! parameter will be passed into the parameter of argument type. ' TODO: Consider using location for the type declaration. InferTypeArgumentsFromArgument( argNode.Expression.Syntax, lambdaParameters(i).Type, argumentTypeByAssumption:=False, parameterType:=delegateParameters(i).Type, param:=delegateParameters(i), digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, inferenceRestrictions:=RequiredConversion.Any) End If AddTypeToGraph(delegateParameters(i).Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) Next haveSeenTypeParameters.Clear() AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) End If ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T AddLambdaToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder) End If End Sub Private Shared Function ArgumentTypePossiblyMatchesParamarrayShape(argument As BoundExpression, paramType As TypeSymbol) As Boolean Dim argumentType As TypeSymbol = argument.Type Dim isArrayLiteral As Boolean = False If argumentType Is Nothing Then If argument.Kind = BoundKind.ArrayLiteral Then isArrayLiteral = True argumentType = DirectCast(argument, BoundArrayLiteral).InferredType Else Return False End If End If While paramType.IsArrayType() If Not argumentType.IsArrayType() Then Return False End If Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol) Dim paramArrayType = DirectCast(paramType, ArrayTypeSymbol) ' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches. If argumentArray.Rank <> paramArrayType.Rank OrElse (Not isArrayLiteral AndAlso argumentArray.IsSZArray <> paramArrayType.IsSZArray) Then Return False End If isArrayLiteral = False argumentType = argumentArray.ElementType paramType = paramArrayType.ElementType End While Return True End Function Public Sub RegisterTypeParameterHint( genericParameter As TypeParameterSymbol, inferredType As TypeSymbol, inferredTypeByAssumption As Boolean, argumentLocation As SyntaxNode, parameter As ParameterSymbol, inferredFromObject As Boolean, inferenceRestrictions As RequiredConversion ) Dim typeNode As TypeParameterNode = FindTypeParameterNode(genericParameter) If typeNode IsNot Nothing Then typeNode.AddTypeHint(inferredType, inferredTypeByAssumption, argumentLocation, parameter, inferredFromObject, inferenceRestrictions) End If End Sub Private Function RefersToGenericParameterToInferArgumentFor( parameterType As TypeSymbol ) As Boolean Select Case parameterType.Kind Case SymbolKind.TypeParameter Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol) Dim typeNode As TypeParameterNode = FindTypeParameterNode(typeParameter) ' TODO: It looks like this check can give us a false positive. For example, ' if we are resolving a recursive call we might already bind a type ' parameter to itself (to the same type parameter of the containing method). ' So, the fact that we ran into this type parameter doesn't necessary mean ' that there is anything to infer. I am not sure if this can lead to some ' negative effect. Dev10 appears to have the same behavior, from what I see ' in the code. If typeNode IsNot Nothing Then Return True End If Case SymbolKind.ArrayType Return RefersToGenericParameterToInferArgumentFor(DirectCast(parameterType, ArrayTypeSymbol).ElementType) Case SymbolKind.NamedType Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol) Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then For Each elementType In elementTypes If RefersToGenericParameterToInferArgumentFor(elementType) Then Return True End If Next Else Do For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If RefersToGenericParameterToInferArgumentFor(typeArgument) Then Return True End If Next possiblyGenericType = possiblyGenericType.ContainingType Loop While possiblyGenericType IsNot Nothing End If End Select Return False End Function ' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments ' to a generic method, infer type arguments corresponding to type parameters that occur ' in the parameter type. ' ' A return value of false indicates that inference fails. ' ' If a generic method is parameterized by T, an argument of type A matches a parameter of type ' P, this function tries to infer type for T by using these patterns: ' ' -- If P is T, then infer A for T ' -- If P is G(Of T) and A is G(Of X), then infer X for T ' -- If P is Array Of T, and A is Array Of X, then infer X for T ' -- If P is ByRef T, then infer A for T Private Function InferTypeArgumentsFromArgumentDirectly( argumentLocation As SyntaxNode, argumentType As TypeSymbol, argumentTypeByAssumption As Boolean, parameterType As TypeSymbol, param As ParameterSymbol, digThroughToBasesAndImplements As MatchGenericArgumentToParameter, inferenceRestrictions As RequiredConversion ) As Boolean If argumentType Is Nothing OrElse argumentType.IsVoidType() Then ' We should never be able to infer a value from something that doesn't provide a value, e.g: ' Goo(Of T) can't be passed Sub bar(), as in Goo(Bar()) Return False End If ' If a generic method is parameterized by T, an argument of type A matching a parameter of type ' P can be used to infer a type for T by these patterns: ' ' -- If P is T, then infer A for T ' -- If P is G(Of T) and A is G(Of X), then infer X for T ' -- If P is Array Of T, and A is Array Of X, then infer X for T ' -- If P is ByRef T, then infer A for T ' -- If P is (T, T) and A is (X, X), then infer X for T If parameterType.IsTypeParameter() Then RegisterTypeParameterHint( DirectCast(parameterType, TypeParameterSymbol), argumentType, argumentTypeByAssumption, argumentLocation, param, False, inferenceRestrictions) Return True End If Dim parameterElementTypes As ImmutableArray(Of TypeSymbol) = Nothing Dim argumentElementTypes As ImmutableArray(Of TypeSymbol) = Nothing If parameterType.GetNullableUnderlyingTypeOrSelf().TryGetElementTypesIfTupleOrCompatible(parameterElementTypes) AndAlso If(parameterType.IsNullableType(), argumentType.GetNullableUnderlyingTypeOrSelf(), argumentType). TryGetElementTypesIfTupleOrCompatible(argumentElementTypes) Then If parameterElementTypes.Length <> argumentElementTypes.Length Then Return False End If For typeArgumentIndex As Integer = 0 To parameterElementTypes.Length - 1 Dim parameterElementType = parameterElementTypes(typeArgumentIndex) Dim argumentElementType = argumentElementTypes(typeArgumentIndex) ' propagate restrictions to the elements If Not InferTypeArgumentsFromArgument( argumentLocation, argumentElementType, argumentTypeByAssumption, parameterElementType, param, digThroughToBasesAndImplements, inferenceRestrictions ) Then Return False End If Next Return True ElseIf parameterType.Kind = SymbolKind.NamedType Then ' e.g. handle goo(of T)(x as Bar(Of T)) We need to dig into Bar(Of T) Dim parameterTypeAsNamedType = DirectCast(parameterType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol) If parameterTypeAsNamedType.IsGenericType Then Dim argumentTypeAsNamedType = If(argumentType.Kind = SymbolKind.NamedType, DirectCast(argumentType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol), Nothing) If argumentTypeAsNamedType IsNot Nothing AndAlso argumentTypeAsNamedType.IsGenericType Then If argumentTypeAsNamedType.OriginalDefinition.IsSameTypeIgnoringAll(parameterTypeAsNamedType.OriginalDefinition) Then Do For typeArgumentIndex As Integer = 0 To parameterTypeAsNamedType.Arity - 1 Step 1 ' The following code is subtle. Let's recap what's going on... ' We've so far encountered some context, e.g. "_" or "ICovariant(_)" ' or "ByRef _" or the like. This context will have given us some TypeInferenceRestrictions. ' Now, inside the context, we've discovered a generic binding "G(Of _,_,_)" ' and we have to apply extra restrictions to each of those subcontexts. ' For non-variant parameters it's easy: the subcontexts just acquire the Identity constraint. ' For variant parameters it's more subtle. First, we have to strengthen the ' restrictions to require reference conversion (rather than just VB conversion or ' whatever it was). Second, if it was an In parameter, then we have to invert ' the sense. ' ' Processing of generics is tricky in the case that we've already encountered ' a "ByRef _". From that outer "ByRef _" we will have inferred the restriction ' "AnyConversionAndReverse", so that the argument could be copied into the parameter ' and back again. But now consider if we find a generic inside that ByRef, e.g. ' if it had been "ByRef x as G(Of T)" then what should we do? More specifically, consider a case ' "Sub f(Of T)(ByRef x as G(Of T))" invoked with some "dim arg as G(Of Hint)". ' What's needed for any candidate for T is that G(Of Hint) be convertible to ' G(Of Candidate), and vice versa for the copyback. ' ' But then what should we write down for the hints? The problem is that hints inhere ' to the generic parameter T, not to the function parameter G(Of T). So we opt for a ' safe approximation: we just require CLR identity between a candidate and the hint. ' This is safe but is a little overly-strict. For example: ' Class G(Of T) ' Public Shared Widening Operator CType(ByVal x As G(Of T)) As G(Of Animal) ' Public Shared Widening Operator CType(ByVal x As G(Of Animal)) As G(Of T) ' Sub inf(Of T)(ByRef x as G(Of T), ByVal y as T) ' ... ' inf(New G(Of Car), New Animal) ' inf(Of Animal)(New G(Of Car), New Animal) ' Then the hints will be "T:{Car=, Animal+}" and they'll result in inference-failure, ' even though the explicitly-provided T=Animal ends up working. ' ' Well, it's the best we can do without some major re-architecting of the way ' hints and type-inference works. That's because all our hints inhere to the ' type parameter T; in an ideal world, the ByRef hint would inhere to the parameter. ' But I don't think we'll ever do better than this, just because trying to do ' type inference inferring to arguments/parameters becomes exponential. ' Variance generic parameters will work the same. ' Dev10#595234: each Param'sInferenceRestriction is found as a modification of the surrounding InferenceRestriction: Dim paramInferenceRestrictions As RequiredConversion Select Case parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance Case VarianceKind.In paramInferenceRestrictions = Conversions.InvertConversionRequirement( Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions)) Case VarianceKind.Out paramInferenceRestrictions = Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions) Case Else Debug.Assert(VarianceKind.None = parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance) paramInferenceRestrictions = RequiredConversion.Identity End Select Dim _DigThroughToBasesAndImplements As MatchGenericArgumentToParameter If paramInferenceRestrictions = RequiredConversion.Reference Then _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter ElseIf paramInferenceRestrictions = RequiredConversion.ReverseReference Then _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter Else _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly End If If Not InferTypeArgumentsFromArgument( argumentLocation, argumentTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo), argumentTypeByAssumption, parameterTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo), param, _DigThroughToBasesAndImplements, paramInferenceRestrictions ) Then ' TODO: Would it make sense to continue through other type arguments even if inference failed for ' the current one? Return False End If Next ' Do not forget about type parameters of containing type parameterTypeAsNamedType = parameterTypeAsNamedType.ContainingType argumentTypeAsNamedType = argumentTypeAsNamedType.ContainingType Loop While parameterTypeAsNamedType IsNot Nothing Debug.Assert(parameterTypeAsNamedType Is Nothing AndAlso argumentTypeAsNamedType Is Nothing) Return True End If ElseIf parameterTypeAsNamedType.IsNullableType() Then ' we reach here when the ParameterType is an instantiation of Nullable, ' and the argument type is NOT a generic type. ' lwischik: ??? what do array elements have to do with nullables? Return InferTypeArgumentsFromArgument( argumentLocation, argumentType, argumentTypeByAssumption, parameterTypeAsNamedType.GetNullableUnderlyingType(), param, digThroughToBasesAndImplements, Conversions.CombineConversionRequirements(inferenceRestrictions, RequiredConversion.ArrayElement)) End If Return False End If ElseIf parameterType.IsArrayType() Then If argumentType.IsArrayType() Then Dim parameterArray = DirectCast(parameterType, ArrayTypeSymbol) Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol) Dim argumentIsAarrayLiteral = TypeOf argumentArray Is ArrayLiteralTypeSymbol ' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches. If parameterArray.Rank = argumentArray.Rank AndAlso (argumentIsAarrayLiteral OrElse parameterArray.IsSZArray = argumentArray.IsSZArray) Then Return InferTypeArgumentsFromArgument( argumentLocation, argumentArray.ElementType, argumentTypeByAssumption, parameterArray.ElementType, param, digThroughToBasesAndImplements, Conversions.CombineConversionRequirements(inferenceRestrictions, If(argumentIsAarrayLiteral, RequiredConversion.Any, RequiredConversion.ArrayElement))) End If End If Return False End If Return True End Function ' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments ' to a generic method, infer type arguments corresponding to type parameters that occur ' in the parameter type. ' ' A return value of false indicates that inference fails. ' ' This routine is given an argument e.g. "List(Of IEnumerable(Of Int))", ' and a parameter e.g. "IEnumerable(Of IEnumerable(Of T))". ' The task is to infer hints for T, e.g. "T=int". ' This function takes care of allowing (in this example) List(Of _) to match IEnumerable(Of _). ' As for the real work, i.e. matching the contents, we invoke "InferTypeArgumentsFromArgumentDirectly" ' to do that. ' ' Note: this function returns "false" if it failed to pattern-match between argument and parameter type, ' and "true" if it succeeded. ' Success in pattern-matching may or may not produce type-hints for generic parameters. ' If it happened not to produce any type-hints, then maybe other argument/parameter pairs will have produced ' their own type hints that allow inference to succeed, or maybe no-one else will have produced type hints, ' or maybe other people will have produced conflicting type hints. In those cases, we'd return True from ' here (to show success at pattern-matching) and leave the downstream code to produce an error message about ' failing to infer T. Friend Function InferTypeArgumentsFromArgument( argumentLocation As SyntaxNode, argumentType As TypeSymbol, argumentTypeByAssumption As Boolean, parameterType As TypeSymbol, param As ParameterSymbol, digThroughToBasesAndImplements As MatchGenericArgumentToParameter, inferenceRestrictions As RequiredConversion ) As Boolean If Not RefersToGenericParameterToInferArgumentFor(parameterType) Then Return True End If ' First try to the things directly. Only if this fails will we bother searching for things like List->IEnumerable. Dim Inferred As Boolean = InferTypeArgumentsFromArgumentDirectly( argumentLocation, argumentType, argumentTypeByAssumption, parameterType, param, digThroughToBasesAndImplements, inferenceRestrictions) If Inferred Then Return True End If If parameterType.IsTypeParameter() Then ' If we failed to match an argument against a generic parameter T, it means that the ' argument was something unmatchable, e.g. an AddressOf. Return False End If ' If we didn't find a direct match, we will have to look in base classes for a match. ' We'll either fix ParameterType and look amongst the bases of ArgumentType, ' or we'll fix ArgumentType and look amongst the bases of ParameterType, ' depending on the "DigThroughToBasesAndImplements" flag. This flag is affected by ' covariance and contravariance... If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly Then Return False End If ' Special handling for Anonymous Delegates. If argumentType IsNot Nothing AndAlso argumentType.IsDelegateType() AndAlso parameterType.IsDelegateType() AndAlso digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter AndAlso (inferenceRestrictions = RequiredConversion.Any OrElse inferenceRestrictions = RequiredConversion.AnyReverse OrElse inferenceRestrictions = RequiredConversion.AnyAndReverse) Then Dim argumentDelegateType = DirectCast(argumentType, NamedTypeSymbol) Dim argumentInvokeProc As MethodSymbol = argumentDelegateType.DelegateInvokeMethod Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol) Dim parameterInvokeProc As MethodSymbol = parameterDelegateType.DelegateInvokeMethod Debug.Assert(argumentInvokeProc IsNot Nothing OrElse Not argumentDelegateType.IsAnonymousType) ' Note, null check for parameterInvokeDeclaration should also filter out MultiCastDelegate type. If argumentDelegateType.IsAnonymousType AndAlso Not parameterDelegateType.IsAnonymousType AndAlso parameterInvokeProc IsNot Nothing AndAlso parameterInvokeProc.GetUseSiteInfo().DiagnosticInfo Is Nothing Then ' Some trickery relating to the fact that anonymous delegates can be converted to any delegate type. ' We are trying to match the anonymous delegate "BaseSearchType" onto the delegate "FixedType". e.g. ' Dim f = function(i as integer) i // ArgumentType = VB$AnonymousDelegate`2(Of Integer,Integer) ' inf(f) // ParameterType might be e.g. D(Of T) for some function inf(Of T)(f as D(Of T)) ' // maybe defined as Delegate Function D(Of T)(x as T) as T. ' We're looking to achieve the same functionality in pattern-matching these types as we already ' have for calling "inf(function(i as integer) i)" directly. ' It allows any VB conversion from param-of-fixed-type to param-of-base-type (not just reference conversions). ' But it does allow a zero-argument BaseSearchType to be used for a FixedType with more. ' And it does allow a function BaseSearchType to be used for a sub FixedType. ' ' Anyway, the plan is to match each of the parameters in the ArgumentType delegate ' to the equivalent parameters in the ParameterType delegate, and also match the return types. ' ' This only works for "ConversionRequired::Any", i.e. using VB conversion semantics. It doesn't work for ' reference conversions. As for the AnyReverse/AnyAndReverse, well, in Orcas that was guaranteed ' to fail type inference (i.e. return a false from this function). In Dev10 we will let it succeed ' with some inferred types, for the sake of better error messages, even though we know that ultimately ' it will fail (because no non-anonymous delegate type can be converted to a delegate type). Dim argumentParams As ImmutableArray(Of ParameterSymbol) = argumentInvokeProc.Parameters Dim parameterParams As ImmutableArray(Of ParameterSymbol) = parameterInvokeProc.Parameters If parameterParams.Length <> argumentParams.Length AndAlso argumentParams.Length <> 0 Then ' If parameter-counts are mismatched then it's a failure. ' Exception: Zero-argument relaxation: we allow a parameterless VB$AnonymousDelegate argument ' to be supplied to a function which expects a parameterfull delegate. Return False End If ' First we'll check that the argument types all match. For i As Integer = 0 To argumentParams.Length - 1 If argumentParams(i).IsByRef <> parameterParams(i).IsByRef Then ' Require an exact match between ByRef/ByVal, since that's how type inference of lambda expressions works. Return False End If If Not InferTypeArgumentsFromArgument( argumentLocation, argumentParams(i).Type, argumentTypeByAssumption, parameterParams(i).Type, param, MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, RequiredConversion.AnyReverse) Then ' AnyReverse: contravariance in delegate arguments Return False End If Next ' Now check that the return type matches. ' Note: we allow a *function* VB$AnonymousDelegate to be supplied to a function which expects a *sub* delegate. If parameterInvokeProc.IsSub Then ' A *sub* delegate parameter can accept either a *function* or a *sub* argument: Return True ElseIf argumentInvokeProc.IsSub Then ' A *function* delegate parameter cannot accept a *sub* argument. Return False Else ' Otherwise, a function argument VB$AnonymousDelegate was supplied to a function parameter: Return InferTypeArgumentsFromArgument( argumentLocation, argumentInvokeProc.ReturnType, argumentTypeByAssumption, parameterInvokeProc.ReturnType, param, MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, RequiredConversion.Any) ' Any: covariance in delegate returns End If End If End If ' MatchBaseOfGenericArgumentToParameter: used for covariant situations, ' e.g. matching argument "List(Of _)" to parameter "ByVal x as IEnumerable(Of _)". ' ' Otherwise, MatchArgumentToBaseOfGenericParameter, used for contravariant situations, ' e.g. when matching argument "Action(Of IEnumerable(Of _))" to parameter "ByVal x as Action(Of List(Of _))". Dim fContinue As Boolean = False If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter Then fContinue = FindMatchingBase(argumentType, parameterType) Else fContinue = FindMatchingBase(parameterType, argumentType) End If If Not fContinue Then Return False End If ' NOTE: baseSearchType was a REFERENCE, to either ArgumentType or ParameterType. ' Therefore the above statement has altered either ArgumentType or ParameterType. Return InferTypeArgumentsFromArgumentDirectly( argumentLocation, argumentType, argumentTypeByAssumption, parameterType, param, digThroughToBasesAndImplements, inferenceRestrictions) End Function Private Function FindMatchingBase( ByRef baseSearchType As TypeSymbol, ByRef fixedType As TypeSymbol ) As Boolean Dim fixedTypeAsNamedType = If(fixedType.Kind = SymbolKind.NamedType, DirectCast(fixedType, NamedTypeSymbol), Nothing) If fixedTypeAsNamedType Is Nothing OrElse Not fixedTypeAsNamedType.IsGenericType Then ' If the fixed candidate isn't a generic (e.g. matching argument IList(Of String) to non-generic parameter IList), ' then we won't learn anything about generic type parameters here: Return False End If Dim fixedTypeTypeKind As TypeKind = fixedType.TypeKind If fixedTypeTypeKind <> TypeKind.Class AndAlso fixedTypeTypeKind <> TypeKind.Interface Then ' Whatever "BaseSearchType" is, it can only inherit from "FixedType" if FixedType is a class/interface. ' (it's impossible to inherit from anything else). Return False End If Dim baseSearchTypeKind As SymbolKind = baseSearchType.Kind If baseSearchTypeKind <> SymbolKind.NamedType AndAlso baseSearchTypeKind <> SymbolKind.TypeParameter AndAlso Not (baseSearchTypeKind = SymbolKind.ArrayType AndAlso DirectCast(baseSearchType, ArrayTypeSymbol).IsSZArray) Then ' The things listed above are the only ones that have bases that could ever lead anywhere useful. ' NamedType is satisfied by interfaces, structures, enums, delegates and modules as well as just classes. Return False End If If baseSearchType.IsSameTypeIgnoringAll(fixedType) Then ' If the types checked were already identical, then exit Return False End If ' Otherwise, if we got through all the above tests, then it really is worth searching through the base ' types to see if that helps us find a match. Dim matchingBase As TypeSymbol = Nothing If fixedTypeTypeKind = TypeKind.Class Then FindMatchingBaseClass(baseSearchType, fixedType, matchingBase) Else Debug.Assert(fixedTypeTypeKind = TypeKind.Interface) FindMatchingBaseInterface(baseSearchType, fixedType, matchingBase) End If If matchingBase Is Nothing Then Return False End If ' And this is what we found baseSearchType = matchingBase Return True End Function Private Shared Function SetMatchIfNothingOrEqual(type As TypeSymbol, ByRef match As TypeSymbol) As Boolean If match Is Nothing Then match = type Return True ElseIf match.IsSameTypeIgnoringAll(type) Then Return True Else match = Nothing Return False End If End Function ''' <summary> ''' Returns False if the search should be cancelled. ''' </summary> Private Function FindMatchingBaseInterface(derivedType As TypeSymbol, baseInterface As TypeSymbol, ByRef match As TypeSymbol) As Boolean Select Case derivedType.Kind Case SymbolKind.TypeParameter For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(constraint, match) Then Return False End If End If If Not FindMatchingBaseInterface(constraint, baseInterface, match) Then Return False End If Next Case Else For Each [interface] In derivedType.AllInterfacesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If [interface].OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual([interface], match) Then Return False End If End If Next End Select Return True End Function ''' <summary> ''' Returns False if the search should be cancelled. ''' </summary> Private Function FindMatchingBaseClass(derivedType As TypeSymbol, baseClass As TypeSymbol, ByRef match As TypeSymbol) As Boolean Select Case derivedType.Kind Case SymbolKind.TypeParameter For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(constraint, match) Then Return False End If End If ' TODO: Do we need to continue even if we already have a matching base class? ' It looks like Dev10 continues. If Not FindMatchingBaseClass(constraint, baseClass, match) Then Return False End If Next Case Else Dim baseType As NamedTypeSymbol = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) While baseType IsNot Nothing If baseType.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(baseType, match) Then Return False End If Exit While End If baseType = baseType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) End While End Select Return True End Function Public Function InferTypeArgumentsFromAddressOfArgument( argument As BoundExpression, parameterType As TypeSymbol, param As ParameterSymbol ) As Boolean If parameterType.IsDelegateType() Then Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterType), NamedTypeSymbol) ' Now find the invoke method of the delegate Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then ' If we don't have an Invoke method, just bail. Return False End If Dim returnType As TypeSymbol = invokeMethod.ReturnType ' If the return type doesn't refer to parameters, no inference required. If Not RefersToGenericParameterToInferArgumentFor(returnType) Then Return True End If Dim addrOf = DirectCast(argument, BoundAddressOfOperator) Dim fromMethod As MethodSymbol = Nothing Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = Binder.ResolveMethodForDelegateInvokeFullAndRelaxed( addrOf, invokeMethod, ignoreMethodReturnType:=True, diagnostics:=BindingDiagnosticBag.Discarded) fromMethod = matchingMethod.Key methodConversions = matchingMethod.Value If fromMethod Is Nothing OrElse (methodConversions And MethodConversionKind.AllErrorReasons) <> 0 OrElse (addrOf.Binder.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=True)) Then Return False End If If fromMethod.IsSub Then ReportNotFailedInferenceDueToObject() Return True End If Dim targetReturnType As TypeSymbol = fromMethod.ReturnType If RefersToGenericParameterToInferArgumentFor(targetReturnType) Then ' Return false if we didn't make any inference progress. Return False End If Return InferTypeArgumentsFromArgument( argument.Syntax, targetReturnType, argumentTypeByAssumption:=False, parameterType:=returnType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) End If ' We did not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference ' as not failed due to object. ReportNotFailedInferenceDueToObject() Return True End Function Public Function InferTypeArgumentsFromLambdaArgument( argument As BoundExpression, parameterType As TypeSymbol, param As ParameterSymbol ) As Boolean Debug.Assert(argument.Kind = BoundKind.UnboundLambda OrElse argument.Kind = BoundKind.QueryLambda OrElse argument.Kind = BoundKind.GroupTypeInferenceLambda) If parameterType.IsTypeParameter() Then Dim anonymousLambdaType As TypeSymbol = Nothing Select Case argument.Kind Case BoundKind.QueryLambda ' Do not infer Anonymous Delegate type from query lambda. Case BoundKind.GroupTypeInferenceLambda ' Can't infer from this lambda. Case BoundKind.UnboundLambda ' Infer Anonymous Delegate type from unbound lambda. Dim inferredAnonymousDelegate As KeyValuePair(Of NamedTypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = DirectCast(argument, UnboundLambda).InferredAnonymousDelegate If (inferredAnonymousDelegate.Value.Diagnostics.IsDefault OrElse Not inferredAnonymousDelegate.Value.Diagnostics.HasAnyErrors()) Then Dim delegateInvokeMethod As MethodSymbol = Nothing If inferredAnonymousDelegate.Key IsNot Nothing Then delegateInvokeMethod = inferredAnonymousDelegate.Key.DelegateInvokeMethod End If If delegateInvokeMethod IsNot Nothing AndAlso delegateInvokeMethod.ReturnType IsNot LambdaSymbol.ReturnTypeIsUnknown Then anonymousLambdaType = inferredAnonymousDelegate.Key End If End If Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select If anonymousLambdaType IsNot Nothing Then Return InferTypeArgumentsFromArgument( argument.Syntax, anonymousLambdaType, argumentTypeByAssumption:=False, parameterType:=parameterType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) Else Return True End If ElseIf parameterType.IsDelegateType() Then Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol) ' First, we need to build a partial type substitution using the type of ' arguments as they stand right now, with some of them still being uninferred. ' TODO: Doesn't this make the inference algorithm order dependent? For example, if we were to ' infer more stuff from other non-lambda arguments, we might have a better chance to have ' more type information for the lambda, allowing successful lambda interpretation. ' Perhaps the graph doesn't allow us to get here until all "inputs" for lambda parameters ' are inferred. Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterDelegateType), NamedTypeSymbol) ' Now find the invoke method of the delegate Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then ' If we don't have an Invoke method, just bail. Return True End If Dim returnType As TypeSymbol = invokeMethod.ReturnType ' If the return type doesn't refer to parameters, no inference required. If Not RefersToGenericParameterToInferArgumentFor(returnType) Then Return True End If Dim lambdaParams As ImmutableArray(Of ParameterSymbol) Select Case argument.Kind Case BoundKind.QueryLambda lambdaParams = DirectCast(argument, BoundQueryLambda).LambdaSymbol.Parameters Case BoundKind.GroupTypeInferenceLambda lambdaParams = DirectCast(argument, GroupTypeInferenceLambda).Parameters Case BoundKind.UnboundLambda lambdaParams = DirectCast(argument, UnboundLambda).Parameters Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select Dim delegateParams As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters If lambdaParams.Length > delegateParams.Length Then Return True End If For i As Integer = 0 To lambdaParams.Length - 1 Step 1 Dim lambdaParam As ParameterSymbol = lambdaParams(i) Dim delegateParam As ParameterSymbol = delegateParams(i) If lambdaParam.Type Is Nothing Then ' If a lambda parameter has no type and the delegate parameter refers ' to an unbound generic parameter, we can't infer yet. If RefersToGenericParameterToInferArgumentFor(delegateParam.Type) Then ' Skip this type argument and other parameters will infer it or ' if that doesn't happen it will report an error. ' TODO: Why does it make sense to continue here? It looks like we can infer something from ' lambda's return type based on incomplete information. Also, this 'if' is redundant, ' there is nothing left to do in this loop anyway, and "continue" doesn't change anything. Continue For End If Else ' report the type of the lambda parameter to the delegate parameter. ' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic ' !!! parameter will be passed into the parameter of argument type. InferTypeArgumentsFromArgument( argument.Syntax, lambdaParam.Type, argumentTypeByAssumption:=False, parameterType:=delegateParam.Type, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, inferenceRestrictions:=RequiredConversion.Any) End If Next ' OK, now try to infer delegates return type from the lambda. Dim lambdaReturnType As TypeSymbol Select Case argument.Kind Case BoundKind.QueryLambda Dim queryLambda = DirectCast(argument, BoundQueryLambda) lambdaReturnType = queryLambda.LambdaSymbol.ReturnType If lambdaReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then lambdaReturnType = queryLambda.Expression.Type If lambdaReturnType Is Nothing Then If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Debug.Assert(Me.Diagnostic IsNot Nothing) lambdaReturnType = queryLambda.LambdaSymbol.ContainingBinder.MakeRValue(queryLambda.Expression, Me.Diagnostic).Type End If End If Case BoundKind.GroupTypeInferenceLambda lambdaReturnType = DirectCast(argument, GroupTypeInferenceLambda).InferLambdaReturnType(delegateParams) Case BoundKind.UnboundLambda Dim unboundLambda = DirectCast(argument, UnboundLambda) If unboundLambda.IsFunctionLambda Then Dim inferenceSignature As New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False) Dim returnTypeInfo As KeyValuePair(Of TypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = unboundLambda.InferReturnType(inferenceSignature) If Not returnTypeInfo.Value.Diagnostics.IsDefault AndAlso returnTypeInfo.Value.Diagnostics.HasAnyErrors() Then lambdaReturnType = Nothing ' Let's keep return type inference errors If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(returnTypeInfo.Value) ElseIf returnTypeInfo.Key Is LambdaSymbol.ReturnTypeIsUnknown Then lambdaReturnType = Nothing Else Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(inferenceSignature.ParameterTypes, inferenceSignature.ParameterIsByRef, returnTypeInfo.Key, returnsByRef:=False)) Debug.Assert(boundLambda.LambdaSymbol.ReturnType Is returnTypeInfo.Key) If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors Then lambdaReturnType = returnTypeInfo.Key ' Let's keep return type inference warnings, if any. If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(returnTypeInfo.Value) Me.Diagnostic.AddDependencies(boundLambda.Diagnostics.Dependencies) Else lambdaReturnType = Nothing ' Let's preserve diagnostics that caused the failure If Not boundLambda.Diagnostics.Diagnostics.IsDefaultOrEmpty Then If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(boundLambda.Diagnostics) End If End If End If ' But in the case of async/iterator lambdas, e.g. pass "Async Function() 1" to a parameter ' of type "Func(Of Task(Of T))" then we have to dig in further and match 1 to T... If (unboundLambda.Flags And (SourceMemberFlags.Async Or SourceMemberFlags.Iterator)) <> 0 AndAlso lambdaReturnType IsNot Nothing AndAlso lambdaReturnType.Kind = SymbolKind.NamedType AndAlso returnType IsNot Nothing AndAlso returnType.Kind = SymbolKind.NamedType Then ' By this stage we know that ' * we have an async/iterator lambda argument ' * the parameter-to-match is a delegate type whose result type refers to generic parameters ' The parameter might be a delegate with result type e.g. "Task(Of T)" in which case we have ' to dig in. Or it might be a delegate with result type "T" in which case we ' don't dig in. Dim lambdaReturnNamedType = DirectCast(lambdaReturnType, NamedTypeSymbol) Dim returnNamedType = DirectCast(returnType, NamedTypeSymbol) If lambdaReturnNamedType.Arity = 1 AndAlso IsSameTypeIgnoringAll(lambdaReturnNamedType.OriginalDefinition, returnNamedType.OriginalDefinition) Then ' We can assume that the lambda will have return type Task(Of T) or IEnumerable(Of T) ' or IEnumerator(Of T) as appropriate. That's already been ensured by the lambda-interpretation. Debug.Assert(TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T), TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T), TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T), TypeCompareKind.ConsiderEverything)) lambdaReturnType = lambdaReturnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo) returnType = returnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo) End If End If Else lambdaReturnType = Nothing If Not invokeMethod.IsSub AndAlso (unboundLambda.Flags And SourceMemberFlags.Async) <> 0 Then Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False)) If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors() Then If _asyncLambdaSubToFunctionMismatch Is Nothing Then _asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance) End If _asyncLambdaSubToFunctionMismatch.Add(unboundLambda) End If End If End If Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select If lambdaReturnType Is Nothing Then ' Inference failed, give up. Return False End If If lambdaReturnType.IsErrorType() Then Return True End If ' Now infer from the result type ' not ArgumentTypeByAssumption ??? lwischik: but maybe it should... Return InferTypeArgumentsFromArgument( argument.Syntax, lambdaReturnType, argumentTypeByAssumption:=False, parameterType:=returnType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T Return InferTypeArgumentsFromLambdaArgument(argument, DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), param) End If Return True End Function Public Function ConstructParameterTypeIfNeeded(parameterType As TypeSymbol) As TypeSymbol ' First, we need to build a partial type substitution using the type of ' arguments as they stand right now, with some of them still being uninferred. Dim methodSymbol As MethodSymbol = Candidate Dim typeArguments = ArrayBuilder(Of TypeWithModifiers).GetInstance(_typeParameterNodes.Length) For i As Integer = 0 To _typeParameterNodes.Length - 1 Step 1 Dim typeNode As TypeParameterNode = _typeParameterNodes(i) Dim newType As TypeSymbol If typeNode Is Nothing OrElse typeNode.CandidateInferredType Is Nothing Then 'No substitution newType = methodSymbol.TypeParameters(i) Else newType = typeNode.CandidateInferredType End If typeArguments.Add(New TypeWithModifiers(newType)) Next Dim partialSubstitution = TypeSubstitution.CreateAdditionalMethodTypeParameterSubstitution(methodSymbol.ConstructedFrom, typeArguments.ToImmutableAndFree()) ' Now we apply the partial substitution to the delegate type, leaving uninferred type parameters as is Return parameterType.InternalSubstituteTypeParameters(partialSubstitution).Type End Function Public Sub ReportAmbiguousInferenceError(typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference)) Debug.Assert(typeInfos.Count() >= 2, "Must have at least 2 elements in the list") ' Since they get added fifo, we need to walk the list backward. For i As Integer = 1 To typeInfos.Count - 1 Step 1 Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i) If Not currentTypeInfo.InferredFromObject Then ReportNotFailedInferenceDueToObject() ' TODO: Should we exit the loop? For some reason Dev10 keeps going. End If Next End Sub Public Sub ReportIncompatibleInferenceError( typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference)) If typeInfos.Count < 1 Then Return End If ' Since they get added fifo, we need to walk the list backward. For i As Integer = 1 To typeInfos.Count - 1 Step 1 Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i) If Not currentTypeInfo.InferredFromObject Then ReportNotFailedInferenceDueToObject() ' TODO: Should we exit the loop? For some reason Dev10 keeps going. End If Next End Sub Public Sub RegisterErrorReasons(inferenceErrorReasons As InferenceErrorReasons) _inferenceErrorReasons = _inferenceErrorReasons Or inferenceErrorReasons End Sub 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.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' The only public entry point is the Infer method. ''' </summary> Friend MustInherit Class TypeArgumentInference Public Shared Function Infer( candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, ByRef typeArguments As ImmutableArray(Of TypeSymbol), ByRef inferenceLevel As InferenceLevel, ByRef allFailedInferenceIsDueToObject As Boolean, ByRef someInferenceFailed As Boolean, ByRef inferenceErrorReasons As InferenceErrorReasons, <Out> ByRef inferredTypeByAssumption As BitVector, <Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken), <[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), ByRef diagnostic As BindingDiagnosticBag, Optional inferTheseTypeParameters As BitVector = Nothing ) As Boolean Debug.Assert(candidate Is candidate.ConstructedFrom) Return InferenceGraph.Infer(candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode, typeArguments, inferenceLevel, allFailedInferenceIsDueToObject, someInferenceFailed, inferenceErrorReasons, inferredTypeByAssumption, typeArgumentsLocation, asyncLambdaSubToFunctionMismatch, useSiteInfo, diagnostic, inferTheseTypeParameters) End Function ' No-one should create instances of this class. Private Sub New() End Sub Public Enum InferenceLevel As Byte None = 0 ' None is used to indicate uninitialized but semantically it should not matter if there is a whidbey delegate ' or no delegate in the overload resolution hence both have value 0 such that overload resolution ' will not prefer a non inferred method over an inferred one. Whidbey = 0 Orcas = 1 ' Keep invalid the biggest number Invalid = 2 End Enum ' MatchGenericArgumentParameter: ' This is used in type inference, when matching an argument e.g. Arg(Of String) against a parameter Parm(Of T). ' In covariant contexts e.g. Action(Of _), the two match if Arg <= Parm (i.e. Arg inherits/implements Parm). ' In contravariant contexts e.g. IEnumerable(Of _), the two match if Parm <= Arg (i.e. Parm inherits/implements Arg). ' In invariant contexts e.g. List(Of _), the two match only if Arg and Parm are identical. ' Note: remember that rank-1 arrays T() implement IEnumerable(Of T), IList(Of T) and ICollection(Of T). Public Enum MatchGenericArgumentToParameter MatchBaseOfGenericArgumentToParameter MatchArgumentToBaseOfGenericParameter MatchGenericArgumentToParameterExactly End Enum Private Enum InferenceNodeType As Byte ArgumentNode TypeParameterNode End Enum Private MustInherit Class InferenceNode Inherits GraphNode(Of InferenceNode) Public ReadOnly NodeType As InferenceNodeType Public InferenceComplete As Boolean Protected Sub New(graph As InferenceGraph, nodeType As InferenceNodeType) MyBase.New(graph) Me.NodeType = nodeType End Sub Public Shadows ReadOnly Property Graph As InferenceGraph Get Return DirectCast(MyBase.Graph, InferenceGraph) End Get End Property ''' <summary> ''' Returns True if the inference algorithm should be restarted. ''' </summary> Public MustOverride Function InferTypeAndPropagateHints() As Boolean <Conditional("DEBUG")> Public Sub VerifyIncomingInferenceComplete( ByVal nodeType As InferenceNodeType ) If Not Graph.SomeInferenceHasFailed() Then For Each current As InferenceNode In IncomingEdges Debug.Assert(current.NodeType = nodeType, "Should only have expected incoming edges.") Debug.Assert(current.InferenceComplete, "Should have inferred type already") Next End If End Sub End Class Private Class DominantTypeDataTypeInference Inherits DominantTypeData ' Fields needed for error reporting Public ByAssumption As Boolean ' was ResultType chosen by assumption or intention? Public Parameter As ParameterSymbol Public InferredFromObject As Boolean Public TypeParameter As TypeParameterSymbol Public ArgumentLocation As SyntaxNode End Class Private Class TypeParameterNode Inherits InferenceNode Public ReadOnly DeclaredTypeParam As TypeParameterSymbol Public ReadOnly InferenceTypeCollection As TypeInferenceCollection(Of DominantTypeDataTypeInference) Private _inferredType As TypeSymbol Private _inferredFromLocation As SyntaxNodeOrToken Private _inferredTypeByAssumption As Boolean ' TODO: Dev10 has two locations to track type inferred so far. ' One that can be changed with time and the other one that cannot be changed. ' This one, cannot be changed once set. We need to clean this up later. Private _candidateInferredType As TypeSymbol Private _parameter As ParameterSymbol Public Sub New(graph As InferenceGraph, typeParameter As TypeParameterSymbol) MyBase.New(graph, InferenceNodeType.TypeParameterNode) DeclaredTypeParam = typeParameter InferenceTypeCollection = New TypeInferenceCollection(Of DominantTypeDataTypeInference)() End Sub Public ReadOnly Property InferredType As TypeSymbol Get Return _inferredType End Get End Property Public ReadOnly Property CandidateInferredType As TypeSymbol Get Return _candidateInferredType End Get End Property Public ReadOnly Property InferredFromLocation As SyntaxNodeOrToken Get Return _inferredFromLocation End Get End Property Public ReadOnly Property InferredTypeByAssumption As Boolean Get Return _inferredTypeByAssumption End Get End Property Public Sub RegisterInferredType(inferredType As TypeSymbol, inferredFromLocation As SyntaxNodeOrToken, inferredTypeByAssumption As Boolean) ' Make sure ArrayLiteralTypeSymbol does not leak out Dim arrayLiteralType = TryCast(inferredType, ArrayLiteralTypeSymbol) If arrayLiteralType IsNot Nothing Then Dim arrayLiteral = arrayLiteralType.ArrayLiteral Dim arrayType = arrayLiteral.InferredType If Not (arrayLiteral.HasDominantType AndAlso arrayLiteral.NumberOfCandidates = 1) AndAlso arrayType.ElementType.SpecialType = SpecialType.System_Object Then ' ReportArrayLiteralInferredTypeDiagnostics in ReclassifyArrayLiteralExpression reports an error ' when option strict is on and the array type is object() and there wasn't a dominant type. However, ' Dev10 does not report this error when inferring a type parameter's type. Create a new object() type ' to suppress the error. inferredType = ArrayTypeSymbol.CreateVBArray(arrayType.ElementType, Nothing, arrayType.Rank, arrayLiteral.Binder.Compilation.Assembly) Else inferredType = arrayLiteral.InferredType End If End If Debug.Assert(Not (TypeOf inferredType Is ArrayLiteralTypeSymbol)) _inferredType = inferredType _inferredFromLocation = inferredFromLocation _inferredTypeByAssumption = inferredTypeByAssumption ' TODO: Dev10 has two locations to track type inferred so far. ' One that can be changed with time and the other one that cannot be changed. ' We need to clean this up. If _candidateInferredType Is Nothing Then _candidateInferredType = inferredType End If End Sub Public ReadOnly Property Parameter As ParameterSymbol Get Return _parameter End Get End Property Public Sub SetParameter(parameter As ParameterSymbol) Debug.Assert(_parameter Is Nothing) _parameter = parameter End Sub Public Overrides Function InferTypeAndPropagateHints() As Boolean Dim numberOfIncomingEdges As Integer = IncomingEdges.Count Dim restartAlgorithm As Boolean = False Dim argumentLocation As SyntaxNode Dim numberOfIncomingWithNothing As Integer = 0 If numberOfIncomingEdges > 0 Then argumentLocation = DirectCast(IncomingEdges(0), ArgumentNode).Expression.Syntax Else argumentLocation = Nothing End If Dim numberOfAssertions As Integer = 0 Dim incomingFromObject As Boolean = False Dim list As ArrayBuilder(Of InferenceNode) = IncomingEdges For Each currentGraphNode As InferenceNode In IncomingEdges Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.ArgumentNode, "Should only have named nodes as incoming edges.") Dim currentNamedNode = DirectCast(currentGraphNode, ArgumentNode) If currentNamedNode.Expression.Type IsNot Nothing AndAlso currentNamedNode.Expression.Type.IsObjectType() Then incomingFromObject = True End If If Not currentNamedNode.InferenceComplete Then Graph.RemoveEdge(currentNamedNode, Me) restartAlgorithm = True numberOfAssertions += 1 Else ' We should not infer from a Nothing literal. If currentNamedNode.Expression.IsStrictNothingLiteral() Then numberOfIncomingWithNothing += 1 End If End If Next If numberOfIncomingEdges > 0 AndAlso numberOfIncomingEdges = numberOfIncomingWithNothing Then ' !! Inference has failed: All incoming type hints, were based on 'Nothing' Graph.MarkInferenceFailure() Graph.ReportNotFailedInferenceDueToObject() End If Dim numberOfTypeHints As Integer = InferenceTypeCollection.GetTypeDataList().Count() If numberOfTypeHints = 0 Then If numberOfAssertions = numberOfIncomingEdges Then Graph.MarkInferenceLevel(InferenceLevel.Orcas) Else ' !! Inference has failed. No Type hints, and some, not all were assertions, otherwise we would have picked object for strict. RegisterInferredType(Nothing, Nothing, False) Graph.MarkInferenceFailure() If Not incomingFromObject Then Graph.ReportNotFailedInferenceDueToObject() End If End If ElseIf numberOfTypeHints = 1 Then Dim typeData As DominantTypeDataTypeInference = InferenceTypeCollection.GetTypeDataList()(0) If argumentLocation Is Nothing AndAlso typeData.ArgumentLocation IsNot Nothing Then argumentLocation = typeData.ArgumentLocation End If RegisterInferredType(typeData.ResultType, argumentLocation, typeData.ByAssumption) Else ' Run the whidbey algorithm to see if we are smarter now. Dim firstInferredType As TypeSymbol = Nothing Dim allTypeData As ArrayBuilder(Of DominantTypeDataTypeInference) = InferenceTypeCollection.GetTypeDataList() For Each currentTypeInfo As DominantTypeDataTypeInference In allTypeData If firstInferredType Is Nothing Then firstInferredType = currentTypeInfo.ResultType ElseIf Not firstInferredType.IsSameTypeIgnoringAll(currentTypeInfo.ResultType) Then ' Whidbey failed hard here, in Orcas we added dominant type information. Graph.MarkInferenceLevel(InferenceLevel.Orcas) End If Next Dim dominantTypeDataList = ArrayBuilder(Of DominantTypeDataTypeInference).GetInstance() Dim errorReasons As InferenceErrorReasons = InferenceErrorReasons.Other InferenceTypeCollection.FindDominantType(dominantTypeDataList, errorReasons, Graph.UseSiteInfo) If dominantTypeDataList.Count = 1 Then ' //consider: scottwis ' // This seems dangerous to me, that we ' // remove error reasons here. ' // Instead of clearing these, what we should be doing is ' // asserting that they are not set. ' // If for some reason they get set, but ' // we enter this path, then we have a bug. ' // This code is just masking any such bugs. errorReasons = errorReasons And (Not (InferenceErrorReasons.Ambiguous Or InferenceErrorReasons.NoBest)) Dim typeData As DominantTypeDataTypeInference = dominantTypeDataList(0) RegisterInferredType(typeData.ResultType, typeData.ArgumentLocation, typeData.ByAssumption) ' // Also update the location of the argument for constraint error reporting later on. Else If (errorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then ' !! Inference has failed. Dominant type algorithm found ambiguous types. Graph.ReportAmbiguousInferenceError(dominantTypeDataList) Else ' //consider: scottwis ' // This code appears to be operating under the assumption that if the error reason is not due to an ' // ambiguity then it must be because there was no best match. ' // We should be asserting here to verify that assertion. ' !! Inference has failed. Dominant type algorithm could not find a dominant type. Graph.ReportIncompatibleInferenceError(allTypeData) End If RegisterInferredType(allTypeData(0).ResultType, argumentLocation, False) Graph.MarkInferenceFailure() End If Graph.RegisterErrorReasons(errorReasons) dominantTypeDataList.Free() End If InferenceComplete = True Return restartAlgorithm End Function Public Sub AddTypeHint( type As TypeSymbol, typeByAssumption As Boolean, argumentLocation As SyntaxNode, parameter As ParameterSymbol, inferredFromObject As Boolean, inferenceRestrictions As RequiredConversion ) Debug.Assert(Not typeByAssumption OrElse type.IsObjectType() OrElse TypeOf type Is ArrayLiteralTypeSymbol, "unexpected: a type which was 'by assumption', but isn't object or array literal") ' Don't add error types to the type argument inference collection. If type.IsErrorType Then Return End If Dim foundInList As Boolean = False ' Do not merge array literals with other expressions If TypeOf type IsNot ArrayLiteralTypeSymbol Then For Each competitor As DominantTypeDataTypeInference In InferenceTypeCollection.GetTypeDataList() ' Do not merge array literals with other expressions If TypeOf competitor.ResultType IsNot ArrayLiteralTypeSymbol AndAlso type.IsSameTypeIgnoringAll(competitor.ResultType) Then competitor.ResultType = TypeInferenceCollection.MergeTupleNames(competitor.ResultType, type) competitor.InferenceRestrictions = Conversions.CombineConversionRequirements( competitor.InferenceRestrictions, inferenceRestrictions) competitor.ByAssumption = competitor.ByAssumption AndAlso typeByAssumption Debug.Assert(Not foundInList, "List is supposed to be unique: how can we already find two of the same type in this list.") foundInList = True ' TODO: Should we simply exit the loop for RELEASE build? End If Next End If If Not foundInList Then Dim typeData As DominantTypeDataTypeInference = New DominantTypeDataTypeInference() typeData.ResultType = type typeData.ByAssumption = typeByAssumption typeData.InferenceRestrictions = inferenceRestrictions typeData.ArgumentLocation = argumentLocation typeData.Parameter = parameter typeData.InferredFromObject = inferredFromObject typeData.TypeParameter = DeclaredTypeParam InferenceTypeCollection.GetTypeDataList().Add(typeData) End If End Sub End Class Private Class ArgumentNode Inherits InferenceNode Public ReadOnly ParameterType As TypeSymbol Public ReadOnly Expression As BoundExpression Public ReadOnly Parameter As ParameterSymbol Public Sub New(graph As InferenceGraph, expression As BoundExpression, parameterType As TypeSymbol, parameter As ParameterSymbol) MyBase.New(graph, InferenceNodeType.ArgumentNode) Me.Expression = expression Me.ParameterType = parameterType Me.Parameter = parameter End Sub Public Overrides Function InferTypeAndPropagateHints() As Boolean #If DEBUG Then VerifyIncomingInferenceComplete(InferenceNodeType.TypeParameterNode) #End If ' Check if all incoming are ok, otherwise skip inference. For Each currentGraphNode As InferenceNode In IncomingEdges Debug.Assert(currentGraphNode.NodeType = InferenceNodeType.TypeParameterNode, "Should only have typed nodes as incoming edges.") Dim currentTypedNode As TypeParameterNode = DirectCast(currentGraphNode, TypeParameterNode) If currentTypedNode.InferredType Is Nothing Then Dim skipThisNode As Boolean = True If Expression.Kind = BoundKind.UnboundLambda AndAlso ParameterType.IsDelegateType() Then ' Check here if we need to infer Object for some of the parameters of the Lambda if we weren't able ' to infer these otherwise. This is only the case for arguments of the lambda that have a GenericParam ' of the method we are inferring that is not yet inferred. ' Now find the invoke method of the delegate Dim delegateType = DirectCast(ParameterType, NamedTypeSymbol) Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod IsNot Nothing AndAlso invokeMethod.GetUseSiteInfo().DiagnosticInfo Is Nothing Then Dim unboundLambda = DirectCast(Expression, UnboundLambda) Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) = unboundLambda.Parameters Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters For i As Integer = 0 To Math.Min(lambdaParameters.Length, delegateParameters.Length) - 1 Step 1 Dim lambdaParameter = DirectCast(lambdaParameters(i), UnboundLambdaParameterSymbol) Dim delegateParam As ParameterSymbol = delegateParameters(i) If lambdaParameter.Type Is Nothing AndAlso delegateParam.Type.Equals(currentTypedNode.DeclaredTypeParam) Then If Graph.Diagnostic Is Nothing Then Graph.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Graph.UseSiteInfo.AccumulatesDependencies) End If ' If this was an argument to the unbound Lambda, infer Object. If Graph.ObjectType Is Nothing Then Debug.Assert(Graph.Diagnostic IsNot Nothing) Graph.ObjectType = unboundLambda.Binder.GetSpecialType(SpecialType.System_Object, lambdaParameter.IdentifierSyntax, Graph.Diagnostic) End If currentTypedNode.RegisterInferredType(Graph.ObjectType, lambdaParameter.TypeSyntax, currentTypedNode.InferredTypeByAssumption) ' ' Port SP1 CL 2941063 to VS10 ' Bug 153317 ' Report an error if Option Strict On or a warning if Option Strict Off ' because we have no hints about the lambda parameter ' and we are assuming that it is an object. ' e.g. "Sub f(Of T, U)(ByVal x As Func(Of T, U))" invoked with "f(function(z)z)" ' needs to put the squiggly on the first "z". Debug.Assert(Graph.Diagnostic IsNot Nothing) unboundLambda.Binder.ReportLambdaParameterInferredToBeObject(lambdaParameter, Graph.Diagnostic) skipThisNode = False Exit For End If Next End If End If If skipThisNode Then InferenceComplete = True Return False ' DOn't restart the algorithm. End If End If Next Dim argumentType As TypeSymbol = Nothing Dim inferenceOk As Boolean = False Select Case Expression.Kind Case BoundKind.AddressOfOperator inferenceOk = Graph.InferTypeArgumentsFromAddressOfArgument( Expression, ParameterType, Parameter) Case BoundKind.LateAddressOfOperator ' We can not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference ' as not failed due to object. Graph.ReportNotFailedInferenceDueToObject() inferenceOk = True Case BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda, BoundKind.UnboundLambda ' TODO: Not sure if this is applicable to Roslyn, need to try this out when all required features are available. ' BUG: 131359 If the lambda is wrapped in a delegate constructor the resultType ' will be set and not be Void. In this case the lambda argument should be treated as a regular ' argument so fall through in this case. Debug.Assert(Expression.Type Is Nothing) ' TODO: We are setting inference level before ' even trying to infer something from the lambda. It is possible ' that we won't infer anything, should consider changing the ' inference level after. Graph.MarkInferenceLevel(InferenceLevel.Orcas) inferenceOk = Graph.InferTypeArgumentsFromLambdaArgument( Expression, ParameterType, Parameter) Case Else HandleAsAGeneralExpression: ' We should not infer from a Nothing literal. If Expression.IsStrictNothingLiteral() Then InferenceComplete = True ' continue without restarting, if all hints are Nothing the InferenceTypeNode will mark ' the inference as failed. Return False End If Dim inferenceRestrictions As RequiredConversion = RequiredConversion.Any If Parameter IsNot Nothing AndAlso Parameter.IsByRef AndAlso (Expression.IsLValue() OrElse Expression.IsPropertySupportingAssignment()) Then ' A ByRef parameter needs (if the argument was an lvalue) to be copy-backable into ' that argument. Debug.Assert(inferenceRestrictions = RequiredConversion.Any, "there should have been no prior restrictions by the time we encountered ByRef") inferenceRestrictions = Conversions.CombineConversionRequirements( inferenceRestrictions, Conversions.InvertConversionRequirement(inferenceRestrictions)) Debug.Assert(inferenceRestrictions = RequiredConversion.AnyAndReverse, "expected ByRef to require AnyAndReverseConversion") End If Dim arrayLiteral As BoundArrayLiteral = Nothing Dim argumentTypeByAssumption As Boolean = False Dim expressionType As TypeSymbol If Expression.Kind = BoundKind.ArrayLiteral Then arrayLiteral = DirectCast(Expression, BoundArrayLiteral) argumentTypeByAssumption = arrayLiteral.NumberOfCandidates <> 1 expressionType = New ArrayLiteralTypeSymbol(arrayLiteral) ElseIf Expression.Kind = BoundKind.TupleLiteral Then expressionType = DirectCast(Expression, BoundTupleLiteral).InferredType Else expressionType = Expression.Type End If ' Need to create an ArrayLiteralTypeSymbol inferenceOk = Graph.InferTypeArgumentsFromArgument( Expression.Syntax, expressionType, argumentTypeByAssumption, ParameterType, Parameter, MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions) End Select If Not inferenceOk Then ' !! Inference has failed. Mismatch of Argument and Parameter signature, so could not find type hints. Graph.MarkInferenceFailure() If Not (Expression.Type IsNot Nothing AndAlso Expression.Type.IsObjectType()) Then Graph.ReportNotFailedInferenceDueToObject() End If End If InferenceComplete = True Return False ' // Don't restart the algorithm; End Function End Class Private Class InferenceGraph Inherits Graph(Of InferenceNode) Public Diagnostic As BindingDiagnosticBag Public ObjectType As NamedTypeSymbol Public ReadOnly Candidate As MethodSymbol Public ReadOnly Arguments As ImmutableArray(Of BoundExpression) Public ReadOnly ParameterToArgumentMap As ArrayBuilder(Of Integer) Public ReadOnly ParamArrayItems As ArrayBuilder(Of Integer) Public ReadOnly DelegateReturnType As TypeSymbol Public ReadOnly DelegateReturnTypeReferenceBoundNode As BoundNode Public UseSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) Private _someInferenceFailed As Boolean Private _inferenceErrorReasons As InferenceErrorReasons Private _allFailedInferenceIsDueToObject As Boolean = True ' remains true until proven otherwise. Private _typeInferenceLevel As InferenceLevel = InferenceLevel.None Private _asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression) Private ReadOnly _typeParameterNodes As ImmutableArray(Of TypeParameterNode) Private ReadOnly _verifyingAssertions As Boolean Private Sub New( diagnostic As BindingDiagnosticBag, candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol) ) Debug.Assert(delegateReturnType Is Nothing OrElse delegateReturnTypeReferenceBoundNode IsNot Nothing) Me.Diagnostic = diagnostic Me.Candidate = candidate Me.Arguments = arguments Me.ParameterToArgumentMap = parameterToArgumentMap Me.ParamArrayItems = paramArrayItems Me.DelegateReturnType = delegateReturnType Me.DelegateReturnTypeReferenceBoundNode = delegateReturnTypeReferenceBoundNode Me._asyncLambdaSubToFunctionMismatch = asyncLambdaSubToFunctionMismatch Me.UseSiteInfo = useSiteInfo ' Allocate the array of TypeParameter nodes. Dim arity As Integer = candidate.Arity Dim typeParameterNodes(arity - 1) As TypeParameterNode For i As Integer = 0 To arity - 1 Step 1 typeParameterNodes(i) = New TypeParameterNode(Me, candidate.TypeParameters(i)) Next _typeParameterNodes = typeParameterNodes.AsImmutableOrNull() End Sub Public ReadOnly Property SomeInferenceHasFailed As Boolean Get Return _someInferenceFailed End Get End Property Public Sub MarkInferenceFailure() _someInferenceFailed = True End Sub Public ReadOnly Property AllFailedInferenceIsDueToObject As Boolean Get Return _allFailedInferenceIsDueToObject End Get End Property Public ReadOnly Property InferenceErrorReasons As InferenceErrorReasons Get Return _inferenceErrorReasons End Get End Property Public Sub ReportNotFailedInferenceDueToObject() _allFailedInferenceIsDueToObject = False End Sub Public ReadOnly Property TypeInferenceLevel As InferenceLevel Get Return _typeInferenceLevel End Get End Property Public Sub MarkInferenceLevel(typeInferenceLevel As InferenceLevel) If _typeInferenceLevel < typeInferenceLevel Then _typeInferenceLevel = typeInferenceLevel End If End Sub Public Shared Function Infer( candidate As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), parameterToArgumentMap As ArrayBuilder(Of Integer), paramArrayItems As ArrayBuilder(Of Integer), delegateReturnType As TypeSymbol, delegateReturnTypeReferenceBoundNode As BoundNode, ByRef typeArguments As ImmutableArray(Of TypeSymbol), ByRef inferenceLevel As InferenceLevel, ByRef allFailedInferenceIsDueToObject As Boolean, ByRef someInferenceFailed As Boolean, ByRef inferenceErrorReasons As InferenceErrorReasons, <Out> ByRef inferredTypeByAssumption As BitVector, <Out> ByRef typeArgumentsLocation As ImmutableArray(Of SyntaxNodeOrToken), <[In](), Out()> ByRef asyncLambdaSubToFunctionMismatch As HashSet(Of BoundExpression), <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), ByRef diagnostic As BindingDiagnosticBag, inferTheseTypeParameters As BitVector ) As Boolean Dim graph As New InferenceGraph(diagnostic, candidate, arguments, parameterToArgumentMap, paramArrayItems, delegateReturnType, delegateReturnTypeReferenceBoundNode, asyncLambdaSubToFunctionMismatch, useSiteInfo) ' Build a graph describing the flow of type inference data. ' This creates edges from "regular" arguments to type parameters and from type parameters to lambda arguments. ' In the rest of this function that graph is then processed (see below for more details). Essentially, for each ' "type parameter" node a list of "type hints" (possible candidates for type inference) is collected. The dominant ' type algorithm is then performed over the list of hints associated with each node. ' ' The process of populating the graph also seeds type hints for type parameters referenced by explicitly typed ' lambda parameters. Also, hints sometimes have restrictions placed on them that limit what conversions the dominant type ' algorithm can consider when it processes them. The restrictions are generally driven by the context in which type ' parameters are used. For example if a type parameter is used as a type parameter of another type (something like IGoo(of T)), ' then the dominant type algorithm is not allowed to consider any conversions. There are similar restrictions for ' Array co-variance. graph.PopulateGraph() Dim topoSortedGraph = ArrayBuilder(Of StronglyConnectedComponent(Of InferenceNode)).GetInstance() ' This is the restart point of the algorithm Do Dim restartAlgorithm As Boolean = False Dim stronglyConnectedComponents As Graph(Of StronglyConnectedComponent(Of InferenceNode)) = graph.BuildStronglyConnectedComponents() topoSortedGraph.Clear() stronglyConnectedComponents.TopoSort(topoSortedGraph) ' We now iterate over the topologically-sorted strongly connected components of the graph, and generate ' type hints as appropriate. ' ' When we find a node for an argument (or an ArgumentNode as it's referred to in the code), we infer ' types for all type parameters referenced by that argument and then propagate those types as hints ' to the referenced type parameters. If there are incoming edges into the argument node, they correspond ' to parameters of lambda arguments that get their value from the delegate type that contains type ' parameters that would have been inferred during a previous iteration of the loop. Those types are ' flowed into the lambda argument. ' ' When we encounter a "type parameter" node (or TypeParameterNode as it is called in the code), we run ' the dominant type algorithm over all of it's hints and use the resulting type as the value for the ' referenced type parameter. ' ' If we find a strongly connected component with more than one node, it means we ' have a cycle and cannot simply run the inference algorithm. When this happens, ' we look through the nodes in the cycle for a type parameter node with at least ' one type hint. If we find one, we remove all incoming edges to that node, ' infer the type using its hints, and then restart the whole algorithm from the ' beginning (recompute the strongly connected components, resort them, and then ' iterate over the graph again). The source nodes of the incoming edges we ' removed are added to an "assertion list". After graph traversal is done we ' then run inference on any "assertion nodes" we may have created. For Each sccNode As StronglyConnectedComponent(Of InferenceNode) In topoSortedGraph Dim childNodes As ArrayBuilder(Of InferenceNode) = sccNode.ChildNodes ' Small optimization if one node If childNodes.Count = 1 Then If childNodes(0).InferTypeAndPropagateHints() Then ' consider: scottwis ' We should be asserting here, because this code is unreachable.. ' There are two implementations of InferTypeAndPropagateHints, ' one for "named nodes" (nodes corresponding to arguments) and another ' for "type nodes" (nodes corresponding to types). ' The implementation for "named nodes" always returns false, which means ' "don't restart the algorithm". The implementation for "type nodes" only returns true ' if a node has incoming edges that have not been visited previously. In order for that ' to happen the node must be inside a strongly connected component with more than one node ' (i.e. it must be involved in a cycle). If it wasn't we would be visiting it in ' topological order, which means all incoming edges should have already been visited. ' That means that if we reach this code, there is probably a bug in the traversal process. We ' don't want to silently mask the bug. At a minimum we should either assert or generate a compiler error. ' ' An argument could be made that it is good to have this because ' InferTypeAndPropagateHints is virtual, and should some new node type be ' added it's implementation may return true, and so this would follow that ' path. That argument does make some tiny amount of sense, and so we ' should keep this code here to make it easier to make any such ' modifications in the future. However, we still need an assert to guard ' against graph traversal bugs, and in the event that such changes are ' made, leave it to the modifier to remove the assert if necessary. Throw ExceptionUtilities.Unreachable End If Else Dim madeInferenceProgress As Boolean = False For Each child As InferenceNode In childNodes If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso DirectCast(child, TypeParameterNode).InferenceTypeCollection.GetTypeDataList().Count > 0 Then If child.InferTypeAndPropagateHints() Then ' If edges were broken, restart algorithm to recompute strongly connected components. restartAlgorithm = True End If madeInferenceProgress = True End If Next If Not madeInferenceProgress Then ' Did not make progress trying to force incoming edges for nodes with TypesHints, just inferring all now, ' will infer object if no type hints. For Each child As InferenceNode In childNodes If child.NodeType = InferenceNodeType.TypeParameterNode AndAlso child.InferTypeAndPropagateHints() Then ' If edges were broken, restart algorithm to recompute strongly connected components. restartAlgorithm = True End If Next End If If restartAlgorithm Then Exit For ' For Each sccNode End If End If Next If restartAlgorithm Then Continue Do End If Exit Do Loop 'The commented code below is from Dev10, but it looks like 'it doesn't do anything useful because topoSortedGraph contains 'StronglyConnectedComponents, which have NodeType=None. ' 'graph.m_VerifyingAssertions = True 'GraphNodeListIterator assertionIter(&topoSortedGraph); ' While (assertionIter.MoveNext()) '{ ' GraphNode* currentNode = assertionIter.Current(); ' if (currentNode->m_NodeType == TypedNodeType) ' { ' InferenceTypeNode* currentTypeNode = (InferenceTypeNode*)currentNode; ' currentTypeNode->VerifyTypeAssertions(); ' } '} 'graph.m_VerifyingAssertions = False topoSortedGraph.Free() Dim succeeded As Boolean = Not graph.SomeInferenceHasFailed someInferenceFailed = graph.SomeInferenceHasFailed allFailedInferenceIsDueToObject = graph.AllFailedInferenceIsDueToObject inferenceErrorReasons = graph.InferenceErrorReasons ' Make sure that allFailedInferenceIsDueToObject only stays set, ' if there was an actual inference failure. If Not someInferenceFailed OrElse delegateReturnType IsNot Nothing Then allFailedInferenceIsDueToObject = False End If Dim arity As Integer = candidate.Arity Dim inferredTypes(arity - 1) As TypeSymbol Dim inferredFromLocation(arity - 1) As SyntaxNodeOrToken For i As Integer = 0 To arity - 1 Step 1 ' TODO: Should we use InferredType or CandidateInferredType here? It looks like Dev10 is using the latter, ' it might not be cleaned in case of a failure. Will use the former for now. Dim typeParameterNode = graph._typeParameterNodes(i) Dim inferredType As TypeSymbol = typeParameterNode.InferredType If inferredType Is Nothing AndAlso (inferTheseTypeParameters.IsNull OrElse inferTheseTypeParameters(i)) Then succeeded = False End If If typeParameterNode.InferredTypeByAssumption Then If inferredTypeByAssumption.IsNull Then inferredTypeByAssumption = BitVector.Create(arity) End If inferredTypeByAssumption(i) = True End If inferredTypes(i) = inferredType inferredFromLocation(i) = typeParameterNode.InferredFromLocation Next typeArguments = inferredTypes.AsImmutableOrNull() typeArgumentsLocation = inferredFromLocation.AsImmutableOrNull() inferenceLevel = graph._typeInferenceLevel Debug.Assert(diagnostic Is Nothing OrElse diagnostic Is graph.Diagnostic) diagnostic = graph.Diagnostic asyncLambdaSubToFunctionMismatch = graph._asyncLambdaSubToFunctionMismatch useSiteInfo = graph.UseSiteInfo Return succeeded End Function Private Sub PopulateGraph() Dim candidate As MethodSymbol = Me.Candidate Dim arguments As ImmutableArray(Of BoundExpression) = Me.Arguments Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = Me.ParameterToArgumentMap Dim paramArrayItems As ArrayBuilder(Of Integer) = Me.ParamArrayItems Dim isExpandedParamArrayForm As Boolean = (paramArrayItems IsNot Nothing) Dim argIndex As Integer For paramIndex = 0 To candidate.ParameterCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Parameters(paramIndex) Dim targetType As TypeSymbol = param.Type If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then If targetType.Kind <> SymbolKind.ArrayType Then Continue For End If If Not isExpandedParamArrayForm Then argIndex = parameterToArgumentMap(paramIndex) Dim paramArrayArgument = If(argIndex = -1, Nothing, arguments(argIndex)) Debug.Assert(paramArrayArgument Is Nothing OrElse paramArrayArgument.Kind <> BoundKind.OmittedArgument) '§11.8.2 Applicable Methods 'If the conversion from the type of the argument expression to the paramarray type is narrowing, 'then the method is only applicable in its expanded form. '!!! However, there is an exception to that rule - narrowing conversion from semantical Nothing literal is Ok. !!! If paramArrayArgument Is Nothing OrElse paramArrayArgument.HasErrors OrElse Not ArgumentTypePossiblyMatchesParamarrayShape(paramArrayArgument, targetType) Then Continue For End If RegisterArgument(paramArrayArgument, targetType, param) Else Debug.Assert(isExpandedParamArrayForm) '§11.8.2 Applicable Methods 'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form. ' Note, that explicitly converted NOTHING is treated the same way by Dev10. If paramArrayItems.Count = 1 AndAlso arguments(paramArrayItems(0)).IsNothingLiteral() Then Continue For End If ' Otherwise, for a ParamArray parameter, all the matching arguments are passed ' ByVal as instances of the element type of the ParamArray. ' Perform the conversions to the element type of the ParamArray here. Dim arrayType = DirectCast(targetType, ArrayTypeSymbol) If Not arrayType.IsSZArray Then Continue For End If targetType = arrayType.ElementType If targetType.Kind = SymbolKind.ErrorType Then Continue For End If For j As Integer = 0 To paramArrayItems.Count - 1 Step 1 If arguments(paramArrayItems(j)).HasErrors Then Continue For End If RegisterArgument(arguments(paramArrayItems(j)), targetType, param) Next End If Continue For End If argIndex = parameterToArgumentMap(paramIndex) Dim argument = If(argIndex = -1, Nothing, arguments(argIndex)) If argument Is Nothing OrElse argument.HasErrors OrElse targetType.IsErrorType() OrElse argument.Kind = BoundKind.OmittedArgument Then Continue For End If RegisterArgument(argument, targetType, param) Next AddDelegateReturnTypeToGraph() End Sub Private Sub AddDelegateReturnTypeToGraph() If Me.DelegateReturnType IsNot Nothing AndAlso Not Me.DelegateReturnType.IsVoidType() Then Dim fakeArgument As New BoundRValuePlaceholder(Me.DelegateReturnTypeReferenceBoundNode.Syntax, Me.DelegateReturnType) Dim returnNode As New ArgumentNode(Me, fakeArgument, Me.Candidate.ReturnType, parameter:=Nothing) ' Add the edges from all the current generic parameters to this named node. For Each current As InferenceNode In Vertices If current.NodeType = InferenceNodeType.TypeParameterNode Then AddEdge(current, returnNode) End If Next ' Add the edges from the resultType outgoing to the generic parameters. AddTypeToGraph(returnNode, isOutgoingEdge:=True) End If End Sub Private Sub RegisterArgument( argument As BoundExpression, targetType As TypeSymbol, param As ParameterSymbol ) ' Dig through parenthesized. If Not argument.IsNothingLiteral Then argument = argument.GetMostEnclosedParenthesizedExpression() End If Dim argNode As New ArgumentNode(Me, argument, targetType, param) Select Case argument.Kind Case BoundKind.UnboundLambda, BoundKind.QueryLambda, BoundKind.GroupTypeInferenceLambda AddLambdaToGraph(argNode, argument.GetBinderFromLambda()) Case BoundKind.AddressOfOperator AddAddressOfToGraph(argNode, DirectCast(argument, BoundAddressOfOperator).Binder) Case BoundKind.TupleLiteral AddTupleLiteralToGraph(argNode) Case Else AddTypeToGraph(argNode, isOutgoingEdge:=True) End Select End Sub Private Sub AddTypeToGraph( node As ArgumentNode, isOutgoingEdge As Boolean ) AddTypeToGraph(node.ParameterType, node, isOutgoingEdge, BitVector.Create(_typeParameterNodes.Length)) End Sub Private Function FindTypeParameterNode(typeParameter As TypeParameterSymbol) As TypeParameterNode Dim ordinal As Integer = typeParameter.Ordinal If ordinal < _typeParameterNodes.Length AndAlso _typeParameterNodes(ordinal) IsNot Nothing AndAlso typeParameter.Equals(_typeParameterNodes(ordinal).DeclaredTypeParam) Then Return _typeParameterNodes(ordinal) End If Return Nothing End Function Private Sub AddTypeToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, isOutgoingEdge As Boolean, ByRef haveSeenTypeParameters As BitVector ) Select Case parameterType.Kind Case SymbolKind.TypeParameter Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol) Dim typeParameterNode As TypeParameterNode = FindTypeParameterNode(typeParameter) If typeParameterNode IsNot Nothing AndAlso Not haveSeenTypeParameters(typeParameter.Ordinal) Then If typeParameterNode.Parameter Is Nothing Then typeParameterNode.SetParameter(argNode.Parameter) End If If (isOutgoingEdge) Then AddEdge(argNode, typeParameterNode) Else AddEdge(typeParameterNode, argNode) End If haveSeenTypeParameters(typeParameter.Ordinal) = True End If Case SymbolKind.ArrayType AddTypeToGraph(DirectCast(parameterType, ArrayTypeSymbol).ElementType, argNode, isOutgoingEdge, haveSeenTypeParameters) Case SymbolKind.NamedType Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol) Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then For Each elementType In elementTypes AddTypeToGraph(elementType, argNode, isOutgoingEdge, haveSeenTypeParameters) Next Else Do For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) AddTypeToGraph(typeArgument, argNode, isOutgoingEdge, haveSeenTypeParameters) Next possiblyGenericType = possiblyGenericType.ContainingType Loop While possiblyGenericType IsNot Nothing End If End Select End Sub Private Sub AddTupleLiteralToGraph(argNode As ArgumentNode) AddTupleLiteralToGraph(argNode.ParameterType, argNode) End Sub Private Sub AddTupleLiteralToGraph( parameterType As TypeSymbol, argNode As ArgumentNode ) Debug.Assert(argNode.Expression.Kind = BoundKind.TupleLiteral) Dim tupleLiteral = DirectCast(argNode.Expression, BoundTupleLiteral) Dim tupleArguments = tupleLiteral.Arguments If parameterType.IsTupleOrCompatibleWithTupleOfCardinality(tupleArguments.Length) Then Dim parameterElementTypes = parameterType.GetElementTypesOfTupleOrCompatible For i As Integer = 0 To tupleArguments.Length - 1 RegisterArgument(tupleArguments(i), parameterElementTypes(i), argNode.Parameter) Next Return End If AddTypeToGraph(argNode, isOutgoingEdge:=True) End Sub Private Sub AddAddressOfToGraph(argNode As ArgumentNode, binder As Binder) AddAddressOfToGraph(argNode.ParameterType, argNode, binder) End Sub Private Sub AddAddressOfToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, binder As Binder ) Debug.Assert(argNode.Expression.Kind = BoundKind.AddressOfOperator) If parameterType.IsTypeParameter() Then AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length)) ElseIf parameterType.IsDelegateType() Then Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol) Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length) AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) ' outgoing (name->type) edge haveSeenTypeParameters.Clear() For Each delegateParameter As ParameterSymbol In invoke.Parameters AddTypeToGraph(delegateParameter.Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) ' incoming (type->name) edge Next End If ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T AddAddressOfToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder) End If End Sub Private Sub AddLambdaToGraph(argNode As ArgumentNode, binder As Binder) AddLambdaToGraph(argNode.ParameterType, argNode, binder) End Sub Private Sub AddLambdaToGraph( parameterType As TypeSymbol, argNode As ArgumentNode, binder As Binder ) If parameterType.IsTypeParameter() Then ' Lambda is bound to a generic typeParam, just infer anonymous delegate AddTypeToGraph(parameterType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=BitVector.Create(_typeParameterNodes.Length)) ElseIf parameterType.IsDelegateType() Then Dim delegateType As NamedTypeSymbol = DirectCast(parameterType, NamedTypeSymbol) Dim invoke As MethodSymbol = delegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso invoke.GetUseSiteInfo().DiagnosticInfo Is Nothing AndAlso delegateType.IsGenericType Then Dim delegateParameters As ImmutableArray(Of ParameterSymbol) = invoke.Parameters Dim lambdaParameters As ImmutableArray(Of ParameterSymbol) Select Case argNode.Expression.Kind Case BoundKind.QueryLambda lambdaParameters = DirectCast(argNode.Expression, BoundQueryLambda).LambdaSymbol.Parameters Case BoundKind.GroupTypeInferenceLambda lambdaParameters = DirectCast(argNode.Expression, GroupTypeInferenceLambda).Parameters Case BoundKind.UnboundLambda lambdaParameters = DirectCast(argNode.Expression, UnboundLambda).Parameters Case Else Throw ExceptionUtilities.UnexpectedValue(argNode.Expression.Kind) End Select Dim haveSeenTypeParameters = BitVector.Create(_typeParameterNodes.Length) For i As Integer = 0 To Math.Min(delegateParameters.Length, lambdaParameters.Length) - 1 Step 1 If lambdaParameters(i).Type IsNot Nothing Then ' Prepopulate the hint from the lambda's parameter. ' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic ' !!! parameter will be passed into the parameter of argument type. ' TODO: Consider using location for the type declaration. InferTypeArgumentsFromArgument( argNode.Expression.Syntax, lambdaParameters(i).Type, argumentTypeByAssumption:=False, parameterType:=delegateParameters(i).Type, param:=delegateParameters(i), digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, inferenceRestrictions:=RequiredConversion.Any) End If AddTypeToGraph(delegateParameters(i).Type, argNode, isOutgoingEdge:=False, haveSeenTypeParameters:=haveSeenTypeParameters) Next haveSeenTypeParameters.Clear() AddTypeToGraph(invoke.ReturnType, argNode, isOutgoingEdge:=True, haveSeenTypeParameters:=haveSeenTypeParameters) End If ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, binder.Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T AddLambdaToGraph(DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), argNode, binder) End If End Sub Private Shared Function ArgumentTypePossiblyMatchesParamarrayShape(argument As BoundExpression, paramType As TypeSymbol) As Boolean Dim argumentType As TypeSymbol = argument.Type Dim isArrayLiteral As Boolean = False If argumentType Is Nothing Then If argument.Kind = BoundKind.ArrayLiteral Then isArrayLiteral = True argumentType = DirectCast(argument, BoundArrayLiteral).InferredType Else Return False End If End If While paramType.IsArrayType() If Not argumentType.IsArrayType() Then Return False End If Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol) Dim paramArrayType = DirectCast(paramType, ArrayTypeSymbol) ' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches. If argumentArray.Rank <> paramArrayType.Rank OrElse (Not isArrayLiteral AndAlso argumentArray.IsSZArray <> paramArrayType.IsSZArray) Then Return False End If isArrayLiteral = False argumentType = argumentArray.ElementType paramType = paramArrayType.ElementType End While Return True End Function Public Sub RegisterTypeParameterHint( genericParameter As TypeParameterSymbol, inferredType As TypeSymbol, inferredTypeByAssumption As Boolean, argumentLocation As SyntaxNode, parameter As ParameterSymbol, inferredFromObject As Boolean, inferenceRestrictions As RequiredConversion ) Dim typeNode As TypeParameterNode = FindTypeParameterNode(genericParameter) If typeNode IsNot Nothing Then typeNode.AddTypeHint(inferredType, inferredTypeByAssumption, argumentLocation, parameter, inferredFromObject, inferenceRestrictions) End If End Sub Private Function RefersToGenericParameterToInferArgumentFor( parameterType As TypeSymbol ) As Boolean Select Case parameterType.Kind Case SymbolKind.TypeParameter Dim typeParameter = DirectCast(parameterType, TypeParameterSymbol) Dim typeNode As TypeParameterNode = FindTypeParameterNode(typeParameter) ' TODO: It looks like this check can give us a false positive. For example, ' if we are resolving a recursive call we might already bind a type ' parameter to itself (to the same type parameter of the containing method). ' So, the fact that we ran into this type parameter doesn't necessary mean ' that there is anything to infer. I am not sure if this can lead to some ' negative effect. Dev10 appears to have the same behavior, from what I see ' in the code. If typeNode IsNot Nothing Then Return True End If Case SymbolKind.ArrayType Return RefersToGenericParameterToInferArgumentFor(DirectCast(parameterType, ArrayTypeSymbol).ElementType) Case SymbolKind.NamedType Dim possiblyGenericType = DirectCast(parameterType, NamedTypeSymbol) Dim elementTypes As ImmutableArray(Of TypeSymbol) = Nothing If possiblyGenericType.TryGetElementTypesIfTupleOrCompatible(elementTypes) Then For Each elementType In elementTypes If RefersToGenericParameterToInferArgumentFor(elementType) Then Return True End If Next Else Do For Each typeArgument In possiblyGenericType.TypeArgumentsWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If RefersToGenericParameterToInferArgumentFor(typeArgument) Then Return True End If Next possiblyGenericType = possiblyGenericType.ContainingType Loop While possiblyGenericType IsNot Nothing End If End Select Return False End Function ' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments ' to a generic method, infer type arguments corresponding to type parameters that occur ' in the parameter type. ' ' A return value of false indicates that inference fails. ' ' If a generic method is parameterized by T, an argument of type A matches a parameter of type ' P, this function tries to infer type for T by using these patterns: ' ' -- If P is T, then infer A for T ' -- If P is G(Of T) and A is G(Of X), then infer X for T ' -- If P is Array Of T, and A is Array Of X, then infer X for T ' -- If P is ByRef T, then infer A for T Private Function InferTypeArgumentsFromArgumentDirectly( argumentLocation As SyntaxNode, argumentType As TypeSymbol, argumentTypeByAssumption As Boolean, parameterType As TypeSymbol, param As ParameterSymbol, digThroughToBasesAndImplements As MatchGenericArgumentToParameter, inferenceRestrictions As RequiredConversion ) As Boolean If argumentType Is Nothing OrElse argumentType.IsVoidType() Then ' We should never be able to infer a value from something that doesn't provide a value, e.g: ' Goo(Of T) can't be passed Sub bar(), as in Goo(Bar()) Return False End If ' If a generic method is parameterized by T, an argument of type A matching a parameter of type ' P can be used to infer a type for T by these patterns: ' ' -- If P is T, then infer A for T ' -- If P is G(Of T) and A is G(Of X), then infer X for T ' -- If P is Array Of T, and A is Array Of X, then infer X for T ' -- If P is ByRef T, then infer A for T ' -- If P is (T, T) and A is (X, X), then infer X for T If parameterType.IsTypeParameter() Then RegisterTypeParameterHint( DirectCast(parameterType, TypeParameterSymbol), argumentType, argumentTypeByAssumption, argumentLocation, param, False, inferenceRestrictions) Return True End If Dim parameterElementTypes As ImmutableArray(Of TypeSymbol) = Nothing Dim argumentElementTypes As ImmutableArray(Of TypeSymbol) = Nothing If parameterType.GetNullableUnderlyingTypeOrSelf().TryGetElementTypesIfTupleOrCompatible(parameterElementTypes) AndAlso If(parameterType.IsNullableType(), argumentType.GetNullableUnderlyingTypeOrSelf(), argumentType). TryGetElementTypesIfTupleOrCompatible(argumentElementTypes) Then If parameterElementTypes.Length <> argumentElementTypes.Length Then Return False End If For typeArgumentIndex As Integer = 0 To parameterElementTypes.Length - 1 Dim parameterElementType = parameterElementTypes(typeArgumentIndex) Dim argumentElementType = argumentElementTypes(typeArgumentIndex) ' propagate restrictions to the elements If Not InferTypeArgumentsFromArgument( argumentLocation, argumentElementType, argumentTypeByAssumption, parameterElementType, param, digThroughToBasesAndImplements, inferenceRestrictions ) Then Return False End If Next Return True ElseIf parameterType.Kind = SymbolKind.NamedType Then ' e.g. handle goo(of T)(x as Bar(Of T)) We need to dig into Bar(Of T) Dim parameterTypeAsNamedType = DirectCast(parameterType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol) If parameterTypeAsNamedType.IsGenericType Then Dim argumentTypeAsNamedType = If(argumentType.Kind = SymbolKind.NamedType, DirectCast(argumentType.GetTupleUnderlyingTypeOrSelf(), NamedTypeSymbol), Nothing) If argumentTypeAsNamedType IsNot Nothing AndAlso argumentTypeAsNamedType.IsGenericType Then If argumentTypeAsNamedType.OriginalDefinition.IsSameTypeIgnoringAll(parameterTypeAsNamedType.OriginalDefinition) Then Do For typeArgumentIndex As Integer = 0 To parameterTypeAsNamedType.Arity - 1 Step 1 ' The following code is subtle. Let's recap what's going on... ' We've so far encountered some context, e.g. "_" or "ICovariant(_)" ' or "ByRef _" or the like. This context will have given us some TypeInferenceRestrictions. ' Now, inside the context, we've discovered a generic binding "G(Of _,_,_)" ' and we have to apply extra restrictions to each of those subcontexts. ' For non-variant parameters it's easy: the subcontexts just acquire the Identity constraint. ' For variant parameters it's more subtle. First, we have to strengthen the ' restrictions to require reference conversion (rather than just VB conversion or ' whatever it was). Second, if it was an In parameter, then we have to invert ' the sense. ' ' Processing of generics is tricky in the case that we've already encountered ' a "ByRef _". From that outer "ByRef _" we will have inferred the restriction ' "AnyConversionAndReverse", so that the argument could be copied into the parameter ' and back again. But now consider if we find a generic inside that ByRef, e.g. ' if it had been "ByRef x as G(Of T)" then what should we do? More specifically, consider a case ' "Sub f(Of T)(ByRef x as G(Of T))" invoked with some "dim arg as G(Of Hint)". ' What's needed for any candidate for T is that G(Of Hint) be convertible to ' G(Of Candidate), and vice versa for the copyback. ' ' But then what should we write down for the hints? The problem is that hints inhere ' to the generic parameter T, not to the function parameter G(Of T). So we opt for a ' safe approximation: we just require CLR identity between a candidate and the hint. ' This is safe but is a little overly-strict. For example: ' Class G(Of T) ' Public Shared Widening Operator CType(ByVal x As G(Of T)) As G(Of Animal) ' Public Shared Widening Operator CType(ByVal x As G(Of Animal)) As G(Of T) ' Sub inf(Of T)(ByRef x as G(Of T), ByVal y as T) ' ... ' inf(New G(Of Car), New Animal) ' inf(Of Animal)(New G(Of Car), New Animal) ' Then the hints will be "T:{Car=, Animal+}" and they'll result in inference-failure, ' even though the explicitly-provided T=Animal ends up working. ' ' Well, it's the best we can do without some major re-architecting of the way ' hints and type-inference works. That's because all our hints inhere to the ' type parameter T; in an ideal world, the ByRef hint would inhere to the parameter. ' But I don't think we'll ever do better than this, just because trying to do ' type inference inferring to arguments/parameters becomes exponential. ' Variance generic parameters will work the same. ' Dev10#595234: each Param'sInferenceRestriction is found as a modification of the surrounding InferenceRestriction: Dim paramInferenceRestrictions As RequiredConversion Select Case parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance Case VarianceKind.In paramInferenceRestrictions = Conversions.InvertConversionRequirement( Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions)) Case VarianceKind.Out paramInferenceRestrictions = Conversions.StrengthenConversionRequirementToReference(inferenceRestrictions) Case Else Debug.Assert(VarianceKind.None = parameterTypeAsNamedType.TypeParameters(typeArgumentIndex).Variance) paramInferenceRestrictions = RequiredConversion.Identity End Select Dim _DigThroughToBasesAndImplements As MatchGenericArgumentToParameter If paramInferenceRestrictions = RequiredConversion.Reference Then _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter ElseIf paramInferenceRestrictions = RequiredConversion.ReverseReference Then _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter Else _DigThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly End If If Not InferTypeArgumentsFromArgument( argumentLocation, argumentTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo), argumentTypeByAssumption, parameterTypeAsNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(typeArgumentIndex, Me.UseSiteInfo), param, _DigThroughToBasesAndImplements, paramInferenceRestrictions ) Then ' TODO: Would it make sense to continue through other type arguments even if inference failed for ' the current one? Return False End If Next ' Do not forget about type parameters of containing type parameterTypeAsNamedType = parameterTypeAsNamedType.ContainingType argumentTypeAsNamedType = argumentTypeAsNamedType.ContainingType Loop While parameterTypeAsNamedType IsNot Nothing Debug.Assert(parameterTypeAsNamedType Is Nothing AndAlso argumentTypeAsNamedType Is Nothing) Return True End If ElseIf parameterTypeAsNamedType.IsNullableType() Then ' we reach here when the ParameterType is an instantiation of Nullable, ' and the argument type is NOT a generic type. ' lwischik: ??? what do array elements have to do with nullables? Return InferTypeArgumentsFromArgument( argumentLocation, argumentType, argumentTypeByAssumption, parameterTypeAsNamedType.GetNullableUnderlyingType(), param, digThroughToBasesAndImplements, Conversions.CombineConversionRequirements(inferenceRestrictions, RequiredConversion.ArrayElement)) End If Return False End If ElseIf parameterType.IsArrayType() Then If argumentType.IsArrayType() Then Dim parameterArray = DirectCast(parameterType, ArrayTypeSymbol) Dim argumentArray = DirectCast(argumentType, ArrayTypeSymbol) Dim argumentIsAarrayLiteral = TypeOf argumentArray Is ArrayLiteralTypeSymbol ' We can ignore IsSZArray value for an inferred type of an array literal as long as its rank matches. If parameterArray.Rank = argumentArray.Rank AndAlso (argumentIsAarrayLiteral OrElse parameterArray.IsSZArray = argumentArray.IsSZArray) Then Return InferTypeArgumentsFromArgument( argumentLocation, argumentArray.ElementType, argumentTypeByAssumption, parameterArray.ElementType, param, digThroughToBasesAndImplements, Conversions.CombineConversionRequirements(inferenceRestrictions, If(argumentIsAarrayLiteral, RequiredConversion.Any, RequiredConversion.ArrayElement))) End If End If Return False End If Return True End Function ' Given an argument type, a parameter type, and a set of (possibly unbound) type arguments ' to a generic method, infer type arguments corresponding to type parameters that occur ' in the parameter type. ' ' A return value of false indicates that inference fails. ' ' This routine is given an argument e.g. "List(Of IEnumerable(Of Int))", ' and a parameter e.g. "IEnumerable(Of IEnumerable(Of T))". ' The task is to infer hints for T, e.g. "T=int". ' This function takes care of allowing (in this example) List(Of _) to match IEnumerable(Of _). ' As for the real work, i.e. matching the contents, we invoke "InferTypeArgumentsFromArgumentDirectly" ' to do that. ' ' Note: this function returns "false" if it failed to pattern-match between argument and parameter type, ' and "true" if it succeeded. ' Success in pattern-matching may or may not produce type-hints for generic parameters. ' If it happened not to produce any type-hints, then maybe other argument/parameter pairs will have produced ' their own type hints that allow inference to succeed, or maybe no-one else will have produced type hints, ' or maybe other people will have produced conflicting type hints. In those cases, we'd return True from ' here (to show success at pattern-matching) and leave the downstream code to produce an error message about ' failing to infer T. Friend Function InferTypeArgumentsFromArgument( argumentLocation As SyntaxNode, argumentType As TypeSymbol, argumentTypeByAssumption As Boolean, parameterType As TypeSymbol, param As ParameterSymbol, digThroughToBasesAndImplements As MatchGenericArgumentToParameter, inferenceRestrictions As RequiredConversion ) As Boolean If Not RefersToGenericParameterToInferArgumentFor(parameterType) Then Return True End If ' First try to the things directly. Only if this fails will we bother searching for things like List->IEnumerable. Dim Inferred As Boolean = InferTypeArgumentsFromArgumentDirectly( argumentLocation, argumentType, argumentTypeByAssumption, parameterType, param, digThroughToBasesAndImplements, inferenceRestrictions) If Inferred Then Return True End If If parameterType.IsTypeParameter() Then ' If we failed to match an argument against a generic parameter T, it means that the ' argument was something unmatchable, e.g. an AddressOf. Return False End If ' If we didn't find a direct match, we will have to look in base classes for a match. ' We'll either fix ParameterType and look amongst the bases of ArgumentType, ' or we'll fix ArgumentType and look amongst the bases of ParameterType, ' depending on the "DigThroughToBasesAndImplements" flag. This flag is affected by ' covariance and contravariance... If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchGenericArgumentToParameterExactly Then Return False End If ' Special handling for Anonymous Delegates. If argumentType IsNot Nothing AndAlso argumentType.IsDelegateType() AndAlso parameterType.IsDelegateType() AndAlso digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter AndAlso (inferenceRestrictions = RequiredConversion.Any OrElse inferenceRestrictions = RequiredConversion.AnyReverse OrElse inferenceRestrictions = RequiredConversion.AnyAndReverse) Then Dim argumentDelegateType = DirectCast(argumentType, NamedTypeSymbol) Dim argumentInvokeProc As MethodSymbol = argumentDelegateType.DelegateInvokeMethod Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol) Dim parameterInvokeProc As MethodSymbol = parameterDelegateType.DelegateInvokeMethod Debug.Assert(argumentInvokeProc IsNot Nothing OrElse Not argumentDelegateType.IsAnonymousType) ' Note, null check for parameterInvokeDeclaration should also filter out MultiCastDelegate type. If argumentDelegateType.IsAnonymousType AndAlso Not parameterDelegateType.IsAnonymousType AndAlso parameterInvokeProc IsNot Nothing AndAlso parameterInvokeProc.GetUseSiteInfo().DiagnosticInfo Is Nothing Then ' Some trickery relating to the fact that anonymous delegates can be converted to any delegate type. ' We are trying to match the anonymous delegate "BaseSearchType" onto the delegate "FixedType". e.g. ' Dim f = function(i as integer) i // ArgumentType = VB$AnonymousDelegate`2(Of Integer,Integer) ' inf(f) // ParameterType might be e.g. D(Of T) for some function inf(Of T)(f as D(Of T)) ' // maybe defined as Delegate Function D(Of T)(x as T) as T. ' We're looking to achieve the same functionality in pattern-matching these types as we already ' have for calling "inf(function(i as integer) i)" directly. ' It allows any VB conversion from param-of-fixed-type to param-of-base-type (not just reference conversions). ' But it does allow a zero-argument BaseSearchType to be used for a FixedType with more. ' And it does allow a function BaseSearchType to be used for a sub FixedType. ' ' Anyway, the plan is to match each of the parameters in the ArgumentType delegate ' to the equivalent parameters in the ParameterType delegate, and also match the return types. ' ' This only works for "ConversionRequired::Any", i.e. using VB conversion semantics. It doesn't work for ' reference conversions. As for the AnyReverse/AnyAndReverse, well, in Orcas that was guaranteed ' to fail type inference (i.e. return a false from this function). In Dev10 we will let it succeed ' with some inferred types, for the sake of better error messages, even though we know that ultimately ' it will fail (because no non-anonymous delegate type can be converted to a delegate type). Dim argumentParams As ImmutableArray(Of ParameterSymbol) = argumentInvokeProc.Parameters Dim parameterParams As ImmutableArray(Of ParameterSymbol) = parameterInvokeProc.Parameters If parameterParams.Length <> argumentParams.Length AndAlso argumentParams.Length <> 0 Then ' If parameter-counts are mismatched then it's a failure. ' Exception: Zero-argument relaxation: we allow a parameterless VB$AnonymousDelegate argument ' to be supplied to a function which expects a parameterfull delegate. Return False End If ' First we'll check that the argument types all match. For i As Integer = 0 To argumentParams.Length - 1 If argumentParams(i).IsByRef <> parameterParams(i).IsByRef Then ' Require an exact match between ByRef/ByVal, since that's how type inference of lambda expressions works. Return False End If If Not InferTypeArgumentsFromArgument( argumentLocation, argumentParams(i).Type, argumentTypeByAssumption, parameterParams(i).Type, param, MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, RequiredConversion.AnyReverse) Then ' AnyReverse: contravariance in delegate arguments Return False End If Next ' Now check that the return type matches. ' Note: we allow a *function* VB$AnonymousDelegate to be supplied to a function which expects a *sub* delegate. If parameterInvokeProc.IsSub Then ' A *sub* delegate parameter can accept either a *function* or a *sub* argument: Return True ElseIf argumentInvokeProc.IsSub Then ' A *function* delegate parameter cannot accept a *sub* argument. Return False Else ' Otherwise, a function argument VB$AnonymousDelegate was supplied to a function parameter: Return InferTypeArgumentsFromArgument( argumentLocation, argumentInvokeProc.ReturnType, argumentTypeByAssumption, parameterInvokeProc.ReturnType, param, MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, RequiredConversion.Any) ' Any: covariance in delegate returns End If End If End If ' MatchBaseOfGenericArgumentToParameter: used for covariant situations, ' e.g. matching argument "List(Of _)" to parameter "ByVal x as IEnumerable(Of _)". ' ' Otherwise, MatchArgumentToBaseOfGenericParameter, used for contravariant situations, ' e.g. when matching argument "Action(Of IEnumerable(Of _))" to parameter "ByVal x as Action(Of List(Of _))". Dim fContinue As Boolean = False If digThroughToBasesAndImplements = MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter Then fContinue = FindMatchingBase(argumentType, parameterType) Else fContinue = FindMatchingBase(parameterType, argumentType) End If If Not fContinue Then Return False End If ' NOTE: baseSearchType was a REFERENCE, to either ArgumentType or ParameterType. ' Therefore the above statement has altered either ArgumentType or ParameterType. Return InferTypeArgumentsFromArgumentDirectly( argumentLocation, argumentType, argumentTypeByAssumption, parameterType, param, digThroughToBasesAndImplements, inferenceRestrictions) End Function Private Function FindMatchingBase( ByRef baseSearchType As TypeSymbol, ByRef fixedType As TypeSymbol ) As Boolean Dim fixedTypeAsNamedType = If(fixedType.Kind = SymbolKind.NamedType, DirectCast(fixedType, NamedTypeSymbol), Nothing) If fixedTypeAsNamedType Is Nothing OrElse Not fixedTypeAsNamedType.IsGenericType Then ' If the fixed candidate isn't a generic (e.g. matching argument IList(Of String) to non-generic parameter IList), ' then we won't learn anything about generic type parameters here: Return False End If Dim fixedTypeTypeKind As TypeKind = fixedType.TypeKind If fixedTypeTypeKind <> TypeKind.Class AndAlso fixedTypeTypeKind <> TypeKind.Interface Then ' Whatever "BaseSearchType" is, it can only inherit from "FixedType" if FixedType is a class/interface. ' (it's impossible to inherit from anything else). Return False End If Dim baseSearchTypeKind As SymbolKind = baseSearchType.Kind If baseSearchTypeKind <> SymbolKind.NamedType AndAlso baseSearchTypeKind <> SymbolKind.TypeParameter AndAlso Not (baseSearchTypeKind = SymbolKind.ArrayType AndAlso DirectCast(baseSearchType, ArrayTypeSymbol).IsSZArray) Then ' The things listed above are the only ones that have bases that could ever lead anywhere useful. ' NamedType is satisfied by interfaces, structures, enums, delegates and modules as well as just classes. Return False End If If baseSearchType.IsSameTypeIgnoringAll(fixedType) Then ' If the types checked were already identical, then exit Return False End If ' Otherwise, if we got through all the above tests, then it really is worth searching through the base ' types to see if that helps us find a match. Dim matchingBase As TypeSymbol = Nothing If fixedTypeTypeKind = TypeKind.Class Then FindMatchingBaseClass(baseSearchType, fixedType, matchingBase) Else Debug.Assert(fixedTypeTypeKind = TypeKind.Interface) FindMatchingBaseInterface(baseSearchType, fixedType, matchingBase) End If If matchingBase Is Nothing Then Return False End If ' And this is what we found baseSearchType = matchingBase Return True End Function Private Shared Function SetMatchIfNothingOrEqual(type As TypeSymbol, ByRef match As TypeSymbol) As Boolean If match Is Nothing Then match = type Return True ElseIf match.IsSameTypeIgnoringAll(type) Then Return True Else match = Nothing Return False End If End Function ''' <summary> ''' Returns False if the search should be cancelled. ''' </summary> Private Function FindMatchingBaseInterface(derivedType As TypeSymbol, baseInterface As TypeSymbol, ByRef match As TypeSymbol) As Boolean Select Case derivedType.Kind Case SymbolKind.TypeParameter For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(constraint, match) Then Return False End If End If If Not FindMatchingBaseInterface(constraint, baseInterface, match) Then Return False End If Next Case Else For Each [interface] In derivedType.AllInterfacesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If [interface].OriginalDefinition.IsSameTypeIgnoringAll(baseInterface.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual([interface], match) Then Return False End If End If Next End Select Return True End Function ''' <summary> ''' Returns False if the search should be cancelled. ''' </summary> Private Function FindMatchingBaseClass(derivedType As TypeSymbol, baseClass As TypeSymbol, ByRef match As TypeSymbol) As Boolean Select Case derivedType.Kind Case SymbolKind.TypeParameter For Each constraint In DirectCast(derivedType, TypeParameterSymbol).ConstraintTypesWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) If constraint.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(constraint, match) Then Return False End If End If ' TODO: Do we need to continue even if we already have a matching base class? ' It looks like Dev10 continues. If Not FindMatchingBaseClass(constraint, baseClass, match) Then Return False End If Next Case Else Dim baseType As NamedTypeSymbol = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) While baseType IsNot Nothing If baseType.OriginalDefinition.IsSameTypeIgnoringAll(baseClass.OriginalDefinition) Then If Not SetMatchIfNothingOrEqual(baseType, match) Then Return False End If Exit While End If baseType = baseType.BaseTypeWithDefinitionUseSiteDiagnostics(Me.UseSiteInfo) End While End Select Return True End Function Public Function InferTypeArgumentsFromAddressOfArgument( argument As BoundExpression, parameterType As TypeSymbol, param As ParameterSymbol ) As Boolean If parameterType.IsDelegateType() Then Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterType), NamedTypeSymbol) ' Now find the invoke method of the delegate Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then ' If we don't have an Invoke method, just bail. Return False End If Dim returnType As TypeSymbol = invokeMethod.ReturnType ' If the return type doesn't refer to parameters, no inference required. If Not RefersToGenericParameterToInferArgumentFor(returnType) Then Return True End If Dim addrOf = DirectCast(argument, BoundAddressOfOperator) Dim fromMethod As MethodSymbol = Nothing Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = Binder.ResolveMethodForDelegateInvokeFullAndRelaxed( addrOf, invokeMethod, ignoreMethodReturnType:=True, diagnostics:=BindingDiagnosticBag.Discarded) fromMethod = matchingMethod.Key methodConversions = matchingMethod.Value If fromMethod Is Nothing OrElse (methodConversions And MethodConversionKind.AllErrorReasons) <> 0 OrElse (addrOf.Binder.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=True)) Then Return False End If If fromMethod.IsSub Then ReportNotFailedInferenceDueToObject() Return True End If Dim targetReturnType As TypeSymbol = fromMethod.ReturnType If RefersToGenericParameterToInferArgumentFor(targetReturnType) Then ' Return false if we didn't make any inference progress. Return False End If Return InferTypeArgumentsFromArgument( argument.Syntax, targetReturnType, argumentTypeByAssumption:=False, parameterType:=returnType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) End If ' We did not infer anything for this addressOf, AddressOf can never be of type Object, so mark inference ' as not failed due to object. ReportNotFailedInferenceDueToObject() Return True End Function Public Function InferTypeArgumentsFromLambdaArgument( argument As BoundExpression, parameterType As TypeSymbol, param As ParameterSymbol ) As Boolean Debug.Assert(argument.Kind = BoundKind.UnboundLambda OrElse argument.Kind = BoundKind.QueryLambda OrElse argument.Kind = BoundKind.GroupTypeInferenceLambda) If parameterType.IsTypeParameter() Then Dim anonymousLambdaType As TypeSymbol = Nothing Select Case argument.Kind Case BoundKind.QueryLambda ' Do not infer Anonymous Delegate type from query lambda. Case BoundKind.GroupTypeInferenceLambda ' Can't infer from this lambda. Case BoundKind.UnboundLambda ' Infer Anonymous Delegate type from unbound lambda. Dim inferredAnonymousDelegate As KeyValuePair(Of NamedTypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = DirectCast(argument, UnboundLambda).InferredAnonymousDelegate If (inferredAnonymousDelegate.Value.Diagnostics.IsDefault OrElse Not inferredAnonymousDelegate.Value.Diagnostics.HasAnyErrors()) Then Dim delegateInvokeMethod As MethodSymbol = Nothing If inferredAnonymousDelegate.Key IsNot Nothing Then delegateInvokeMethod = inferredAnonymousDelegate.Key.DelegateInvokeMethod End If If delegateInvokeMethod IsNot Nothing AndAlso delegateInvokeMethod.ReturnType IsNot LambdaSymbol.ReturnTypeIsUnknown Then anonymousLambdaType = inferredAnonymousDelegate.Key End If End If Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select If anonymousLambdaType IsNot Nothing Then Return InferTypeArgumentsFromArgument( argument.Syntax, anonymousLambdaType, argumentTypeByAssumption:=False, parameterType:=parameterType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) Else Return True End If ElseIf parameterType.IsDelegateType() Then Dim parameterDelegateType = DirectCast(parameterType, NamedTypeSymbol) ' First, we need to build a partial type substitution using the type of ' arguments as they stand right now, with some of them still being uninferred. ' TODO: Doesn't this make the inference algorithm order dependent? For example, if we were to ' infer more stuff from other non-lambda arguments, we might have a better chance to have ' more type information for the lambda, allowing successful lambda interpretation. ' Perhaps the graph doesn't allow us to get here until all "inputs" for lambda parameters ' are inferred. Dim delegateType = DirectCast(ConstructParameterTypeIfNeeded(parameterDelegateType), NamedTypeSymbol) ' Now find the invoke method of the delegate Dim invokeMethod As MethodSymbol = delegateType.DelegateInvokeMethod If invokeMethod Is Nothing OrElse invokeMethod.GetUseSiteInfo().DiagnosticInfo IsNot Nothing Then ' If we don't have an Invoke method, just bail. Return True End If Dim returnType As TypeSymbol = invokeMethod.ReturnType ' If the return type doesn't refer to parameters, no inference required. If Not RefersToGenericParameterToInferArgumentFor(returnType) Then Return True End If Dim lambdaParams As ImmutableArray(Of ParameterSymbol) Select Case argument.Kind Case BoundKind.QueryLambda lambdaParams = DirectCast(argument, BoundQueryLambda).LambdaSymbol.Parameters Case BoundKind.GroupTypeInferenceLambda lambdaParams = DirectCast(argument, GroupTypeInferenceLambda).Parameters Case BoundKind.UnboundLambda lambdaParams = DirectCast(argument, UnboundLambda).Parameters Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select Dim delegateParams As ImmutableArray(Of ParameterSymbol) = invokeMethod.Parameters If lambdaParams.Length > delegateParams.Length Then Return True End If For i As Integer = 0 To lambdaParams.Length - 1 Step 1 Dim lambdaParam As ParameterSymbol = lambdaParams(i) Dim delegateParam As ParameterSymbol = delegateParams(i) If lambdaParam.Type Is Nothing Then ' If a lambda parameter has no type and the delegate parameter refers ' to an unbound generic parameter, we can't infer yet. If RefersToGenericParameterToInferArgumentFor(delegateParam.Type) Then ' Skip this type argument and other parameters will infer it or ' if that doesn't happen it will report an error. ' TODO: Why does it make sense to continue here? It looks like we can infer something from ' lambda's return type based on incomplete information. Also, this 'if' is redundant, ' there is nothing left to do in this loop anyway, and "continue" doesn't change anything. Continue For End If Else ' report the type of the lambda parameter to the delegate parameter. ' !!! Unlike Dev10, we are using MatchArgumentToBaseOfGenericParameter because a value of generic ' !!! parameter will be passed into the parameter of argument type. InferTypeArgumentsFromArgument( argument.Syntax, lambdaParam.Type, argumentTypeByAssumption:=False, parameterType:=delegateParam.Type, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchArgumentToBaseOfGenericParameter, inferenceRestrictions:=RequiredConversion.Any) End If Next ' OK, now try to infer delegates return type from the lambda. Dim lambdaReturnType As TypeSymbol Select Case argument.Kind Case BoundKind.QueryLambda Dim queryLambda = DirectCast(argument, BoundQueryLambda) lambdaReturnType = queryLambda.LambdaSymbol.ReturnType If lambdaReturnType Is LambdaSymbol.ReturnTypePendingDelegate Then lambdaReturnType = queryLambda.Expression.Type If lambdaReturnType Is Nothing Then If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Debug.Assert(Me.Diagnostic IsNot Nothing) lambdaReturnType = queryLambda.LambdaSymbol.ContainingBinder.MakeRValue(queryLambda.Expression, Me.Diagnostic).Type End If End If Case BoundKind.GroupTypeInferenceLambda lambdaReturnType = DirectCast(argument, GroupTypeInferenceLambda).InferLambdaReturnType(delegateParams) Case BoundKind.UnboundLambda Dim unboundLambda = DirectCast(argument, UnboundLambda) If unboundLambda.IsFunctionLambda Then Dim inferenceSignature As New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False) Dim returnTypeInfo As KeyValuePair(Of TypeSymbol, ImmutableBindingDiagnostic(Of AssemblySymbol)) = unboundLambda.InferReturnType(inferenceSignature) If Not returnTypeInfo.Value.Diagnostics.IsDefault AndAlso returnTypeInfo.Value.Diagnostics.HasAnyErrors() Then lambdaReturnType = Nothing ' Let's keep return type inference errors If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(returnTypeInfo.Value) ElseIf returnTypeInfo.Key Is LambdaSymbol.ReturnTypeIsUnknown Then lambdaReturnType = Nothing Else Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(inferenceSignature.ParameterTypes, inferenceSignature.ParameterIsByRef, returnTypeInfo.Key, returnsByRef:=False)) Debug.Assert(boundLambda.LambdaSymbol.ReturnType Is returnTypeInfo.Key) If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors Then lambdaReturnType = returnTypeInfo.Key ' Let's keep return type inference warnings, if any. If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(returnTypeInfo.Value) Me.Diagnostic.AddDependencies(boundLambda.Diagnostics.Dependencies) Else lambdaReturnType = Nothing ' Let's preserve diagnostics that caused the failure If Not boundLambda.Diagnostics.Diagnostics.IsDefaultOrEmpty Then If Me.Diagnostic Is Nothing Then Me.Diagnostic = BindingDiagnosticBag.Create(withDiagnostics:=True, Me.UseSiteInfo.AccumulatesDependencies) End If Me.Diagnostic.AddRange(boundLambda.Diagnostics) End If End If End If ' But in the case of async/iterator lambdas, e.g. pass "Async Function() 1" to a parameter ' of type "Func(Of Task(Of T))" then we have to dig in further and match 1 to T... If (unboundLambda.Flags And (SourceMemberFlags.Async Or SourceMemberFlags.Iterator)) <> 0 AndAlso lambdaReturnType IsNot Nothing AndAlso lambdaReturnType.Kind = SymbolKind.NamedType AndAlso returnType IsNot Nothing AndAlso returnType.Kind = SymbolKind.NamedType Then ' By this stage we know that ' * we have an async/iterator lambda argument ' * the parameter-to-match is a delegate type whose result type refers to generic parameters ' The parameter might be a delegate with result type e.g. "Task(Of T)" in which case we have ' to dig in. Or it might be a delegate with result type "T" in which case we ' don't dig in. Dim lambdaReturnNamedType = DirectCast(lambdaReturnType, NamedTypeSymbol) Dim returnNamedType = DirectCast(returnType, NamedTypeSymbol) If lambdaReturnNamedType.Arity = 1 AndAlso IsSameTypeIgnoringAll(lambdaReturnNamedType.OriginalDefinition, returnNamedType.OriginalDefinition) Then ' We can assume that the lambda will have return type Task(Of T) or IEnumerable(Of T) ' or IEnumerator(Of T) as appropriate. That's already been ensured by the lambda-interpretation. Debug.Assert(TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T), TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T), TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(lambdaReturnNamedType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerator_T), TypeCompareKind.ConsiderEverything)) lambdaReturnType = lambdaReturnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo) returnType = returnNamedType.TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo) End If End If Else lambdaReturnType = Nothing If Not invokeMethod.IsSub AndAlso (unboundLambda.Flags And SourceMemberFlags.Async) <> 0 Then Dim boundLambda As BoundLambda = unboundLambda.Bind(New UnboundLambda.TargetSignature(delegateParams, unboundLambda.Binder.Compilation.GetSpecialType(SpecialType.System_Void), returnsByRef:=False)) If Not boundLambda.HasErrors AndAlso Not boundLambda.Diagnostics.Diagnostics.HasAnyErrors() Then If _asyncLambdaSubToFunctionMismatch Is Nothing Then _asyncLambdaSubToFunctionMismatch = New HashSet(Of BoundExpression)(ReferenceEqualityComparer.Instance) End If _asyncLambdaSubToFunctionMismatch.Add(unboundLambda) End If End If End If Case Else Throw ExceptionUtilities.UnexpectedValue(argument.Kind) End Select If lambdaReturnType Is Nothing Then ' Inference failed, give up. Return False End If If lambdaReturnType.IsErrorType() Then Return True End If ' Now infer from the result type ' not ArgumentTypeByAssumption ??? lwischik: but maybe it should... Return InferTypeArgumentsFromArgument( argument.Syntax, lambdaReturnType, argumentTypeByAssumption:=False, parameterType:=returnType, param:=param, digThroughToBasesAndImplements:=MatchGenericArgumentToParameter.MatchBaseOfGenericArgumentToParameter, inferenceRestrictions:=RequiredConversion.Any) ElseIf TypeSymbol.Equals(parameterType.OriginalDefinition, argument.GetBinderFromLambda().Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T), TypeCompareKind.ConsiderEverything) Then ' If we've got an Expression(Of T), skip through to T Return InferTypeArgumentsFromLambdaArgument(argument, DirectCast(parameterType, NamedTypeSymbol).TypeArgumentWithDefinitionUseSiteDiagnostics(0, Me.UseSiteInfo), param) End If Return True End Function Public Function ConstructParameterTypeIfNeeded(parameterType As TypeSymbol) As TypeSymbol ' First, we need to build a partial type substitution using the type of ' arguments as they stand right now, with some of them still being uninferred. Dim methodSymbol As MethodSymbol = Candidate Dim typeArguments = ArrayBuilder(Of TypeWithModifiers).GetInstance(_typeParameterNodes.Length) For i As Integer = 0 To _typeParameterNodes.Length - 1 Step 1 Dim typeNode As TypeParameterNode = _typeParameterNodes(i) Dim newType As TypeSymbol If typeNode Is Nothing OrElse typeNode.CandidateInferredType Is Nothing Then 'No substitution newType = methodSymbol.TypeParameters(i) Else newType = typeNode.CandidateInferredType End If typeArguments.Add(New TypeWithModifiers(newType)) Next Dim partialSubstitution = TypeSubstitution.CreateAdditionalMethodTypeParameterSubstitution(methodSymbol.ConstructedFrom, typeArguments.ToImmutableAndFree()) ' Now we apply the partial substitution to the delegate type, leaving uninferred type parameters as is Return parameterType.InternalSubstituteTypeParameters(partialSubstitution).Type End Function Public Sub ReportAmbiguousInferenceError(typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference)) Debug.Assert(typeInfos.Count() >= 2, "Must have at least 2 elements in the list") ' Since they get added fifo, we need to walk the list backward. For i As Integer = 1 To typeInfos.Count - 1 Step 1 Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i) If Not currentTypeInfo.InferredFromObject Then ReportNotFailedInferenceDueToObject() ' TODO: Should we exit the loop? For some reason Dev10 keeps going. End If Next End Sub Public Sub ReportIncompatibleInferenceError( typeInfos As ArrayBuilder(Of DominantTypeDataTypeInference)) If typeInfos.Count < 1 Then Return End If ' Since they get added fifo, we need to walk the list backward. For i As Integer = 1 To typeInfos.Count - 1 Step 1 Dim currentTypeInfo As DominantTypeDataTypeInference = typeInfos(i) If Not currentTypeInfo.InferredFromObject Then ReportNotFailedInferenceDueToObject() ' TODO: Should we exit the loop? For some reason Dev10 keeps going. End If Next End Sub Public Sub RegisterErrorReasons(inferenceErrorReasons As InferenceErrorReasons) _inferenceErrorReasons = _inferenceErrorReasons Or inferenceErrorReasons End Sub End Class End Class End Namespace
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/VisualStudio/Core/Def/Implementation/ChangeSignature/AddParameterDialog.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Windows; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { /// <summary> /// Interaction logic for AddParameterDialog.xaml /// </summary> internal partial class AddParameterDialog : DialogWindow { private readonly AddParameterDialogViewModel _viewModel; public string OK { get { return ServicesVSResources.OK; } } public string Cancel { get { return ServicesVSResources.Cancel; } } public string ParameterInformation { get { return ServicesVSResources.Parameter_information; } } public string TypeNameLabel { get { return ServicesVSResources.Type_Name; } } public string ParameterNameLabel { get { return ServicesVSResources.Parameter_Name; } } public string CallSiteValueLabel { get { return ServicesVSResources.Call_site_value; } } public string AddParameterDialogTitle { get { return ServicesVSResources.Add_Parameter; } } public string ParameterKind { get { return ServicesVSResources.Parameter_kind; } } public string Required { get { return ServicesVSResources.Required; } } public string OptionalWithDefaultValue { get { return ServicesVSResources.Optional_with_default_value_colon; } } public string ValueToInjectAtCallsites { get { return ServicesVSResources.Value_to_inject_at_call_sites; } } public string Value { get { return ServicesVSResources.Value_colon; } } public string UseNamedArgument { get { return ServicesVSResources.Use_named_argument; } } public string IntroduceUndefinedTodoVariables { get { return ServicesVSResources.IntroduceUndefinedTodoVariables; } } public string OmitOnlyForOptionalParameters { get { return ServicesVSResources.Omit_only_for_optional_parameters; } } public string InferFromContext { get { return ServicesVSResources.Infer_from_context; } } public AddParameterDialog(AddParameterDialogViewModel viewModel) { _viewModel = viewModel; this.Loaded += AddParameterDialog_Loaded; DataContext = _viewModel; InitializeComponent(); } private void AddParameterDialog_Loaded(object sender, RoutedEventArgs e) { MinHeight = Height; TypeContentControl.Focus(); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); // Workaround WPF bug: https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1101094 DataContext = null; } private void OK_Click(object sender, RoutedEventArgs e) { if (_viewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) { DialogResult = false; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AddParameterDialog _dialog; public TestAccessor(AddParameterDialog dialog) { _dialog = dialog; } public DialogButton OKButton => _dialog.OKButton; public DialogButton CancelButton => _dialog.CancelButton; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Windows; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { /// <summary> /// Interaction logic for AddParameterDialog.xaml /// </summary> internal partial class AddParameterDialog : DialogWindow { private readonly AddParameterDialogViewModel _viewModel; public string OK { get { return ServicesVSResources.OK; } } public string Cancel { get { return ServicesVSResources.Cancel; } } public string ParameterInformation { get { return ServicesVSResources.Parameter_information; } } public string TypeNameLabel { get { return ServicesVSResources.Type_Name; } } public string ParameterNameLabel { get { return ServicesVSResources.Parameter_Name; } } public string CallSiteValueLabel { get { return ServicesVSResources.Call_site_value; } } public string AddParameterDialogTitle { get { return ServicesVSResources.Add_Parameter; } } public string ParameterKind { get { return ServicesVSResources.Parameter_kind; } } public string Required { get { return ServicesVSResources.Required; } } public string OptionalWithDefaultValue { get { return ServicesVSResources.Optional_with_default_value_colon; } } public string ValueToInjectAtCallsites { get { return ServicesVSResources.Value_to_inject_at_call_sites; } } public string Value { get { return ServicesVSResources.Value_colon; } } public string UseNamedArgument { get { return ServicesVSResources.Use_named_argument; } } public string IntroduceUndefinedTodoVariables { get { return ServicesVSResources.IntroduceUndefinedTodoVariables; } } public string OmitOnlyForOptionalParameters { get { return ServicesVSResources.Omit_only_for_optional_parameters; } } public string InferFromContext { get { return ServicesVSResources.Infer_from_context; } } public AddParameterDialog(AddParameterDialogViewModel viewModel) { _viewModel = viewModel; this.Loaded += AddParameterDialog_Loaded; DataContext = _viewModel; InitializeComponent(); } private void AddParameterDialog_Loaded(object sender, RoutedEventArgs e) { MinHeight = Height; TypeContentControl.Focus(); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); // Workaround WPF bug: https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1101094 DataContext = null; } private void OK_Click(object sender, RoutedEventArgs e) { if (_viewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) { DialogResult = false; } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AddParameterDialog _dialog; public TestAccessor(AddParameterDialog dialog) { _dialog = dialog; } public DialogButton OKButton => _dialog.OKButton; public DialogButton CancelButton => _dialog.CancelButton; } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/EditorFeatures/VisualBasicTest/Diagnostics/AddImport/AddImportTests_NuGet.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.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Packaging Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.VisualBasic.AddImport Imports Moq Imports ProviderData = System.Tuple(Of Microsoft.CodeAnalysis.Packaging.IPackageInstallerService, Microsoft.CodeAnalysis.SymbolSearch.ISymbolSearchService) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImport <Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Class AddImportNuGetTests Inherits AbstractAddImportTests Private Const NugetOrgSource = "nuget.org" Private Shared ReadOnly NuGetPackageSources As ImmutableArray(Of PackageSource) = ImmutableArray.Create(New PackageSource(NugetOrgSource, "http://nuget.org")) Protected Overrides Sub InitializeWorkspace(workspace As TestWorkspace, parameters As TestParameters) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options. WithChangedOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic, True). WithChangedOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic, True))) End Sub Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) ' This is used by inherited tests to ensure the properties of diagnostic analyzers are correct. It's not ' needed by the tests in this class, but can't throw an exception. Return (Nothing, Nothing) End Function Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, parameters As TestParameters) As (DiagnosticAnalyzer, CodeFixProvider) Dim data = DirectCast(parameters.fixProviderData, ProviderData) Return (Nothing, New VisualBasicAddImportCodeFixProvider(data.Item1, data.Item2)) End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact> Public Async Function TestSearchPackageSingleName() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestSearchPackageMultipleNames() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NS1.NS2 Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestFailedInstallDoesNotChangeFile() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(False) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestMissingIfPackageAlreadyInstalled() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.IsInstalled(It.IsAny(Of Workspace)(), It.IsAny(Of ProjectId)(), "NuGetPackage")). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestMissingInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", New TestParameters(fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object))) End Function <Fact> Public Async Function TestOptionsOffered() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "2.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0", "2.0")) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Dim data = New ProviderData(installerServiceMock.Object, packageServiceMock.Object) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "1.0"), parameters:=New TestParameters(fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "2.0"), parameters:=New TestParameters(index:=1, fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", FeaturesResources.Find_and_install_latest_version, parameters:=New TestParameters(index:=2, fixProviderData:=data)) End Function <Fact> Public Async Function TestInstallGetsCalledNoVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", Nothing, It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function <Fact> Public Async Function TestInstallGetsCalledWithVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0")) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", "1.0", It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function Private Shared Function CreateSearchResult(packageName As String, typeName As String, nameParts As ImmutableArray(Of String)) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return CreateSearchResult(New PackageWithTypeResult( packageName:=packageName, rank:=0, typeName:=typeName, version:=Nothing, containingNamespaceNames:=nameParts)) End Function Private Shared Function CreateSearchResult(ParamArray results As PackageWithTypeResult()) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return ValueTaskFactory.FromResult(ImmutableArray.Create(results)) End Function Private Shared Function CreateNameParts(ParamArray parts As String()) As ImmutableArray(Of String) Return parts.ToImmutableArray() 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.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Packaging Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.VisualBasic.AddImport Imports Moq Imports ProviderData = System.Tuple(Of Microsoft.CodeAnalysis.Packaging.IPackageInstallerService, Microsoft.CodeAnalysis.SymbolSearch.ISymbolSearchService) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImport <Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Class AddImportNuGetTests Inherits AbstractAddImportTests Private Const NugetOrgSource = "nuget.org" Private Shared ReadOnly NuGetPackageSources As ImmutableArray(Of PackageSource) = ImmutableArray.Create(New PackageSource(NugetOrgSource, "http://nuget.org")) Protected Overrides Sub InitializeWorkspace(workspace As TestWorkspace, parameters As TestParameters) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options. WithChangedOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic, True). WithChangedOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic, True))) End Sub Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) ' This is used by inherited tests to ensure the properties of diagnostic analyzers are correct. It's not ' needed by the tests in this class, but can't throw an exception. Return (Nothing, Nothing) End Function Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, parameters As TestParameters) As (DiagnosticAnalyzer, CodeFixProvider) Dim data = DirectCast(parameters.fixProviderData, ProviderData) Return (Nothing, New VisualBasicAddImportCodeFixProvider(data.Item1, data.Item2)) End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact> Public Async Function TestSearchPackageSingleName() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestSearchPackageMultipleNames() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NS1.NS2 Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestFailedInstallDoesNotChangeFile() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(False) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestMissingIfPackageAlreadyInstalled() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.IsInstalled(It.IsAny(Of Workspace)(), It.IsAny(Of ProjectId)(), "NuGetPackage")). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestMissingInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", New TestParameters(fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object))) End Function <Fact> Public Async Function TestOptionsOffered() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "2.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0", "2.0")) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Dim data = New ProviderData(installerServiceMock.Object, packageServiceMock.Object) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "1.0"), parameters:=New TestParameters(fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "2.0"), parameters:=New TestParameters(index:=1, fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", FeaturesResources.Find_and_install_latest_version, parameters:=New TestParameters(index:=2, fixProviderData:=data)) End Function <Fact> Public Async Function TestInstallGetsCalledNoVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", Nothing, It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function <Fact> Public Async Function TestInstallGetsCalledWithVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0")) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", "1.0", It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function Private Shared Function CreateSearchResult(packageName As String, typeName As String, nameParts As ImmutableArray(Of String)) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return CreateSearchResult(New PackageWithTypeResult( packageName:=packageName, rank:=0, typeName:=typeName, version:=Nothing, containingNamespaceNames:=nameParts)) End Function Private Shared Function CreateSearchResult(ParamArray results As PackageWithTypeResult()) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return ValueTaskFactory.FromResult(ImmutableArray.Create(results)) End Function Private Shared Function CreateNameParts(ParamArray parts As String()) As ImmutableArray(Of String) Return parts.ToImmutableArray() End Function End Class End Namespace
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Tools/ExternalAccess/OmniSharp/PublicAPI.Shipped.txt
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Workspaces/Remote/ServiceHub/Services/DocumentHighlights/RemoteDocumentHighlightsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.DocumentHighlighting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteDocumentHighlightsService : BrokeredServiceBase, IRemoteDocumentHighlightsService { internal sealed class Factory : FactoryBase<IRemoteDocumentHighlightsService> { protected override IRemoteDocumentHighlightsService CreateService(in ServiceConstructionArguments arguments) => new RemoteDocumentHighlightsService(arguments); } public RemoteDocumentHighlightsService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<ImmutableArray<SerializableDocumentHighlights>> GetDocumentHighlightsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, int position, ImmutableArray<DocumentId> documentIdsToSearch, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { // NOTE: In projection scenarios, we might get a set of documents to search // that are not all the same language and might not exist in the OOP process // (like the JS parts of a .cshtml file). Filter them out here. This will // need to be revisited if we someday support FAR between these languages. var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var documentsToSearch = await documentIdsToSearch.SelectAsArrayAsync(id => solution.GetDocumentAsync(id, includeSourceGenerated: true, cancellationToken)).ConfigureAwait(false); var documentsToSearchSet = ImmutableHashSet.CreateRange(documentsToSearch.WhereNotNull()); var service = document.GetLanguageService<IDocumentHighlightsService>(); var result = await service.GetDocumentHighlightsAsync( document, position, documentsToSearchSet, cancellationToken).ConfigureAwait(false); return result.SelectAsArray(SerializableDocumentHighlights.Dehydrate); }, 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.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteDocumentHighlightsService : BrokeredServiceBase, IRemoteDocumentHighlightsService { internal sealed class Factory : FactoryBase<IRemoteDocumentHighlightsService> { protected override IRemoteDocumentHighlightsService CreateService(in ServiceConstructionArguments arguments) => new RemoteDocumentHighlightsService(arguments); } public RemoteDocumentHighlightsService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<ImmutableArray<SerializableDocumentHighlights>> GetDocumentHighlightsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, int position, ImmutableArray<DocumentId> documentIdsToSearch, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { // NOTE: In projection scenarios, we might get a set of documents to search // that are not all the same language and might not exist in the OOP process // (like the JS parts of a .cshtml file). Filter them out here. This will // need to be revisited if we someday support FAR between these languages. var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var documentsToSearch = await documentIdsToSearch.SelectAsArrayAsync(id => solution.GetDocumentAsync(id, includeSourceGenerated: true, cancellationToken)).ConfigureAwait(false); var documentsToSearchSet = ImmutableHashSet.CreateRange(documentsToSearch.WhereNotNull()); var service = document.GetLanguageService<IDocumentHighlightsService>(); var result = await service.GetDocumentHighlightsAsync( document, position, documentsToSearchSet, cancellationToken).ConfigureAwait(false); return result.SelectAsArray(SerializableDocumentHighlights.Dehydrate); }, cancellationToken); } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/Core/Portable/Collections/KeyedStack.cs
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Collections { internal class KeyedStack<T, R> where T : notnull { private readonly Dictionary<T, Stack<R>> _dict = new Dictionary<T, Stack<R>>(); public void Push(T key, R value) { Stack<R>? store; if (!_dict.TryGetValue(key, out store)) { store = new Stack<R>(); _dict.Add(key, store); } store.Push(value); } public bool TryPop(T key, [MaybeNullWhen(returnValue: false)] out R value) { Stack<R>? store; if (_dict.TryGetValue(key, out store) && store.Count > 0) { value = store.Pop(); return true; } value = default(R)!; 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.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Collections { internal class KeyedStack<T, R> where T : notnull { private readonly Dictionary<T, Stack<R>> _dict = new Dictionary<T, Stack<R>>(); public void Push(T key, R value) { Stack<R>? store; if (!_dict.TryGetValue(key, out store)) { store = new Stack<R>(); _dict.Add(key, store); } store.Push(value); } public bool TryPop(T key, [MaybeNullWhen(returnValue: false)] out R value) { Stack<R>? store; if (_dict.TryGetValue(key, out store) && store.Count > 0) { value = store.Pop(); return true; } value = default(R)!; return false; } } }
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Compilers/VisualBasic/Test/Semantic/Diagnostics/OperationAnalyzerTests.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.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics <CompilerTrait(CompilerFeature.IOperation)> Public Class OperationAnalyzerTests Inherits BasicTestBase <Fact> Public Sub EmptyArrayVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Sub M1() Dim arr1 As Integer() = New Integer(-1) { } ' yes Dim arr2 As Byte() = { } ' yes Dim arr3 As C() = New C(-1) { } ' yes Dim arr4 As String() = New String() { Nothing } ' no Dim arr5 As Double() = New Double(1) { } ' no Dim arr6 As Integer() = { -1 } ' no Dim arr7 as Integer()() = New Integer(-1)() { } ' yes Dim arr8 as Integer()()()() = New Integer( -1)()()() { } ' yes Dim arr9 as Integer(,) = New Integer(-1,-1) { } ' no Dim arr10 as Integer()(,) = New Integer(-1)(,) { } ' yes Dim arr11 as Integer()(,) = New Integer(1)(,) { } ' no Dim arr12 as Integer(,)() = New Integer(-1,-1)() { } ' no Dim arr13 as Integer() = New Integer(0) { } ' no End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EmptyArrayAnalyzer}, Nothing, Nothing, Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1) { }").WithLocation(3, 33), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "{ }").WithLocation(4, 30), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New C(-1) { }").WithLocation(5, 27), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)() { }").WithLocation(9, 35), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer( -1)()()() { }").WithLocation(10, 39), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)(,) { }").WithLocation(12, 37)) End Sub <Fact> Public Sub BoxingVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(p1 As Object, p2 As Object, p3 As Object) As Object Dim v1 As New S Dim v2 As S = v1 Dim v3 As S = v1.M1(v2) Dim v4 As Object = M1(3, Me, v1) Dim v5 As Object = v3 If p1 Is Nothing return 3 End If If p2 Is Nothing return v3 End If If p3 Is Nothing Return v4 End If Return v5 End Function End Class Structure S Public X As Integer Public Y As Integer Public Z As Object Public Function M1(p1 As S) As S p1.GetType() Z = Me Return p1 End Function End Structure ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BoxingOperationAnalyzer}, Nothing, Nothing, Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(6, 32), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v1").WithLocation(6, 39), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(7, 29), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(9, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(12, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "p1").WithLocation(27, 9), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "Me").WithLocation(28, 13)) End Sub <Fact> Public Sub BadStuffVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(z as Integer) Framitz() Dim x As Integer = Bexley() Dim y As Integer = 10 Dim d As Double() = Nothing M1(d) Goto End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyAnalyzerDiagnostics({New BadStuffTestAnalyzer}, Nothing, Nothing, Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz()").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz()").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley()").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley()").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "M1(d)").WithLocation(7, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "M1(d)").WithLocation(7, 9), Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "Goto").WithLocation(8, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Goto").WithLocation(8, 9), Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "").WithLocation(8, 13), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "").WithLocation(8, 13)) End Sub <Fact> Public Sub SwitchVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select Select Case x Case Else Exit Select End Select Select Case x End Select Select Case x Case 1 Exit Select Case Exit Select End Select Select Case x Case 1 Exit Select Case = Exit Select End Select Select Case x Case 1 Exit Select Case 2 to Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(60, 17), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(68, 1), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(74, 22)) comp.VerifyAnalyzerDiagnostics({New SwitchTestAnalyzer}, Nothing, Nothing, Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(12, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(30, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(37, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(37, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(42, 21), Diagnostic(SwitchTestAnalyzer.OnlyDefaultSwitchDescriptor.Id, "x").WithLocation(49, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(54, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(54, 21)) End Sub <Fact> Public Sub InvocationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1(a As Integer, b As Integer, c As Integer, x As Integer, y As Integer, z As Integer) End Sub Public Sub M2() M1(1, 2, 3, 4, 5, 6) M1(a:=1, b:=2, c:=3, x:=4, y:=5, z:=6) M1(a:=1, c:=2, b:=3, x:=4, y:=5, z:=6) M1(z:=1, x:=2, y:=3, c:=4, a:=5, b:=6) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) M0(1) M0(1, 2, 4, 3) End Sub Public Sub M3(Optional a As Integer = Nothing, Optional b As Integer = 0) End Sub Public Sub M4() M3(Nothing, 0) M3(Nothing,) M3(,0) M3(,) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New InvocationTestAnalyzer}, Nothing, Nothing, Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(Nothing,)").WithArguments("b").WithLocation(25, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,0)").WithArguments("a").WithLocation(26, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,)").WithArguments("a").WithLocation(27, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,)").WithArguments("b").WithLocation(27, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(11, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "4").WithLocation(12, 33), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(12, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "1").WithLocation(12, 15), Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)").WithLocation(14, 9), Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)").WithLocation(15, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "3").WithLocation(17, 21)) End Sub <Fact> Public Sub FieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer Public Const F2 As Integer = 2 Public ReadOnly F3 As Integer Public F4 As Integer Public F5 As Integer Public F6 As Integer = 6 Public F7 As Integer Public F9 As S Public F10 As New C1 Public Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 12)) End Sub <Fact> Public Sub StaticFieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Shared F1 As Integer Public Shared ReadOnly F2 As Integer = 2 Public Shared Readonly F3 As Integer Public Shared F4 As Integer Public Shared F5 As Integer Public Shared F6 As Integer = 6 Public Shared F7 As Integer Public Shared F9 As S Public Shared F10 As New C1 Shared Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Shared Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Shared Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 19)) End Sub <Fact> Public Sub LocalCouldBeConstVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(p as Integer) Dim x As Integer = p Dim y As Integer = x Const z As Integer = 1 Dim a As Integer = 2 Dim b As Integer = 3 Dim c As Integer = 4 Dim d As Integer = 5 Dim e As Integer = 6 Dim s As String = "ZZZ" b = 3 c -= 12 d += e + b M1(y, z, a, s) Dim n As S n.A = 10 n.B = 20 Dim o As New C1 o.A = 10 o.B = 20 End Sub Public Sub M1(ByRef x As Integer, y As Integer, ByRef z as Integer, s as String) x = 10 End Sub End Class Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LocalCouldBeConstAnalyzer}, Nothing, Nothing, Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "e").WithLocation(10, 13), Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "s").WithLocation(11, 13)) End Sub <Fact> Public Sub SymbolCouldHaveMoreSpecificTypeVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0() Dim a As Object = New Middle() Dim b As Object = New Value(10) Dim c As Object = New Middle() c = New Base() Dim d As Base = New Derived() Dim e As Base = New Derived() e = New Middle() Dim f As Base = New Middle() f = New Base() Dim g As Object = New Derived() g = New Base() g = New Middle() Dim h As New Middle() h = New Derived() Dim i As Object = 3 Dim j As Object j = 10 j = 10.1 Dim k As Middle = New Derived() Dim l As Middle = New Derived() Dim o As Object = New Middle() MM(l, o) Dim ibase1 As IBase1 = Nothing Dim ibase2 As IBase2 = Nothing Dim imiddle As IMiddle = Nothing Dim iderived As IDerived = Nothing Dim ia As Object = imiddle Dim ic As Object = imiddle ic = ibase1 Dim id As IBase1 = iderived Dim ie As IBase1 = iderived ie = imiddle Dim iff As IBase1 = imiddle iff = ibase1 Dim ig As Object = iderived ig = ibase1 ig = imiddle Dim ih = imiddle ih = iderived Dim ik As IMiddle = iderived Dim il As IMiddle = iderived Dim io As Object = imiddle IMM(il, io) Dim im As IBase2 = iderived Dim isink As Object = ibase2 isink = 3 End Sub Private fa As Object = New Middle() Private fb As Object = New Value(10) Private fc As Object = New Middle() Private fd As Base = New Derived() Private fe As Base = New Derived() Private ff As Base = New Middle() Private fg As Object = New Derived() Private fh As New Middle() Private fi As Object = 3 Private fj As Object Private fk As Middle = New Derived() Private fl As Middle = New Derived() Private fo As Object = New Middle() Private Shared fibase1 As IBase1 = Nothing Private Shared fibase2 As IBase2 = Nothing Private Shared fimiddle As IMiddle= Nothing Private Shared fiderived As IDerived = Nothing Private fia As Object = fimiddle Private fic As Object = fimiddle Private fid As IBase1 = fiderived Private fie As IBase1 = fiderived Private fiff As IBase1 = fimiddle Private fig As Object = fiderived Private fih As IMiddle = fimiddle Private fik As IMiddle = fiderived Private fil As IMiddle = fiderived Private fio As Object = fimiddle Private fisink As Object = fibase2 Private fim As IBase2 = fiderived Sub M1() fc = New Base() fe = New Middle() ff = New Base() fg = New Base() fg = New Middle() fh = New Derived() fj = 10 fj = 10.1 MM(fl, fo) fic = fibase1 fie = fimiddle fiff = fibase1 fig = fibase1 fig = fimiddle fih = fiderived IMM(fil, fio) fisink = 3 End Sub Sub MM(ByRef p1 As Middle, ByRef p2 As Object) p1 = New Middle() p2 = Nothing End Sub Sub IMM(ByRef p1 As IMiddle, ByRef p2 As object) p1 = Nothing p2 = Nothing End Sub End Class Class Base End Class Class Middle Inherits Base End Class Class Derived Inherits Middle End Class Structure Value Public Sub New(a As Integer) X = a End Sub Public X As Integer End Structure Interface IBase1 End Interface Interface IBase2 End Interface Interface IMiddle Inherits IBase1 End Interface Interface IDerived Inherits IMiddle Inherits IBase2 End Interface ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SymbolCouldHaveMoreSpecificTypeAnalyzer}, Nothing, Nothing, Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "a").WithArguments("a", "Middle").WithLocation(3, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "b").WithArguments("b", "Value").WithLocation(4, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "c").WithArguments("c", "Base").WithLocation(5, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "d").WithArguments("d", "Derived").WithLocation(7, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "e").WithArguments("e", "Middle").WithLocation(8, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "g").WithArguments("g", "Base").WithLocation(12, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "i").WithArguments("i", "Integer").WithLocation(17, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "k").WithArguments("k", "Derived").WithLocation(21, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ia").WithArguments("ia", "IMiddle").WithLocation(31, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ic").WithArguments("ic", "IBase1").WithLocation(32, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "id").WithArguments("id", "IDerived").WithLocation(34, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ie").WithArguments("ie", "IMiddle").WithLocation(35, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ig").WithArguments("ig", "IBase1").WithLocation(39, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ik").WithArguments("ik", "IDerived").WithLocation(44, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "im").WithArguments("im", "IDerived").WithLocation(48, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fa").WithArguments("Private fa As Object", "Middle").WithLocation(53, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fb").WithArguments("Private fb As Object", "Value").WithLocation(54, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fc").WithArguments("Private fc As Object", "Base").WithLocation(55, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fd").WithArguments("Private fd As Base", "Derived").WithLocation(56, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fe").WithArguments("Private fe As Base", "Middle").WithLocation(57, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fg").WithArguments("Private fg As Object", "Base").WithLocation(59, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fi").WithArguments("Private fi As Object", "Integer").WithLocation(61, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fk").WithArguments("Private fk As Middle", "Derived").WithLocation(63, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fia").WithArguments("Private fia As Object", "IMiddle").WithLocation(72, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fic").WithArguments("Private fic As Object", "IBase1").WithLocation(73, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fid").WithArguments("Private fid As IBase1", "IDerived").WithLocation(74, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fie").WithArguments("Private fie As IBase1", "IMiddle").WithLocation(75, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fig").WithArguments("Private fig As Object", "IBase1").WithLocation(77, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fik").WithArguments("Private fik As IMiddle", "IDerived").WithLocation(79, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fim").WithArguments("Private fim As IBase2", "IDerived").WithLocation(83, 13)) End Sub <Fact> Public Sub ValueContextsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(Optional a As Integer = 16, Optional b As Integer = 17, Optional c As Integer = 18) End Sub Public F1 As Integer = 16 Public F2 As Integer = 17 Public F3 As Integer = 18 Public Sub M1() M0(16, 17, 18) M0(f1, f2, f3) M0() End Sub End Class Enum E A = 16 B C = 17 D = 18 End Enum Class C1 Public Sub New (a As Integer, b As Integer, c As Integer) End Sub Public F1 As C1 = New C1(c:=16, a:=17, b:=18) Public F2 As New C1(16, 17, 18) Public F3(16) As Integer Public F4(17) As Integer ' The upper bound specification is not presently treated as a code block. This is suspect. Public F5(18) As Integer Public F6 As Integer() = New Integer(16) {} Public F7 As Integer() = New Integer(17) {} End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SeventeenTestAnalyzer}, Nothing, Nothing, Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(2, 71), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(6, 28), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(10, 16), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(19, 9), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(27, 40), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(28, 29), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(33, 42), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "M0").WithLocation(12, 9)) ' The M0 diagnostic is an artifact of the VB compiler filling in default values in the high-level bound tree, and is questionable. End Sub <Fact> Public Sub NullArgumentVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Goo Public Sub New(X As String) End Sub End Class Class C Public Sub M0(x As String, y As String) End Sub Public Sub M1() M0("""", """") M0(Nothing, """") M0("""", Nothing) M0(Nothing, Nothing) End Sub Public Sub M2() Dim f1 = New Goo("""") Dim f2 = New Goo(Nothing) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NullArgumentTestAnalyzer}, Nothing, Nothing, Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(13, 12), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(14, 18), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(15, 12), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(15, 21), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(20, 26)) End Sub <Fact> Public Sub MemberInitializerVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Bar Public Field As Boolean End Class Class Goo Public Field As Integer Public Property Prop1 As String Public Property Prop2 As Bar End Class Class C Public Sub M1() Dim f1 = New Goo() Dim f2 = New Goo() With {.Field = 10} Dim f3 = New Goo With {.Prop1 = Nothing} Dim f4 = New Goo With {.Field = 10, .Prop1 = Nothing} Dim f5 = New Goo With {.Prop2 = New Bar() With {.Field = True}} Dim e1 = New Goo() With {.Prop1 = 10} Dim e2 = New Goo With {10} End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQualifiedNameInInit, "").WithLocation(20, 32)) comp.VerifyAnalyzerDiagnostics({New MemberInitializerTestAnalyzer}, Nothing, Nothing, Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(14, 35), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(15, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(16, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(16, 46), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop2").WithLocation(17, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(17, 58), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(19, 35)) End Sub <Fact> Public Sub AssignmentVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Bar Public Field As Boolean End Class Class Goo Public Field As Integer Public Property Prop1 As String Public Property Prop2 As Bar End Class Class C Public Sub M1() Dim f1 = New Goo() Dim f2 = New Goo() With {.Field = 10} Dim f3 = New Goo With {.Prop1 = Nothing} Dim f4 = New Goo With {.Field = 10, .Prop1 = Nothing} Dim f5 = New Goo With {.Prop2 = New Bar() With {.Field = True}} End Sub Public Sub M2() Dim f1 = New Goo With {.Prop2 = New Bar() With {.Field = True}} f1.Field = 0 f1.Prop1 = Nothing Dim f2 = New Bar() f2.Field = True End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New AssignmentTestAnalyzer}, Nothing, Nothing, Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop2 = New Bar() With {.Field = True}").WithLocation(21, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = 10").WithLocation(14, 34), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop1 = Nothing").WithLocation(15, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = 10").WithLocation(16, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop1 = Nothing").WithLocation(16, 45), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop2 = New Bar() With {.Field = True}").WithLocation(17, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = True").WithLocation(17, 57), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = True").WithLocation(21, 57), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f1.Field = 0").WithLocation(22, 9), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f1.Prop1 = Nothing").WithLocation(23, 9), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f2.Field = True").WithLocation(26, 9)) End Sub <Fact> Public Sub ArrayInitializerVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1() Dim arr1 = New Integer() {} Dim arr2 As Object = {} Dim arr3 = {} Dim arr4 = New Integer() {1, 2, 3} Dim arr5 = {1, 2, 3} Dim arr6 As C() = {Nothing, Nothing, Nothing} Dim arr7 = New Integer() {1, 2, 3, 4, 5, 6} ' LargeList Dim arr8 = {1, 2, 3, 4, 5, 6} ' LargeList Dim arr9 As C() = {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing} ' LargeList Dim arr10 As Integer(,) = {{1, 2, 3, 4, 5, 6}} ' LargeList Dim arr11 = New Integer(,) {{1, 2, 3, 4, 5, 6}, ' LargeList {7, 8, 9, 10, 11, 12}} ' LargeList Dim arr12 As C(,) = {{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}, ' LargeList {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}} ' LargeList Dim arr13 = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}} ' jagged array Dim arr14 = {({1, 2, 3}), ({4, 5}), ({6}), ({7})} Dim arr15 = {({({1, 2, 3, 4, 5, 6})})} ' LargeList End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ArrayInitializerTestAnalyzer()}, Nothing, Nothing, Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(11, 34), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(12, 20), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(13, 27), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(15, 36), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(16, 37), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{7, 8, 9, 10, 11, 12}").WithLocation(17, 37), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(18, 30), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(19, 29), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(24, 25)) End Sub <Fact> Public Sub VariableDeclarationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C #Disable Warning BC42024 Dim field1, field2, field3, field4 As Integer Public Sub M1() Dim a1 = 10 Dim b1 As New Integer, b2, b3, b4 As New Goo(1) 'too many Dim c1, c2 As Integer, c3, c4 As Goo 'too many Dim d1() As Goo Dim e1 As Integer = 10, e2 = {1, 2, 3}, e3, e4 As C 'too many Dim f1 = 10, f2 = 11, f3 As Integer Dim h1, h2, , h3 As Integer 'too many Dim i1, i2, i3, i4 As New UndefType 'too many Dim j1, j2, j3, j4 As UndefType 'too many Dim k1 As Integer, k2, k3, k4 As New Goo(1) 'too many End Sub #Enable Warning BC42024 End Class Class Goo Public Sub New(X As Integer) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedIdentifier, "").WithLocation(11, 21), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31)) comp.VerifyAnalyzerDiagnostics({New VariableDeclarationTestAnalyzer}, Nothing, Nothing, Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "a1").WithLocation(5, 13), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim b1 As New Integer, b2, b3, b4 As New Goo(1)").WithLocation(6, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b1").WithLocation(6, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b2").WithLocation(6, 32), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b3").WithLocation(6, 36), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b4").WithLocation(6, 40), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim c1, c2 As Integer, c3, c4 As Goo").WithLocation(7, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim e1 As Integer = 10, e2 = {1, 2, 3}, e3, e4 As C").WithLocation(9, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e1").WithLocation(9, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e2").WithLocation(9, 33), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "f1").WithLocation(10, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "f2").WithLocation(10, 22), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim h1, h2, , h3 As Integer").WithLocation(11, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim i1, i2, i3, i4 As New UndefType").WithLocation(12, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim j1, j2, j3, j4 As UndefType").WithLocation(13, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim k1 As Integer, k2, k3, k4 As New Goo(1)").WithLocation(14, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k2").WithLocation(14, 28), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k3").WithLocation(14, 32), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k4").WithLocation(14, 36)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub CaseVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select Select Case x Case Else Exit Select End Select Select Case x End Select Select Case x Case 1 Exit Select Case Exit Select End Select Select Case x Case 1 Exit Select Case = Exit Select End Select Select Case x Case 1 Exit Select Case 2 to Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(60, 17), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(68, 1), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(74, 22)) comp.VerifyAnalyzerDiagnostics({New CaseTestAnalyzer}, Nothing, Nothing, Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1, 2 Exit Select").WithLocation(4, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(8, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(17, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(26, 13), Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1, 980 To 985 Exit Select").WithLocation(31, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(33, 13), Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1 to 3, 980 To 985 Exit Select").WithLocation(38, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(50, 13)) End Sub <Fact> Public Sub ExplicitVsImplicitInstancesVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Overridable Sub M1() Me.M1() M1() End Sub Public Sub M2() End Sub End Class Class D Inherits C Public Overrides Sub M1() MyBase.M1() M1() M2() End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ExplicitVsImplicitInstanceAnalyzer}, Nothing, Nothing, Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "Me").WithLocation(3, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(4, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "MyBase").WithLocation(13, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(14, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M2").WithLocation(15, 9)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub EventAndMethodReferencesVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Delegate Sub MumbleEventHandler(sender As Object, args As System.EventArgs) Class C Public Event Mumble As MumbleEventHandler Public Sub OnMumble(args As System.EventArgs) AddHandler Mumble, New MumbleEventHandler(AddressOf Mumbler) AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As System.EventArgs) End Sub) AddHandler Mumble, Sub(s As Object, a As System.EventArgs) End Sub RaiseEvent Mumble(Me, args) ' Dim o As object = AddressOf Mumble Dim d As MumbleEventHandler = AddressOf Mumbler Mumbler(Me, Nothing) RemoveHandler Mumble, AddressOf Mumbler End Sub Private Sub Mumbler(sender As Object, args As System.EventArgs) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New MemberReferenceAnalyzer}, Nothing, Nothing, Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, New MumbleEventHandler(AddressOf Mumbler)").WithLocation(7, 9), ' Bug: we are missing diagnostics of "MethodBindingDescriptor" here. https://github.com/dotnet/roslyn/issues/20095 Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(7, 20), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(7, 51), Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As System.EventArgs) End Sub)").WithLocation(8, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(8, 20), Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, Sub(s As Object, a As System.EventArgs) End Sub").WithLocation(10, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(10, 20), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(12, 20), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(14, 39), Diagnostic(MemberReferenceAnalyzer.HandlerRemovedDescriptor.Id, "RemoveHandler Mumble, AddressOf Mumbler").WithLocation(16, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(16, 23), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(16, 31) ) End Sub <Fact> Public Sub ParamArraysVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1() M0(1) M0(1, 2) M0(1, 2, 3, 4) M0(1, 2, 3, 4, 5) M0(1, 2, 3, 4, 5, 6) M0(1, New Integer() { 2, 3, 4 }) M0(1, New Integer() { 2, 3, 4, 5 }) M0(1, New Integer() { 2, 3, 4, 5, 6 }) Dim local As D = new D(1, 2, 3, 4, 5) local = new D(1, New Integer() { 2, 3, 4, 5 }) local = new D(1, 2, 3, 4) local = new D(1, New Integer() { 2, 3, 4 }) End Sub End Class Class D Public Sub New(a As Integer, ParamArray b As Integer()) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ParamsArrayTestAnalyzer}, Nothing, Nothing, Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5)").WithLocation(9, 9), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6)").WithLocation(10, 9), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5 }").WithLocation(12, 15), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5, 6 }").WithLocation(13, 15), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "D").WithLocation(14, 30), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5 }").WithLocation(15, 26)) End Sub <Fact> Public Sub FieldInitializersVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer = 44 Public F2 As String = "Hello" Public F3 As Integer = Goo() Public Shared Function Goo() Return 10 End Function Public Shared Function Bar(Optional P1 As Integer = 10, Optional F2 As Integer = 20) Return P1 + F2 End Function End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EqualsValueTestAnalyzer}, Nothing, Nothing, Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 44").WithLocation(2, 26), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= ""Hello""").WithLocation(3, 25), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= Goo()").WithLocation(4, 26), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 20").WithLocation(10, 84)) End Sub <Fact> Public Sub OwningSymbolVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub UnFunkyMethod() Dim x As Integer = 0 Dim y As Integer = x End Sub Public Sub FunkyMethod() Dim x As Integer = 0 Dim y As Integer = x End Sub Public FunkyField As Integer = 12 Public UnFunkyField As Integer = 12 End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New OwningSymbolTestAnalyzer}, Nothing, Nothing, Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(8, 28), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(9, 28), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(12, 36)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub NoneOperationVisualBasic() ' BoundCaseStatement is OperationKind.None Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x as Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select End Sub Public Property Fred As Integer Set(value As Integer) Exit Property End Set Get Return 12 End Get End Property Public Sub Barney Resume End Sub End Class ]]> </file> </compilation> ' We have 2 OperationKind.None operations in the operation tree: ' (1) BoundUnstructuredExceptionHandlingStatement for the method block with Resume statement ' (2) BoundResumeStatement for Resume statement Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NoneOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(NoneOperationTestAnalyzer.NoneOperationDescriptor.Id, <![CDATA[Public Sub Barney Resume End Sub]]>).WithLocation(22, 5), Diagnostic(NoneOperationTestAnalyzer.NoneOperationDescriptor.Id, "Resume").WithLocation(23, 9)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub LambdaExpressionVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Class B Public Sub M1(x As Integer) Dim action1 As Action = Sub() End Sub Dim action2 As Action = Sub() Console.WriteLine(1) End Sub Dim func1 As Func(Of Integer, Integer) = Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function End Sub End Class Delegate Sub MumbleEventHandler(sender As Object, args As EventArgs) Class C Public Event Mumble As MumbleEventHandler Public Sub OnMumble(args As EventArgs) AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As EventArgs) End Sub) AddHandler Mumble, Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub RaiseEvent Mumble(Me, args) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LambdaTestAnalyzer}, Nothing, Nothing, Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub() End Sub").WithLocation(5, 33), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) End Sub").WithLocation(25, 51), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub() Console.WriteLine(1) End Sub").WithLocation(7, 33), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub").WithLocation(27, 28), Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub").WithLocation(27, 28), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function").WithLocation(10, 50), Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function").WithLocation(10, 50)) End Sub <WorkItem(8385, "https://github.com/dotnet/roslyn/issues/8385")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/18839")> Public Sub StaticMemberReferenceVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class D Public Shared Event E() Public Shared Field As Integer Public Shared Property P As Integer Public Shared Sub Method() End Sub End Class Class C Public Shared Event E() Public Shared Sub Bar() End Sub Public Sub Goo() AddHandler C.E, AddressOf D.Method RaiseEvent E() ' Can't raise static event with type in VB C.Bar() AddHandler D.E, Sub() End Sub D.Field = 1 Dim x = D.P D.Method() End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New StaticMemberTestAnalyzer}, Nothing, Nothing, Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddHandler C.E, AddressOf D.Method").WithLocation(19, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddressOf D.Method").WithLocation(19, 25), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "E").WithLocation(20, 20), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.Bar()").WithLocation(21, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddHandler D.E, Sub() End Sub").WithLocation(23, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Field").WithLocation(25, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.P").WithLocation(26, 17), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Method()").WithLocation(27, 9)) End Sub <Fact> Public Sub LabelOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class A Public Sub Fred() Wilma: GoTo Betty Betty: GoTo Wilma End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LabelOperationsTestAnalyzer}, Nothing, Nothing, Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Wilma:").WithLocation(3, 9), Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "GoTo Betty").WithLocation(4, 9), Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Betty:").WithLocation(5, 9), Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "GoTo Wilma").WithLocation(6, 9)) End Sub <Fact> Public Sub UnaryBinaryOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class A Private ReadOnly _value As Integer Public Sub New (value As Integer) _value = value End Sub Public Shared Operator +(x As A, Y As A) As A Return New A(x._value + y._value) End Operator Public Shared Operator *(x As A, y As A) As A Return New A(x._value * y._value) End Operator Public Shared Operator -(x As A) As A Return New A(-x._value) End Operator Public Shared operator +(x As A) As A Return New A(+x._value) End Operator End CLass Class C Public Shared Sub Main() Dim B As Boolean = False Dim d As Double = 100 Dim a1 As New A(0) Dim a2 As New A(100) b = Not b d = d * 100 a1 = a1 + a2 a1 = -a2 End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New UnaryAndBinaryOperationsTestAnalyzer}, Nothing, Nothing, Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.BooleanNotDescriptor.Id, "Not b").WithLocation(33, 13), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.DoubleMultiplyDescriptor.Id, "d * 100").WithLocation(34, 13), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorAddMethodDescriptor.Id, "a1 + a2").WithLocation(35, 14), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorMinusMethodDescriptor.Id, "-a2").WithLocation(36, 14)) End Sub <Fact> Public Sub BinaryOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class B2 Public Shared Operator +(x As B2, y As B2) As B2 System.Console.WriteLine("+") Return x End Operator Public Shared Operator -(x As B2, y As B2) As B2 System.Console.WriteLine("-") Return x End Operator Public Shared Operator *(x As B2, y As B2) As B2 System.Console.WriteLine("*") Return x End Operator Public Shared Operator /(x As B2, y As B2) As B2 System.Console.WriteLine("/") Return x End Operator Public Shared Operator \(x As B2, y As B2) As B2 System.Console.WriteLine("\") Return x End Operator Public Shared Operator Mod(x As B2, y As B2) As B2 System.Console.WriteLine("Mod") Return x End Operator Public Shared Operator ^(x As B2, y As B2) As B2 System.Console.WriteLine("^") Return x End Operator Public Shared Operator =(x As B2, y As B2) As B2 System.Console.WriteLine("=") Return x End Operator Public Shared Operator <>(x As B2, y As B2) As B2 System.Console.WriteLine("<>") Return x End Operator Public Shared Operator <(x As B2, y As B2) As B2 System.Console.WriteLine("<") Return x End Operator Public Shared Operator >(x As B2, y As B2) As B2 System.Console.WriteLine(">") Return x End Operator Public Shared Operator <=(x As B2, y As B2) As B2 System.Console.WriteLine("<=") Return x End Operator Public Shared Operator >=(x As B2, y As B2) As B2 System.Console.WriteLine(">=") Return x End Operator Public Shared Operator Like(x As B2, y As B2) As B2 System.Console.WriteLine("Like") Return x End Operator Public Shared Operator &(x As B2, y As B2) As B2 System.Console.WriteLine("&") Return x End Operator Public Shared Operator And(x As B2, y As B2) As B2 System.Console.WriteLine("And") Return x End Operator Public Shared Operator Or(x As B2, y As B2) As B2 System.Console.WriteLine("Or") Return x End Operator Public Shared Operator Xor(x As B2, y As B2) As B2 System.Console.WriteLine("Xor") Return x End Operator Public Shared Operator <<(x As B2, y As Integer) As B2 System.Console.WriteLine("<<") Return x End Operator Public Shared Operator >>(x As B2, y As Integer) As B2 System.Console.WriteLine(">>") Return x End Operator End Class Module Module1 Sub Main() Dim x, y As New B2() Dim r As B2 r = x + y r = x - y r = x * y r = x / y r = x \ y r = x Mod y r = x ^ y r = x = y r = x <> y r = x < y r = x > y r = x <= y r = x >= y r = x Like y r = x & y r = x And y r = x Or y r = x Xor y r = x << 2 r = x >> 3 End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BinaryOperatorVBTestAnalyzer}, Nothing, Nothing, Diagnostic("BinaryUserDefinedOperator", "x + y").WithArguments("Add").WithLocation(109, 13), Diagnostic("BinaryUserDefinedOperator", "x - y").WithArguments("Subtract").WithLocation(110, 13), Diagnostic("BinaryUserDefinedOperator", "x * y").WithArguments("Multiply").WithLocation(111, 13), Diagnostic("BinaryUserDefinedOperator", "x / y").WithArguments("Divide").WithLocation(112, 13), Diagnostic("BinaryUserDefinedOperator", "x \ y").WithArguments("IntegerDivide").WithLocation(113, 13), Diagnostic("BinaryUserDefinedOperator", "x Mod y").WithArguments("Remainder").WithLocation(114, 13), Diagnostic("BinaryUserDefinedOperator", "x ^ y").WithArguments("Power").WithLocation(115, 13), Diagnostic("BinaryUserDefinedOperator", "x = y").WithArguments("Equals").WithLocation(116, 13), Diagnostic("BinaryUserDefinedOperator", "x <> y").WithArguments("NotEquals").WithLocation(117, 13), Diagnostic("BinaryUserDefinedOperator", "x < y").WithArguments("LessThan").WithLocation(118, 13), Diagnostic("BinaryUserDefinedOperator", "x > y").WithArguments("GreaterThan").WithLocation(119, 13), Diagnostic("BinaryUserDefinedOperator", "x <= y").WithArguments("LessThanOrEqual").WithLocation(120, 13), Diagnostic("BinaryUserDefinedOperator", "x >= y").WithArguments("GreaterThanOrEqual").WithLocation(121, 13), Diagnostic("BinaryUserDefinedOperator", "x Like y").WithArguments("Like").WithLocation(122, 13), Diagnostic("BinaryUserDefinedOperator", "x & y").WithArguments("Concatenate").WithLocation(123, 13), Diagnostic("BinaryUserDefinedOperator", "x And y").WithArguments("And").WithLocation(124, 13), Diagnostic("BinaryUserDefinedOperator", "x Or y").WithArguments("Or").WithLocation(125, 13), Diagnostic("BinaryUserDefinedOperator", "x Xor y").WithArguments("ExclusiveOr").WithLocation(126, 13), Diagnostic("BinaryUserDefinedOperator", "x << 2").WithArguments("LeftShift").WithLocation(127, 13), Diagnostic("BinaryUserDefinedOperator", "x >> 3").WithArguments("RightShift").WithLocation(128, 13)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub InvalidOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class B2 Public Shared Operator +(x As B2, y As B2) As B2 System.Console.WriteLine("+") Return x End Operator Public Shared Operator -(x As B2) As B2 System.Console.WriteLine("-") Return x End Operator Public Shared Operator -(x As B2) As B2 System.Console.WriteLine("-") Return x End Operator End Class Module Module1 Sub Main() Dim x, y As New B2() x = x + 10 x = x + y x = -x End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateProcDef1, "-", New Object() {"Public Shared Operator -(x As B2) As B2"}).WithLocation(8, 28), Diagnostic(ERRID.ERR_TypeMismatch2, "10", New Object() {"Integer", "B2"}).WithLocation(23, 17), Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "-x", New Object() {"-", Environment.NewLine & " 'Public Shared Operator -(x As B2) As B2': Not most specific." & vbCrLf & " 'Public Shared Operator -(x As B2) As B2': Not most specific."}).WithLocation(25, 13)) ' no diagnostic since nodes are invalid comp.VerifyAnalyzerDiagnostics({New OperatorPropertyPullerTestAnalyzer}) End Sub <Fact> Public Sub NullOperationSyntaxVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(ParamArray b As Integer()) End Sub Public Sub M1() M0() M0(1) M0(1, 2) M0(New Integer() { }) M0(New Integer() { 1 }) M0(New Integer() { 1, 2 }) End Sub End Class ]]> </file> </compilation> ' TODO: array should not be treated as ParamArray argument ' https://github.com/dotnet/roslyn/issues/8570 Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NullOperationSyntaxTestAnalyzer}, Nothing, Nothing, Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0()").WithLocation(6, 9), Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1)").WithLocation(7, 9), Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1, 2)").WithLocation(8, 9)) End Sub <WorkItem(8114, "https://github.com/dotnet/roslyn/issues/8114")> <Fact> Public Sub InvalidOperatorVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(a As Double, b as C) as Double Return b + c End Sub Public Function M2(s As C) As C Return -s End Function End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_EndFunctionExpected, "Public Function M1(a As Double, b as C) as Double").WithLocation(2, 5), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub").WithLocation(4, 5), Diagnostic(ERRID.ERR_InvInsideEndsProc, "Public Function M2(s As C) As C").WithLocation(6, 5), Diagnostic(ERRID.ERR_ClassNotExpression1, "c").WithArguments("C").WithLocation(3, 20), Diagnostic(ERRID.ERR_UnaryOperand2, "-s").WithArguments("-", "C").WithLocation(7, 16)) comp.VerifyAnalyzerDiagnostics({New InvalidOperatorExpressionTestAnalyzer}, Nothing, Nothing, Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidBinaryDescriptor.Id, "b + c").WithLocation(3, 16), Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidUnaryDescriptor.Id, "-s").WithLocation(7, 16)) End Sub <WorkItem(9014, "https://github.com/dotnet/roslyn/issues/9014")> <Fact> Public Sub InvalidConstructorVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Protected Structure S End Structure End Class Class D Shared Sub M(o) M(New C.S()) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30389: 'C.S' is not accessible in this context because it is 'Protected'. M(New C.S()) ~~~ ]]></errors>) ' Reuse ParamsArrayTestAnalyzer for this test. comp.VerifyAnalyzerDiagnostics({New ParamsArrayTestAnalyzer}, Nothing, Nothing, Diagnostic(ParamsArrayTestAnalyzer.InvalidConstructorDescriptor.Id, "New C.S()").WithLocation(7, 11)) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of ObjectCreationExpressionSyntax)().Single() comp.VerifyOperationTree(node, expectedOperationTree:=<![CDATA[ IObjectCreationOperation (Constructor: <null>) (OperationKind.ObjectCreation, Type: C.S, IsInvalid) (Syntax: 'New C.S()') Arguments(0) Initializer: null ]]>.Value) End Sub <Fact> Public Sub ConditionalAccessOperationsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Property Prop As Integer Get Return 0 End Get Set End Set End Property Public Field As Integer Default Public Property Mumble(i As Integer) Get return Field End Get Set Field = Value End Set End Property Public Field1 As C = Nothing Public Sub M0(p As C) Dim x = p?.Prop x = p?.Field x = p?(0) p?.M0(Nothing) x = Field1?.Prop x = Field1?.Field x = Field1?(0) Field1?.M0(Nothing) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() ' https://github.com/dotnet/roslyn/issues/21294 comp.VerifyAnalyzerDiagnostics({New ConditionalAccessOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Prop").WithLocation(24, 17), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(24, 17), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Field").WithLocation(25, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(25, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?(0)").WithLocation(26, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(26, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.M0(Nothing)").WithLocation(27, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(27, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Prop").WithLocation(29, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(29, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Field").WithLocation(30, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(30, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?(0)").WithLocation(31, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(31, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.M0(Nothing)").WithLocation(32, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(32, 9)) End Sub <WorkItem(8955, "https://github.com/dotnet/roslyn/issues/8955")> <Fact> Public Sub ForToLoopConditionCrashVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module M1 Class C1(Of t) Shared Widening Operator CType(ByVal p1 As C1(Of t)) As Integer Return 1 End Operator Shared Widening Operator CType(ByVal p1 As Integer) As C1(Of t) Return Nothing End Operator Shared Operator -(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Short) Return Nothing End Operator Shared Operator +(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Integer) Return Nothing End Operator End Class Sub goo() For i As C1(Of Integer) = 1 To 10 Next End Sub End Module Module M2 ReadOnly Property Moo As Integer Get Return 1 End Get End Property WriteOnly Property Boo As integer Set(value As integer) End Set End Property Sub Main() For Moo = 1 to Moo step Moo Next For Boo = 1 to Boo step Boo Next End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_LoopControlMustNotBeProperty, "Moo").WithLocation(38, 13), Diagnostic(ERRID.ERR_LoopControlMustNotBeProperty, "Boo").WithLocation(41, 13), Diagnostic(ERRID.ERR_NoGetProperty1, "Boo").WithArguments("Boo").WithLocation(41, 24), Diagnostic(ERRID.ERR_NoGetProperty1, "Boo").WithArguments("Boo").WithLocation(41, 33), Diagnostic(ERRID.ERR_UnacceptableForLoopOperator2, "For i As C1(Of Integer) = 1 To 10").WithArguments("Public Shared Operator -(p1 As M1.C1(Of Integer), p2 As M1.C1(Of Integer)) As M1.C1(Of Short)", "M1.C1(Of Integer)").WithLocation(19, 9), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", "<=").WithLocation(19, 9), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", ">=").WithLocation(19, 9), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System").WithLocation(1, 1)) comp.VerifyAnalyzerDiagnostics({New ForLoopConditionCrashVBTestAnalyzer}, Nothing, Nothing, Diagnostic(ForLoopConditionCrashVBTestAnalyzer.ForLoopConditionCrashDescriptor.Id, "Boo").WithLocation(41, 24), Diagnostic(ForLoopConditionCrashVBTestAnalyzer.ForLoopConditionCrashDescriptor.Id, "10").WithLocation(19, 40)) End Sub <WorkItem(9012, "https://github.com/dotnet/roslyn/issues/9012")> <Fact> Public Sub InvalidEventInstanceVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Module Program Sub Main(args As String()) AddHandler Function(ByVal x) x End Sub End Module Class TestClass Event TestEvent As Action Shared Sub Test(receiver As TestClass) AddHandler receiver?.TestEvent, AddressOf Main End Sub Shared Sub Main() End Sub End Class Module Module1 Sub Main() Dim x = {Iterator sub() yield, new object} Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object} Dim z = {Sub() AddHandler, New Object} g0(Iterator sub() Yield) g1(Iterator Sub() Yield, 5) End Sub Sub g0(ByVal x As Func(Of IEnumerator)) End Sub Sub g1(ByVal x As Func(Of IEnumerator), ByVal y As Integer) End Sub Iterator Function f() As IEnumerator Yield End Function End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedComma, "").WithLocation(6, 39), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(6, 39), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(24, 38), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(25, 62), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(26, 34), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(27, 32), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(28, 32), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(37, 14), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(31, 31), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(33, 31), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(36, 30), Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "receiver?.TestEvent").WithLocation(15, 20), Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "Function(ByVal x) x").WithLocation(6, 20), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(24, 27), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(25, 27), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(25, 51), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(27, 21), Diagnostic(ERRID.ERR_BadIteratorReturn, "Sub").WithLocation(28, 21), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Collections.Generic").WithLocation(2, 1)) comp.VerifyAnalyzerDiagnostics({New MemberReferenceAnalyzer}, Nothing, Nothing, Diagnostic("HandlerAdded", "AddHandler Function(ByVal x) x").WithLocation(6, 9), Diagnostic("InvalidEvent", "AddHandler Function(ByVal x) x").WithLocation(6, 9), Diagnostic("HandlerAdded", "AddHandler receiver?.TestEvent, AddressOf Main").WithLocation(15, 9), Diagnostic("InvalidEvent", "AddHandler receiver?.TestEvent, AddressOf Main").WithLocation(15, 9), Diagnostic("HandlerAdded", "AddHandler, New Object").WithLocation(26, 24), Diagnostic("InvalidEvent", "AddHandler, New Object").WithLocation(26, 24), Diagnostic("EventReference", ".TestEvent").WithLocation(15, 29)) End Sub <Fact, WorkItem(9127, "https://github.com/dotnet/roslyn/issues/9127")> Public Sub UnaryTrueFalseOperationVisualBasic() ' BoundCaseStatement is OperationKind.None Dim source = <compilation> <file name="c.vb"> <![CDATA[ Module Module1 Structure S8 Public Shared Narrowing Operator CType(x As S8) As Boolean System.Console.WriteLine("Narrowing Operator CType(x As S8) As Boolean") Return Nothing End Operator Public Shared Operator IsTrue(x As S8) As Boolean System.Console.WriteLine("IsTrue(x As S8) As Boolean") Return False End Operator Public Shared Operator IsFalse(x As S8) As Boolean System.Console.WriteLine("IsFalse(x As S8) As Boolean") Return False End Operator Public Shared Operator And(x As S8, y As S8) As S8 Return New S8() End Operator End Structure Sub Main() Dim x As New S8 Dim y As New S8 If x Then 'BIND1:"x" System.Console.WriteLine("If") Else System.Console.WriteLine("Else") End If If x AndAlso y Then End If End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New TrueFalseUnaryOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x").WithLocation(27, 12), Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x AndAlso y").WithLocation(33, 12)) End Sub <Fact> Public Sub TestOperationBlockAnalyzer_EmptyMethodBody() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M() End Sub Public Sub M2(i as Integer) End Sub Public Sub M3(Optional i as Integer = 0) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New OperationBlockAnalyzer}, Nothing, Nothing, Diagnostic("ID", "M").WithArguments("M", "Block").WithLocation(2, 16), Diagnostic("ID", "M2").WithArguments("M2", "Block").WithLocation(5, 16), Diagnostic("ID", "M3").WithArguments("M3", "ParameterInitializer").WithLocation(8, 16), Diagnostic("ID", "M3").WithArguments("M3", "Block").WithLocation(8, 16)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics <CompilerTrait(CompilerFeature.IOperation)> Public Class OperationAnalyzerTests Inherits BasicTestBase <Fact> Public Sub EmptyArrayVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Sub M1() Dim arr1 As Integer() = New Integer(-1) { } ' yes Dim arr2 As Byte() = { } ' yes Dim arr3 As C() = New C(-1) { } ' yes Dim arr4 As String() = New String() { Nothing } ' no Dim arr5 As Double() = New Double(1) { } ' no Dim arr6 As Integer() = { -1 } ' no Dim arr7 as Integer()() = New Integer(-1)() { } ' yes Dim arr8 as Integer()()()() = New Integer( -1)()()() { } ' yes Dim arr9 as Integer(,) = New Integer(-1,-1) { } ' no Dim arr10 as Integer()(,) = New Integer(-1)(,) { } ' yes Dim arr11 as Integer()(,) = New Integer(1)(,) { } ' no Dim arr12 as Integer(,)() = New Integer(-1,-1)() { } ' no Dim arr13 as Integer() = New Integer(0) { } ' no End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EmptyArrayAnalyzer}, Nothing, Nothing, Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1) { }").WithLocation(3, 33), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "{ }").WithLocation(4, 30), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New C(-1) { }").WithLocation(5, 27), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)() { }").WithLocation(9, 35), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer( -1)()()() { }").WithLocation(10, 39), Diagnostic(EmptyArrayAnalyzer.UseArrayEmptyDescriptor.Id, "New Integer(-1)(,) { }").WithLocation(12, 37)) End Sub <Fact> Public Sub BoxingVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(p1 As Object, p2 As Object, p3 As Object) As Object Dim v1 As New S Dim v2 As S = v1 Dim v3 As S = v1.M1(v2) Dim v4 As Object = M1(3, Me, v1) Dim v5 As Object = v3 If p1 Is Nothing return 3 End If If p2 Is Nothing return v3 End If If p3 Is Nothing Return v4 End If Return v5 End Function End Class Structure S Public X As Integer Public Y As Integer Public Z As Object Public Function M1(p1 As S) As S p1.GetType() Z = Me Return p1 End Function End Structure ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BoxingOperationAnalyzer}, Nothing, Nothing, Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(6, 32), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v1").WithLocation(6, 39), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(7, 29), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "3").WithLocation(9, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "v3").WithLocation(12, 21), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "p1").WithLocation(27, 9), Diagnostic(BoxingOperationAnalyzer.BoxingDescriptor.Id, "Me").WithLocation(28, 13)) End Sub <Fact> Public Sub BadStuffVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(z as Integer) Framitz() Dim x As Integer = Bexley() Dim y As Integer = 10 Dim d As Double() = Nothing M1(d) Goto End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyAnalyzerDiagnostics({New BadStuffTestAnalyzer}, Nothing, Nothing, Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz()").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz()").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Framitz").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Framitz").WithLocation(3, 9), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley()").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley()").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "Bexley").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Bexley").WithLocation(4, 28), Diagnostic(BadStuffTestAnalyzer.InvalidExpressionDescriptor.Id, "M1(d)").WithLocation(7, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "M1(d)").WithLocation(7, 9), Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "Goto").WithLocation(8, 9), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "Goto").WithLocation(8, 9), Diagnostic(BadStuffTestAnalyzer.InvalidStatementDescriptor.Id, "").WithLocation(8, 13), Diagnostic(BadStuffTestAnalyzer.IsInvalidDescriptor.Id, "").WithLocation(8, 13)) End Sub <Fact> Public Sub SwitchVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select Select Case x Case Else Exit Select End Select Select Case x End Select Select Case x Case 1 Exit Select Case Exit Select End Select Select Case x Case 1 Exit Select Case = Exit Select End Select Select Case x Case 1 Exit Select Case 2 to Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(60, 17), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(68, 1), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(74, 22)) comp.VerifyAnalyzerDiagnostics({New SwitchTestAnalyzer}, Nothing, Nothing, Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(12, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(30, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(37, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(37, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(42, 21), Diagnostic(SwitchTestAnalyzer.OnlyDefaultSwitchDescriptor.Id, "x").WithLocation(49, 21), Diagnostic(SwitchTestAnalyzer.SparseSwitchDescriptor.Id, "x").WithLocation(54, 21), Diagnostic(SwitchTestAnalyzer.NoDefaultSwitchDescriptor.Id, "x").WithLocation(54, 21)) End Sub <Fact> Public Sub InvocationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1(a As Integer, b As Integer, c As Integer, x As Integer, y As Integer, z As Integer) End Sub Public Sub M2() M1(1, 2, 3, 4, 5, 6) M1(a:=1, b:=2, c:=3, x:=4, y:=5, z:=6) M1(a:=1, c:=2, b:=3, x:=4, y:=5, z:=6) M1(z:=1, x:=2, y:=3, c:=4, a:=5, b:=6) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) M0(1) M0(1, 2, 4, 3) End Sub Public Sub M3(Optional a As Integer = Nothing, Optional b As Integer = 0) End Sub Public Sub M4() M3(Nothing, 0) M3(Nothing,) M3(,0) M3(,) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New InvocationTestAnalyzer}, Nothing, Nothing, Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(Nothing,)").WithArguments("b").WithLocation(25, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,0)").WithArguments("a").WithLocation(26, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,)").WithArguments("a").WithLocation(27, 9), Diagnostic(InvocationTestAnalyzer.UseDefaultArgumentDescriptor.Id, "M3(,)").WithArguments("b").WithLocation(27, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(11, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "4").WithLocation(12, 33), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "2").WithLocation(12, 21), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "1").WithLocation(12, 15), Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)").WithLocation(14, 9), Diagnostic(InvocationTestAnalyzer.BigParamArrayArgumentsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)").WithLocation(15, 9), Diagnostic(InvocationTestAnalyzer.OutOfNumericalOrderArgumentsDescriptor.Id, "3").WithLocation(17, 21)) End Sub <Fact> Public Sub FieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer Public Const F2 As Integer = 2 Public ReadOnly F3 As Integer Public F4 As Integer Public F5 As Integer Public F6 As Integer = 6 Public F7 As Integer Public F9 As S Public F10 As New C1 Public Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 12), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 12)) End Sub <Fact> Public Sub StaticFieldCouldBeReadOnlyVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Shared F1 As Integer Public Shared ReadOnly F2 As Integer = 2 Public Shared Readonly F3 As Integer Public Shared F4 As Integer Public Shared F5 As Integer Public Shared F6 As Integer = 6 Public Shared F7 As Integer Public Shared F9 As S Public Shared F10 As New C1 Shared Sub New() F1 = 1 F4 = 4 F5 = 5 End Sub Public Shared Sub M0() Dim x As Integer = F1 x = F2 x = F3 x = F4 x = F5 x = F6 x = F7 F4 = 4 F7 = 7 M1(F1, F5) F9.A = 10 F9.B = 20 F10.A = F9.A F10.B = F9.B End Sub Public Shared Sub M1(ByRef X As Integer, Y As Integer) x = 10 End Sub Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New FieldCouldBeReadOnlyAnalyzer}, Nothing, Nothing, Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F5").WithLocation(6, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F6").WithLocation(7, 19), Diagnostic(FieldCouldBeReadOnlyAnalyzer.FieldCouldBeReadOnlyDescriptor.Id, "F10").WithLocation(10, 19)) End Sub <Fact> Public Sub LocalCouldBeConstVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(p as Integer) Dim x As Integer = p Dim y As Integer = x Const z As Integer = 1 Dim a As Integer = 2 Dim b As Integer = 3 Dim c As Integer = 4 Dim d As Integer = 5 Dim e As Integer = 6 Dim s As String = "ZZZ" b = 3 c -= 12 d += e + b M1(y, z, a, s) Dim n As S n.A = 10 n.B = 20 Dim o As New C1 o.A = 10 o.B = 20 End Sub Public Sub M1(ByRef x As Integer, y As Integer, ByRef z as Integer, s as String) x = 10 End Sub End Class Structure S Public A As Integer Public B As Integer End Structure Class C1 Public A As Integer Public B As Integer End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LocalCouldBeConstAnalyzer}, Nothing, Nothing, Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "e").WithLocation(10, 13), Diagnostic(LocalCouldBeConstAnalyzer.LocalCouldBeConstDescriptor.Id, "s").WithLocation(11, 13)) End Sub <Fact> Public Sub SymbolCouldHaveMoreSpecificTypeVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0() Dim a As Object = New Middle() Dim b As Object = New Value(10) Dim c As Object = New Middle() c = New Base() Dim d As Base = New Derived() Dim e As Base = New Derived() e = New Middle() Dim f As Base = New Middle() f = New Base() Dim g As Object = New Derived() g = New Base() g = New Middle() Dim h As New Middle() h = New Derived() Dim i As Object = 3 Dim j As Object j = 10 j = 10.1 Dim k As Middle = New Derived() Dim l As Middle = New Derived() Dim o As Object = New Middle() MM(l, o) Dim ibase1 As IBase1 = Nothing Dim ibase2 As IBase2 = Nothing Dim imiddle As IMiddle = Nothing Dim iderived As IDerived = Nothing Dim ia As Object = imiddle Dim ic As Object = imiddle ic = ibase1 Dim id As IBase1 = iderived Dim ie As IBase1 = iderived ie = imiddle Dim iff As IBase1 = imiddle iff = ibase1 Dim ig As Object = iderived ig = ibase1 ig = imiddle Dim ih = imiddle ih = iderived Dim ik As IMiddle = iderived Dim il As IMiddle = iderived Dim io As Object = imiddle IMM(il, io) Dim im As IBase2 = iderived Dim isink As Object = ibase2 isink = 3 End Sub Private fa As Object = New Middle() Private fb As Object = New Value(10) Private fc As Object = New Middle() Private fd As Base = New Derived() Private fe As Base = New Derived() Private ff As Base = New Middle() Private fg As Object = New Derived() Private fh As New Middle() Private fi As Object = 3 Private fj As Object Private fk As Middle = New Derived() Private fl As Middle = New Derived() Private fo As Object = New Middle() Private Shared fibase1 As IBase1 = Nothing Private Shared fibase2 As IBase2 = Nothing Private Shared fimiddle As IMiddle= Nothing Private Shared fiderived As IDerived = Nothing Private fia As Object = fimiddle Private fic As Object = fimiddle Private fid As IBase1 = fiderived Private fie As IBase1 = fiderived Private fiff As IBase1 = fimiddle Private fig As Object = fiderived Private fih As IMiddle = fimiddle Private fik As IMiddle = fiderived Private fil As IMiddle = fiderived Private fio As Object = fimiddle Private fisink As Object = fibase2 Private fim As IBase2 = fiderived Sub M1() fc = New Base() fe = New Middle() ff = New Base() fg = New Base() fg = New Middle() fh = New Derived() fj = 10 fj = 10.1 MM(fl, fo) fic = fibase1 fie = fimiddle fiff = fibase1 fig = fibase1 fig = fimiddle fih = fiderived IMM(fil, fio) fisink = 3 End Sub Sub MM(ByRef p1 As Middle, ByRef p2 As Object) p1 = New Middle() p2 = Nothing End Sub Sub IMM(ByRef p1 As IMiddle, ByRef p2 As object) p1 = Nothing p2 = Nothing End Sub End Class Class Base End Class Class Middle Inherits Base End Class Class Derived Inherits Middle End Class Structure Value Public Sub New(a As Integer) X = a End Sub Public X As Integer End Structure Interface IBase1 End Interface Interface IBase2 End Interface Interface IMiddle Inherits IBase1 End Interface Interface IDerived Inherits IMiddle Inherits IBase2 End Interface ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SymbolCouldHaveMoreSpecificTypeAnalyzer}, Nothing, Nothing, Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "a").WithArguments("a", "Middle").WithLocation(3, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "b").WithArguments("b", "Value").WithLocation(4, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "c").WithArguments("c", "Base").WithLocation(5, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "d").WithArguments("d", "Derived").WithLocation(7, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "e").WithArguments("e", "Middle").WithLocation(8, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "g").WithArguments("g", "Base").WithLocation(12, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "i").WithArguments("i", "Integer").WithLocation(17, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "k").WithArguments("k", "Derived").WithLocation(21, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ia").WithArguments("ia", "IMiddle").WithLocation(31, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ic").WithArguments("ic", "IBase1").WithLocation(32, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "id").WithArguments("id", "IDerived").WithLocation(34, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ie").WithArguments("ie", "IMiddle").WithLocation(35, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ig").WithArguments("ig", "IBase1").WithLocation(39, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "ik").WithArguments("ik", "IDerived").WithLocation(44, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.LocalCouldHaveMoreSpecificTypeDescriptor.Id, "im").WithArguments("im", "IDerived").WithLocation(48, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fa").WithArguments("Private fa As Object", "Middle").WithLocation(53, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fb").WithArguments("Private fb As Object", "Value").WithLocation(54, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fc").WithArguments("Private fc As Object", "Base").WithLocation(55, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fd").WithArguments("Private fd As Base", "Derived").WithLocation(56, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fe").WithArguments("Private fe As Base", "Middle").WithLocation(57, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fg").WithArguments("Private fg As Object", "Base").WithLocation(59, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fi").WithArguments("Private fi As Object", "Integer").WithLocation(61, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fk").WithArguments("Private fk As Middle", "Derived").WithLocation(63, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fia").WithArguments("Private fia As Object", "IMiddle").WithLocation(72, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fic").WithArguments("Private fic As Object", "IBase1").WithLocation(73, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fid").WithArguments("Private fid As IBase1", "IDerived").WithLocation(74, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fie").WithArguments("Private fie As IBase1", "IMiddle").WithLocation(75, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fig").WithArguments("Private fig As Object", "IBase1").WithLocation(77, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fik").WithArguments("Private fik As IMiddle", "IDerived").WithLocation(79, 13), Diagnostic(SymbolCouldHaveMoreSpecificTypeAnalyzer.FieldCouldHaveMoreSpecificTypeDescriptor.Id, "fim").WithArguments("Private fim As IBase2", "IDerived").WithLocation(83, 13)) End Sub <Fact> Public Sub ValueContextsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(Optional a As Integer = 16, Optional b As Integer = 17, Optional c As Integer = 18) End Sub Public F1 As Integer = 16 Public F2 As Integer = 17 Public F3 As Integer = 18 Public Sub M1() M0(16, 17, 18) M0(f1, f2, f3) M0() End Sub End Class Enum E A = 16 B C = 17 D = 18 End Enum Class C1 Public Sub New (a As Integer, b As Integer, c As Integer) End Sub Public F1 As C1 = New C1(c:=16, a:=17, b:=18) Public F2 As New C1(16, 17, 18) Public F3(16) As Integer Public F4(17) As Integer ' The upper bound specification is not presently treated as a code block. This is suspect. Public F5(18) As Integer Public F6 As Integer() = New Integer(16) {} Public F7 As Integer() = New Integer(17) {} End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New SeventeenTestAnalyzer}, Nothing, Nothing, Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(2, 71), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(6, 28), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(10, 16), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(19, 9), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(27, 40), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(28, 29), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "17").WithLocation(33, 42), Diagnostic(SeventeenTestAnalyzer.SeventeenDescriptor.Id, "M0").WithLocation(12, 9)) ' The M0 diagnostic is an artifact of the VB compiler filling in default values in the high-level bound tree, and is questionable. End Sub <Fact> Public Sub NullArgumentVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Goo Public Sub New(X As String) End Sub End Class Class C Public Sub M0(x As String, y As String) End Sub Public Sub M1() M0("""", """") M0(Nothing, """") M0("""", Nothing) M0(Nothing, Nothing) End Sub Public Sub M2() Dim f1 = New Goo("""") Dim f2 = New Goo(Nothing) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NullArgumentTestAnalyzer}, Nothing, Nothing, Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(13, 12), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(14, 18), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(15, 12), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(15, 21), Diagnostic(NullArgumentTestAnalyzer.NullArgumentsDescriptor.Id, "Nothing").WithLocation(20, 26)) End Sub <Fact> Public Sub MemberInitializerVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Bar Public Field As Boolean End Class Class Goo Public Field As Integer Public Property Prop1 As String Public Property Prop2 As Bar End Class Class C Public Sub M1() Dim f1 = New Goo() Dim f2 = New Goo() With {.Field = 10} Dim f3 = New Goo With {.Prop1 = Nothing} Dim f4 = New Goo With {.Field = 10, .Prop1 = Nothing} Dim f5 = New Goo With {.Prop2 = New Bar() With {.Field = True}} Dim e1 = New Goo() With {.Prop1 = 10} Dim e2 = New Goo With {10} End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQualifiedNameInInit, "").WithLocation(20, 32)) comp.VerifyAnalyzerDiagnostics({New MemberInitializerTestAnalyzer}, Nothing, Nothing, Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(14, 35), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(15, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(16, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(16, 46), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop2").WithLocation(17, 33), Diagnostic(MemberInitializerTestAnalyzer.DoNotUseFieldInitializerDescriptor.Id, "Field").WithLocation(17, 58), Diagnostic(MemberInitializerTestAnalyzer.DoNotUsePropertyInitializerDescriptor.Id, "Prop1").WithLocation(19, 35)) End Sub <Fact> Public Sub AssignmentVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class Bar Public Field As Boolean End Class Class Goo Public Field As Integer Public Property Prop1 As String Public Property Prop2 As Bar End Class Class C Public Sub M1() Dim f1 = New Goo() Dim f2 = New Goo() With {.Field = 10} Dim f3 = New Goo With {.Prop1 = Nothing} Dim f4 = New Goo With {.Field = 10, .Prop1 = Nothing} Dim f5 = New Goo With {.Prop2 = New Bar() With {.Field = True}} End Sub Public Sub M2() Dim f1 = New Goo With {.Prop2 = New Bar() With {.Field = True}} f1.Field = 0 f1.Prop1 = Nothing Dim f2 = New Bar() f2.Field = True End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New AssignmentTestAnalyzer}, Nothing, Nothing, Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop2 = New Bar() With {.Field = True}").WithLocation(21, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = 10").WithLocation(14, 34), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop1 = Nothing").WithLocation(15, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = 10").WithLocation(16, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop1 = Nothing").WithLocation(16, 45), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Prop2 = New Bar() With {.Field = True}").WithLocation(17, 32), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = True").WithLocation(17, 57), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, ".Field = True").WithLocation(21, 57), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f1.Field = 0").WithLocation(22, 9), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f1.Prop1 = Nothing").WithLocation(23, 9), Diagnostic(AssignmentTestAnalyzer.DoNotUseMemberAssignmentDescriptor.Id, "f2.Field = True").WithLocation(26, 9)) End Sub <Fact> Public Sub ArrayInitializerVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1() Dim arr1 = New Integer() {} Dim arr2 As Object = {} Dim arr3 = {} Dim arr4 = New Integer() {1, 2, 3} Dim arr5 = {1, 2, 3} Dim arr6 As C() = {Nothing, Nothing, Nothing} Dim arr7 = New Integer() {1, 2, 3, 4, 5, 6} ' LargeList Dim arr8 = {1, 2, 3, 4, 5, 6} ' LargeList Dim arr9 As C() = {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing} ' LargeList Dim arr10 As Integer(,) = {{1, 2, 3, 4, 5, 6}} ' LargeList Dim arr11 = New Integer(,) {{1, 2, 3, 4, 5, 6}, ' LargeList {7, 8, 9, 10, 11, 12}} ' LargeList Dim arr12 As C(,) = {{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}, ' LargeList {Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}} ' LargeList Dim arr13 = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}} ' jagged array Dim arr14 = {({1, 2, 3}), ({4, 5}), ({6}), ({7})} Dim arr15 = {({({1, 2, 3, 4, 5, 6})})} ' LargeList End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ArrayInitializerTestAnalyzer()}, Nothing, Nothing, Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(11, 34), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(12, 20), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(13, 27), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(15, 36), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(16, 37), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{7, 8, 9, 10, 11, 12}").WithLocation(17, 37), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(18, 30), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}").WithLocation(19, 29), Diagnostic(ArrayInitializerTestAnalyzer.DoNotUseLargeListOfArrayInitializersDescriptor.Id, "{1, 2, 3, 4, 5, 6}").WithLocation(24, 25)) End Sub <Fact> Public Sub VariableDeclarationVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C #Disable Warning BC42024 Dim field1, field2, field3, field4 As Integer Public Sub M1() Dim a1 = 10 Dim b1 As New Integer, b2, b3, b4 As New Goo(1) 'too many Dim c1, c2 As Integer, c3, c4 As Goo 'too many Dim d1() As Goo Dim e1 As Integer = 10, e2 = {1, 2, 3}, e3, e4 As C 'too many Dim f1 = 10, f2 = 11, f3 As Integer Dim h1, h2, , h3 As Integer 'too many Dim i1, i2, i3, i4 As New UndefType 'too many Dim j1, j2, j3, j4 As UndefType 'too many Dim k1 As Integer, k2, k3, k4 As New Goo(1) 'too many End Sub #Enable Warning BC42024 End Class Class Goo Public Sub New(X As Integer) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedIdentifier, "").WithLocation(11, 21), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(12, 35), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31), Diagnostic(ERRID.ERR_UndefinedType1, "UndefType").WithArguments("UndefType").WithLocation(13, 31)) comp.VerifyAnalyzerDiagnostics({New VariableDeclarationTestAnalyzer}, Nothing, Nothing, Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "a1").WithLocation(5, 13), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim b1 As New Integer, b2, b3, b4 As New Goo(1)").WithLocation(6, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b1").WithLocation(6, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b2").WithLocation(6, 32), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b3").WithLocation(6, 36), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "b4").WithLocation(6, 40), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim c1, c2 As Integer, c3, c4 As Goo").WithLocation(7, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim e1 As Integer = 10, e2 = {1, 2, 3}, e3, e4 As C").WithLocation(9, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e1").WithLocation(9, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "e2").WithLocation(9, 33), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "f1").WithLocation(10, 13), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "f2").WithLocation(10, 22), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim h1, h2, , h3 As Integer").WithLocation(11, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim i1, i2, i3, i4 As New UndefType").WithLocation(12, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim j1, j2, j3, j4 As UndefType").WithLocation(13, 9), Diagnostic(VariableDeclarationTestAnalyzer.TooManyLocalVarDeclarationsDescriptor.Id, "Dim k1 As Integer, k2, k3, k4 As New Goo(1)").WithLocation(14, 9), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k2").WithLocation(14, 28), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k3").WithLocation(14, 32), Diagnostic(VariableDeclarationTestAnalyzer.LocalVarInitializedDeclarationDescriptor.Id, "k4").WithLocation(14, 36)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub CaseVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x As Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select Select Case x Case 1 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 10 To 500 Exit Select Case = 1000 Exit Select Case Else Exit Select End Select Select Case x Case 1, 980 To 985 Exit Select Case Else Exit Select End Select Select Case x Case 1 to 3, 980 To 985 Exit Select End Select Select Case x Case 1 Exit Select Case > 100000 Exit Select End Select Select Case x Case Else Exit Select End Select Select Case x End Select Select Case x Case 1 Exit Select Case Exit Select End Select Select Case x Case 1 Exit Select Case = Exit Select End Select Select Case x Case 1 Exit Select Case 2 to Exit Select End Select End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(60, 17), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(68, 1), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(74, 22)) comp.VerifyAnalyzerDiagnostics({New CaseTestAnalyzer}, Nothing, Nothing, Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1, 2 Exit Select").WithLocation(4, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(8, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(17, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(26, 13), Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1, 980 To 985 Exit Select").WithLocation(31, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(33, 13), Diagnostic(CaseTestAnalyzer.MultipleCaseClausesDescriptor.Id, "Case 1 to 3, 980 To 985 Exit Select").WithLocation(38, 13), Diagnostic(CaseTestAnalyzer.HasDefaultCaseDescriptor.Id, "Case Else").WithLocation(50, 13)) End Sub <Fact> Public Sub ExplicitVsImplicitInstancesVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Overridable Sub M1() Me.M1() M1() End Sub Public Sub M2() End Sub End Class Class D Inherits C Public Overrides Sub M1() MyBase.M1() M1() M2() End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ExplicitVsImplicitInstanceAnalyzer}, Nothing, Nothing, Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "Me").WithLocation(3, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(4, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ExplicitInstanceDescriptor.Id, "MyBase").WithLocation(13, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M1").WithLocation(14, 9), Diagnostic(ExplicitVsImplicitInstanceAnalyzer.ImplicitInstanceDescriptor.Id, "M2").WithLocation(15, 9)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29531")> Public Sub EventAndMethodReferencesVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Delegate Sub MumbleEventHandler(sender As Object, args As System.EventArgs) Class C Public Event Mumble As MumbleEventHandler Public Sub OnMumble(args As System.EventArgs) AddHandler Mumble, New MumbleEventHandler(AddressOf Mumbler) AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As System.EventArgs) End Sub) AddHandler Mumble, Sub(s As Object, a As System.EventArgs) End Sub RaiseEvent Mumble(Me, args) ' Dim o As object = AddressOf Mumble Dim d As MumbleEventHandler = AddressOf Mumbler Mumbler(Me, Nothing) RemoveHandler Mumble, AddressOf Mumbler End Sub Private Sub Mumbler(sender As Object, args As System.EventArgs) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New MemberReferenceAnalyzer}, Nothing, Nothing, Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, New MumbleEventHandler(AddressOf Mumbler)").WithLocation(7, 9), ' Bug: we are missing diagnostics of "MethodBindingDescriptor" here. https://github.com/dotnet/roslyn/issues/20095 Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(7, 20), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(7, 51), Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As System.EventArgs) End Sub)").WithLocation(8, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(8, 20), Diagnostic(MemberReferenceAnalyzer.HandlerAddedDescriptor.Id, "AddHandler Mumble, Sub(s As Object, a As System.EventArgs) End Sub").WithLocation(10, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(10, 20), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(12, 20), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(14, 39), Diagnostic(MemberReferenceAnalyzer.HandlerRemovedDescriptor.Id, "RemoveHandler Mumble, AddressOf Mumbler").WithLocation(16, 9), Diagnostic(MemberReferenceAnalyzer.EventReferenceDescriptor.Id, "Mumble").WithLocation(16, 23), Diagnostic(MemberReferenceAnalyzer.MethodBindingDescriptor.Id, "AddressOf Mumbler").WithLocation(16, 31) ) End Sub <Fact> Public Sub ParamArraysVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(a As Integer, ParamArray b As Integer()) End Sub Public Sub M1() M0(1) M0(1, 2) M0(1, 2, 3, 4) M0(1, 2, 3, 4, 5) M0(1, 2, 3, 4, 5, 6) M0(1, New Integer() { 2, 3, 4 }) M0(1, New Integer() { 2, 3, 4, 5 }) M0(1, New Integer() { 2, 3, 4, 5, 6 }) Dim local As D = new D(1, 2, 3, 4, 5) local = new D(1, New Integer() { 2, 3, 4, 5 }) local = new D(1, 2, 3, 4) local = new D(1, New Integer() { 2, 3, 4 }) End Sub End Class Class D Public Sub New(a As Integer, ParamArray b As Integer()) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New ParamsArrayTestAnalyzer}, Nothing, Nothing, Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5)").WithLocation(9, 9), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "M0(1, 2, 3, 4, 5, 6)").WithLocation(10, 9), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5 }").WithLocation(12, 15), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5, 6 }").WithLocation(13, 15), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "D").WithLocation(14, 30), Diagnostic(ParamsArrayTestAnalyzer.LongParamsDescriptor.Id, "New Integer() { 2, 3, 4, 5 }").WithLocation(15, 26)) End Sub <Fact> Public Sub FieldInitializersVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public F1 As Integer = 44 Public F2 As String = "Hello" Public F3 As Integer = Goo() Public Shared Function Goo() Return 10 End Function Public Shared Function Bar(Optional P1 As Integer = 10, Optional F2 As Integer = 20) Return P1 + F2 End Function End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New EqualsValueTestAnalyzer}, Nothing, Nothing, Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 44").WithLocation(2, 26), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= ""Hello""").WithLocation(3, 25), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= Goo()").WithLocation(4, 26), Diagnostic(EqualsValueTestAnalyzer.EqualsValueDescriptor.Id, "= 20").WithLocation(10, 84)) End Sub <Fact> Public Sub OwningSymbolVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub UnFunkyMethod() Dim x As Integer = 0 Dim y As Integer = x End Sub Public Sub FunkyMethod() Dim x As Integer = 0 Dim y As Integer = x End Sub Public FunkyField As Integer = 12 Public UnFunkyField As Integer = 12 End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New OwningSymbolTestAnalyzer}, Nothing, Nothing, Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(8, 28), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(9, 28), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(12, 36)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub NoneOperationVisualBasic() ' BoundCaseStatement is OperationKind.None Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M1(x as Integer) Select Case x Case 1, 2 Exit Select Case = 10 Exit Select Case Else Exit Select End Select End Sub Public Property Fred As Integer Set(value As Integer) Exit Property End Set Get Return 12 End Get End Property Public Sub Barney Resume End Sub End Class ]]> </file> </compilation> ' We have 2 OperationKind.None operations in the operation tree: ' (1) BoundUnstructuredExceptionHandlingStatement for the method block with Resume statement ' (2) BoundResumeStatement for Resume statement Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NoneOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(NoneOperationTestAnalyzer.NoneOperationDescriptor.Id, <![CDATA[Public Sub Barney Resume End Sub]]>).WithLocation(22, 5), Diagnostic(NoneOperationTestAnalyzer.NoneOperationDescriptor.Id, "Resume").WithLocation(23, 9)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub LambdaExpressionVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Class B Public Sub M1(x As Integer) Dim action1 As Action = Sub() End Sub Dim action2 As Action = Sub() Console.WriteLine(1) End Sub Dim func1 As Func(Of Integer, Integer) = Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function End Sub End Class Delegate Sub MumbleEventHandler(sender As Object, args As EventArgs) Class C Public Event Mumble As MumbleEventHandler Public Sub OnMumble(args As EventArgs) AddHandler Mumble, New MumbleEventHandler(Sub(s As Object, a As EventArgs) End Sub) AddHandler Mumble, Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub RaiseEvent Mumble(Me, args) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LambdaTestAnalyzer}, Nothing, Nothing, Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub() End Sub").WithLocation(5, 33), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) End Sub").WithLocation(25, 51), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub() Console.WriteLine(1) End Sub").WithLocation(7, 33), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub").WithLocation(27, 28), Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "Sub(s As Object, a As EventArgs) Dim value = 1 value = value + 1 value = value + 1 value = value + 1 End Sub").WithLocation(27, 28), Diagnostic(LambdaTestAnalyzer.LambdaExpressionDescriptor.Id, "Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function").WithLocation(10, 50), Diagnostic(LambdaTestAnalyzer.TooManyStatementsInLambdaExpressionDescriptor.Id, "Function(value As Integer) value = value + 1 value = value + 1 value = value + 1 Return value + 1 End Function").WithLocation(10, 50)) End Sub <WorkItem(8385, "https://github.com/dotnet/roslyn/issues/8385")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/18839")> Public Sub StaticMemberReferenceVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class D Public Shared Event E() Public Shared Field As Integer Public Shared Property P As Integer Public Shared Sub Method() End Sub End Class Class C Public Shared Event E() Public Shared Sub Bar() End Sub Public Sub Goo() AddHandler C.E, AddressOf D.Method RaiseEvent E() ' Can't raise static event with type in VB C.Bar() AddHandler D.E, Sub() End Sub D.Field = 1 Dim x = D.P D.Method() End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New StaticMemberTestAnalyzer}, Nothing, Nothing, Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddHandler C.E, AddressOf D.Method").WithLocation(19, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddressOf D.Method").WithLocation(19, 25), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "E").WithLocation(20, 20), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "C.Bar()").WithLocation(21, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "AddHandler D.E, Sub() End Sub").WithLocation(23, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Field").WithLocation(25, 9), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.P").WithLocation(26, 17), Diagnostic(StaticMemberTestAnalyzer.StaticMemberDescriptor.Id, "D.Method()").WithLocation(27, 9)) End Sub <Fact> Public Sub LabelOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class A Public Sub Fred() Wilma: GoTo Betty Betty: GoTo Wilma End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New LabelOperationsTestAnalyzer}, Nothing, Nothing, Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Wilma:").WithLocation(3, 9), Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "GoTo Betty").WithLocation(4, 9), Diagnostic(LabelOperationsTestAnalyzer.LabelDescriptor.Id, "Betty:").WithLocation(5, 9), Diagnostic(LabelOperationsTestAnalyzer.GotoDescriptor.Id, "GoTo Wilma").WithLocation(6, 9)) End Sub <Fact> Public Sub UnaryBinaryOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class A Private ReadOnly _value As Integer Public Sub New (value As Integer) _value = value End Sub Public Shared Operator +(x As A, Y As A) As A Return New A(x._value + y._value) End Operator Public Shared Operator *(x As A, y As A) As A Return New A(x._value * y._value) End Operator Public Shared Operator -(x As A) As A Return New A(-x._value) End Operator Public Shared operator +(x As A) As A Return New A(+x._value) End Operator End CLass Class C Public Shared Sub Main() Dim B As Boolean = False Dim d As Double = 100 Dim a1 As New A(0) Dim a2 As New A(100) b = Not b d = d * 100 a1 = a1 + a2 a1 = -a2 End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New UnaryAndBinaryOperationsTestAnalyzer}, Nothing, Nothing, Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.BooleanNotDescriptor.Id, "Not b").WithLocation(33, 13), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.DoubleMultiplyDescriptor.Id, "d * 100").WithLocation(34, 13), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorAddMethodDescriptor.Id, "a1 + a2").WithLocation(35, 14), Diagnostic(UnaryAndBinaryOperationsTestAnalyzer.OperatorMinusMethodDescriptor.Id, "-a2").WithLocation(36, 14)) End Sub <Fact> Public Sub BinaryOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class B2 Public Shared Operator +(x As B2, y As B2) As B2 System.Console.WriteLine("+") Return x End Operator Public Shared Operator -(x As B2, y As B2) As B2 System.Console.WriteLine("-") Return x End Operator Public Shared Operator *(x As B2, y As B2) As B2 System.Console.WriteLine("*") Return x End Operator Public Shared Operator /(x As B2, y As B2) As B2 System.Console.WriteLine("/") Return x End Operator Public Shared Operator \(x As B2, y As B2) As B2 System.Console.WriteLine("\") Return x End Operator Public Shared Operator Mod(x As B2, y As B2) As B2 System.Console.WriteLine("Mod") Return x End Operator Public Shared Operator ^(x As B2, y As B2) As B2 System.Console.WriteLine("^") Return x End Operator Public Shared Operator =(x As B2, y As B2) As B2 System.Console.WriteLine("=") Return x End Operator Public Shared Operator <>(x As B2, y As B2) As B2 System.Console.WriteLine("<>") Return x End Operator Public Shared Operator <(x As B2, y As B2) As B2 System.Console.WriteLine("<") Return x End Operator Public Shared Operator >(x As B2, y As B2) As B2 System.Console.WriteLine(">") Return x End Operator Public Shared Operator <=(x As B2, y As B2) As B2 System.Console.WriteLine("<=") Return x End Operator Public Shared Operator >=(x As B2, y As B2) As B2 System.Console.WriteLine(">=") Return x End Operator Public Shared Operator Like(x As B2, y As B2) As B2 System.Console.WriteLine("Like") Return x End Operator Public Shared Operator &(x As B2, y As B2) As B2 System.Console.WriteLine("&") Return x End Operator Public Shared Operator And(x As B2, y As B2) As B2 System.Console.WriteLine("And") Return x End Operator Public Shared Operator Or(x As B2, y As B2) As B2 System.Console.WriteLine("Or") Return x End Operator Public Shared Operator Xor(x As B2, y As B2) As B2 System.Console.WriteLine("Xor") Return x End Operator Public Shared Operator <<(x As B2, y As Integer) As B2 System.Console.WriteLine("<<") Return x End Operator Public Shared Operator >>(x As B2, y As Integer) As B2 System.Console.WriteLine(">>") Return x End Operator End Class Module Module1 Sub Main() Dim x, y As New B2() Dim r As B2 r = x + y r = x - y r = x * y r = x / y r = x \ y r = x Mod y r = x ^ y r = x = y r = x <> y r = x < y r = x > y r = x <= y r = x >= y r = x Like y r = x & y r = x And y r = x Or y r = x Xor y r = x << 2 r = x >> 3 End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New BinaryOperatorVBTestAnalyzer}, Nothing, Nothing, Diagnostic("BinaryUserDefinedOperator", "x + y").WithArguments("Add").WithLocation(109, 13), Diagnostic("BinaryUserDefinedOperator", "x - y").WithArguments("Subtract").WithLocation(110, 13), Diagnostic("BinaryUserDefinedOperator", "x * y").WithArguments("Multiply").WithLocation(111, 13), Diagnostic("BinaryUserDefinedOperator", "x / y").WithArguments("Divide").WithLocation(112, 13), Diagnostic("BinaryUserDefinedOperator", "x \ y").WithArguments("IntegerDivide").WithLocation(113, 13), Diagnostic("BinaryUserDefinedOperator", "x Mod y").WithArguments("Remainder").WithLocation(114, 13), Diagnostic("BinaryUserDefinedOperator", "x ^ y").WithArguments("Power").WithLocation(115, 13), Diagnostic("BinaryUserDefinedOperator", "x = y").WithArguments("Equals").WithLocation(116, 13), Diagnostic("BinaryUserDefinedOperator", "x <> y").WithArguments("NotEquals").WithLocation(117, 13), Diagnostic("BinaryUserDefinedOperator", "x < y").WithArguments("LessThan").WithLocation(118, 13), Diagnostic("BinaryUserDefinedOperator", "x > y").WithArguments("GreaterThan").WithLocation(119, 13), Diagnostic("BinaryUserDefinedOperator", "x <= y").WithArguments("LessThanOrEqual").WithLocation(120, 13), Diagnostic("BinaryUserDefinedOperator", "x >= y").WithArguments("GreaterThanOrEqual").WithLocation(121, 13), Diagnostic("BinaryUserDefinedOperator", "x Like y").WithArguments("Like").WithLocation(122, 13), Diagnostic("BinaryUserDefinedOperator", "x & y").WithArguments("Concatenate").WithLocation(123, 13), Diagnostic("BinaryUserDefinedOperator", "x And y").WithArguments("And").WithLocation(124, 13), Diagnostic("BinaryUserDefinedOperator", "x Or y").WithArguments("Or").WithLocation(125, 13), Diagnostic("BinaryUserDefinedOperator", "x Xor y").WithArguments("ExclusiveOr").WithLocation(126, 13), Diagnostic("BinaryUserDefinedOperator", "x << 2").WithArguments("LeftShift").WithLocation(127, 13), Diagnostic("BinaryUserDefinedOperator", "x >> 3").WithArguments("RightShift").WithLocation(128, 13)) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:="https://github.com/dotnet/roslyn/issues/29568")> Public Sub InvalidOperatorsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Public Class B2 Public Shared Operator +(x As B2, y As B2) As B2 System.Console.WriteLine("+") Return x End Operator Public Shared Operator -(x As B2) As B2 System.Console.WriteLine("-") Return x End Operator Public Shared Operator -(x As B2) As B2 System.Console.WriteLine("-") Return x End Operator End Class Module Module1 Sub Main() Dim x, y As New B2() x = x + 10 x = x + y x = -x End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateProcDef1, "-", New Object() {"Public Shared Operator -(x As B2) As B2"}).WithLocation(8, 28), Diagnostic(ERRID.ERR_TypeMismatch2, "10", New Object() {"Integer", "B2"}).WithLocation(23, 17), Diagnostic(ERRID.ERR_NoMostSpecificOverload2, "-x", New Object() {"-", Environment.NewLine & " 'Public Shared Operator -(x As B2) As B2': Not most specific." & vbCrLf & " 'Public Shared Operator -(x As B2) As B2': Not most specific."}).WithLocation(25, 13)) ' no diagnostic since nodes are invalid comp.VerifyAnalyzerDiagnostics({New OperatorPropertyPullerTestAnalyzer}) End Sub <Fact> Public Sub NullOperationSyntaxVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M0(ParamArray b As Integer()) End Sub Public Sub M1() M0() M0(1) M0(1, 2) M0(New Integer() { }) M0(New Integer() { 1 }) M0(New Integer() { 1, 2 }) End Sub End Class ]]> </file> </compilation> ' TODO: array should not be treated as ParamArray argument ' https://github.com/dotnet/roslyn/issues/8570 Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New NullOperationSyntaxTestAnalyzer}, Nothing, Nothing, Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0()").WithLocation(6, 9), Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1)").WithLocation(7, 9), Diagnostic(NullOperationSyntaxTestAnalyzer.ParamsArrayOperationDescriptor.Id, "M0(1, 2)").WithLocation(8, 9)) End Sub <WorkItem(8114, "https://github.com/dotnet/roslyn/issues/8114")> <Fact> Public Sub InvalidOperatorVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Function M1(a As Double, b as C) as Double Return b + c End Sub Public Function M2(s As C) As C Return -s End Function End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_EndFunctionExpected, "Public Function M1(a As Double, b as C) as Double").WithLocation(2, 5), Diagnostic(ERRID.ERR_InvalidEndSub, "End Sub").WithLocation(4, 5), Diagnostic(ERRID.ERR_InvInsideEndsProc, "Public Function M2(s As C) As C").WithLocation(6, 5), Diagnostic(ERRID.ERR_ClassNotExpression1, "c").WithArguments("C").WithLocation(3, 20), Diagnostic(ERRID.ERR_UnaryOperand2, "-s").WithArguments("-", "C").WithLocation(7, 16)) comp.VerifyAnalyzerDiagnostics({New InvalidOperatorExpressionTestAnalyzer}, Nothing, Nothing, Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidBinaryDescriptor.Id, "b + c").WithLocation(3, 16), Diagnostic(InvalidOperatorExpressionTestAnalyzer.InvalidUnaryDescriptor.Id, "-s").WithLocation(7, 16)) End Sub <WorkItem(9014, "https://github.com/dotnet/roslyn/issues/9014")> <Fact> Public Sub InvalidConstructorVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Protected Structure S End Structure End Class Class D Shared Sub M(o) M(New C.S()) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30389: 'C.S' is not accessible in this context because it is 'Protected'. M(New C.S()) ~~~ ]]></errors>) ' Reuse ParamsArrayTestAnalyzer for this test. comp.VerifyAnalyzerDiagnostics({New ParamsArrayTestAnalyzer}, Nothing, Nothing, Diagnostic(ParamsArrayTestAnalyzer.InvalidConstructorDescriptor.Id, "New C.S()").WithLocation(7, 11)) Dim tree = comp.SyntaxTrees.Single() Dim node = tree.GetRoot().DescendantNodes().OfType(Of ObjectCreationExpressionSyntax)().Single() comp.VerifyOperationTree(node, expectedOperationTree:=<![CDATA[ IObjectCreationOperation (Constructor: <null>) (OperationKind.ObjectCreation, Type: C.S, IsInvalid) (Syntax: 'New C.S()') Arguments(0) Initializer: null ]]>.Value) End Sub <Fact> Public Sub ConditionalAccessOperationsVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Property Prop As Integer Get Return 0 End Get Set End Set End Property Public Field As Integer Default Public Property Mumble(i As Integer) Get return Field End Get Set Field = Value End Set End Property Public Field1 As C = Nothing Public Sub M0(p As C) Dim x = p?.Prop x = p?.Field x = p?(0) p?.M0(Nothing) x = Field1?.Prop x = Field1?.Field x = Field1?(0) Field1?.M0(Nothing) End Sub End Class ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() ' https://github.com/dotnet/roslyn/issues/21294 comp.VerifyAnalyzerDiagnostics({New ConditionalAccessOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Prop").WithLocation(24, 17), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(24, 17), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.Field").WithLocation(25, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(25, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?(0)").WithLocation(26, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(26, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "p?.M0(Nothing)").WithLocation(27, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "p").WithLocation(27, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Prop").WithLocation(29, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(29, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.Field").WithLocation(30, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(30, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?(0)").WithLocation(31, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(31, 13), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessOperationDescriptor.Id, "Field1?.M0(Nothing)").WithLocation(32, 9), Diagnostic(ConditionalAccessOperationTestAnalyzer.ConditionalAccessInstanceOperationDescriptor.Id, "Field1").WithLocation(32, 9)) End Sub <WorkItem(8955, "https://github.com/dotnet/roslyn/issues/8955")> <Fact> Public Sub ForToLoopConditionCrashVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Module M1 Class C1(Of t) Shared Widening Operator CType(ByVal p1 As C1(Of t)) As Integer Return 1 End Operator Shared Widening Operator CType(ByVal p1 As Integer) As C1(Of t) Return Nothing End Operator Shared Operator -(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Short) Return Nothing End Operator Shared Operator +(ByVal p1 As C1(Of t), ByVal p2 As C1(Of t)) As C1(Of Integer) Return Nothing End Operator End Class Sub goo() For i As C1(Of Integer) = 1 To 10 Next End Sub End Module Module M2 ReadOnly Property Moo As Integer Get Return 1 End Get End Property WriteOnly Property Boo As integer Set(value As integer) End Set End Property Sub Main() For Moo = 1 to Moo step Moo Next For Boo = 1 to Boo step Boo Next End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_LoopControlMustNotBeProperty, "Moo").WithLocation(38, 13), Diagnostic(ERRID.ERR_LoopControlMustNotBeProperty, "Boo").WithLocation(41, 13), Diagnostic(ERRID.ERR_NoGetProperty1, "Boo").WithArguments("Boo").WithLocation(41, 24), Diagnostic(ERRID.ERR_NoGetProperty1, "Boo").WithArguments("Boo").WithLocation(41, 33), Diagnostic(ERRID.ERR_UnacceptableForLoopOperator2, "For i As C1(Of Integer) = 1 To 10").WithArguments("Public Shared Operator -(p1 As M1.C1(Of Integer), p2 As M1.C1(Of Integer)) As M1.C1(Of Short)", "M1.C1(Of Integer)").WithLocation(19, 9), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", "<=").WithLocation(19, 9), Diagnostic(ERRID.ERR_ForLoopOperatorRequired2, "For i As C1(Of Integer) = 1 To 10").WithArguments("M1.C1(Of Integer)", ">=").WithLocation(19, 9), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System").WithLocation(1, 1)) comp.VerifyAnalyzerDiagnostics({New ForLoopConditionCrashVBTestAnalyzer}, Nothing, Nothing, Diagnostic(ForLoopConditionCrashVBTestAnalyzer.ForLoopConditionCrashDescriptor.Id, "Boo").WithLocation(41, 24), Diagnostic(ForLoopConditionCrashVBTestAnalyzer.ForLoopConditionCrashDescriptor.Id, "10").WithLocation(19, 40)) End Sub <WorkItem(9012, "https://github.com/dotnet/roslyn/issues/9012")> <Fact> Public Sub InvalidEventInstanceVisualBasic() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Imports System Imports System.Collections.Generic Module Program Sub Main(args As String()) AddHandler Function(ByVal x) x End Sub End Module Class TestClass Event TestEvent As Action Shared Sub Test(receiver As TestClass) AddHandler receiver?.TestEvent, AddressOf Main End Sub Shared Sub Main() End Sub End Class Module Module1 Sub Main() Dim x = {Iterator sub() yield, new object} Dim y = {Iterator sub() yield 1, Iterator sub() yield, new object} Dim z = {Sub() AddHandler, New Object} g0(Iterator sub() Yield) g1(Iterator Sub() Yield, 5) End Sub Sub g0(ByVal x As Func(Of IEnumerator)) End Sub Sub g1(ByVal x As Func(Of IEnumerator), ByVal y As Integer) End Sub Iterator Function f() As IEnumerator Yield End Function End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_ExpectedComma, "").WithLocation(6, 39), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(6, 39), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(24, 38), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(25, 62), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(26, 34), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(27, 32), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(28, 32), Diagnostic(ERRID.ERR_ExpectedExpression, "").WithLocation(37, 14), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(31, 31), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(33, 31), Diagnostic(ERRID.ERR_TooFewGenericArguments1, "IEnumerator").WithArguments("System.Collections.Generic.IEnumerator(Of Out T)").WithLocation(36, 30), Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "receiver?.TestEvent").WithLocation(15, 20), Diagnostic(ERRID.ERR_AddOrRemoveHandlerEvent, "Function(ByVal x) x").WithLocation(6, 20), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(24, 27), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(25, 27), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(25, 51), Diagnostic(ERRID.ERR_BadIteratorReturn, "sub").WithLocation(27, 21), Diagnostic(ERRID.ERR_BadIteratorReturn, "Sub").WithLocation(28, 21), Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports System.Collections.Generic").WithLocation(2, 1)) comp.VerifyAnalyzerDiagnostics({New MemberReferenceAnalyzer}, Nothing, Nothing, Diagnostic("HandlerAdded", "AddHandler Function(ByVal x) x").WithLocation(6, 9), Diagnostic("InvalidEvent", "AddHandler Function(ByVal x) x").WithLocation(6, 9), Diagnostic("HandlerAdded", "AddHandler receiver?.TestEvent, AddressOf Main").WithLocation(15, 9), Diagnostic("InvalidEvent", "AddHandler receiver?.TestEvent, AddressOf Main").WithLocation(15, 9), Diagnostic("HandlerAdded", "AddHandler, New Object").WithLocation(26, 24), Diagnostic("InvalidEvent", "AddHandler, New Object").WithLocation(26, 24), Diagnostic("EventReference", ".TestEvent").WithLocation(15, 29)) End Sub <Fact, WorkItem(9127, "https://github.com/dotnet/roslyn/issues/9127")> Public Sub UnaryTrueFalseOperationVisualBasic() ' BoundCaseStatement is OperationKind.None Dim source = <compilation> <file name="c.vb"> <![CDATA[ Module Module1 Structure S8 Public Shared Narrowing Operator CType(x As S8) As Boolean System.Console.WriteLine("Narrowing Operator CType(x As S8) As Boolean") Return Nothing End Operator Public Shared Operator IsTrue(x As S8) As Boolean System.Console.WriteLine("IsTrue(x As S8) As Boolean") Return False End Operator Public Shared Operator IsFalse(x As S8) As Boolean System.Console.WriteLine("IsFalse(x As S8) As Boolean") Return False End Operator Public Shared Operator And(x As S8, y As S8) As S8 Return New S8() End Operator End Structure Sub Main() Dim x As New S8 Dim y As New S8 If x Then 'BIND1:"x" System.Console.WriteLine("If") Else System.Console.WriteLine("Else") End If If x AndAlso y Then End If End Sub End Module ]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New TrueFalseUnaryOperationTestAnalyzer}, Nothing, Nothing, Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x").WithLocation(27, 12), Diagnostic(TrueFalseUnaryOperationTestAnalyzer.UnaryTrueDescriptor.Id, "x AndAlso y").WithLocation(33, 12)) End Sub <Fact> Public Sub TestOperationBlockAnalyzer_EmptyMethodBody() Dim source = <compilation> <file name="c.vb"> <![CDATA[ Class C Public Sub M() End Sub Public Sub M2(i as Integer) End Sub Public Sub M3(Optional i as Integer = 0) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40AndVBRuntime(source) comp.VerifyDiagnostics() comp.VerifyAnalyzerDiagnostics({New OperationBlockAnalyzer}, Nothing, Nothing, Diagnostic("ID", "M").WithArguments("M", "Block").WithLocation(2, 16), Diagnostic("ID", "M2").WithArguments("M2", "Block").WithLocation(5, 16), Diagnostic("ID", "M3").WithArguments("M3", "ParameterInitializer").WithLocation(8, 16), Diagnostic("ID", "M3").WithArguments("M3", "Block").WithLocation(8, 16)) End Sub End Class End Namespace
-1
dotnet/roslyn
55,827
Directly reference theme keys
sharwell
2021-08-23T22:16:27Z
2021-08-24T19:52:50Z
2238b1592337286d8208f1fe25aa193941d680b7
8c2dce8f7f30b33f18f8a58c3e4250f34f9ea9f3
Directly reference theme keys.
./src/Workspaces/MSBuildTest/Resources/CircularProjectReferences/CircularSolution.sln
 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CircularCSharpProject1", "CircularCSharpProject1.csproj", "{686DD036-86AA-443E-8A10-DDB43266A8C4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CircularCSharpProject2", "CircularCSharpProject2.csproj", "{C71872E2-0D54-4C4E-B6A9-8C1726B7B78C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CircularCSharpProject1", "CircularCSharpProject1.csproj", "{686DD036-86AA-443E-8A10-DDB43266A8C4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CircularCSharpProject2", "CircularCSharpProject2.csproj", "{C71872E2-0D54-4C4E-B6A9-8C1726B7B78C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/EditorFeatures/CSharpTest/Diagnostics/GenerateType/GenerateTypeTests_Dialog.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.GenerateTypeTests { public partial class GenerateTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { #region SameProject #region SameProject_SameFile [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeDefaultValues() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|Goo$$|] f; } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { Goo f; } } class Goo { }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInsideNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.Goo$$|] f; } } namespace A { }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.Goo f; } } namespace A { class Goo { } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInsideQualifiedNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.Goo f; } } namespace A.B { class Goo { } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithinQualifiedNestedNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.C.Goo$$|] f; } } namespace A.B { namespace C { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.C.Goo f; } } namespace A.B { namespace C { class Goo { } } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithinNestedQualifiedNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.C.Goo$$|] f; } } namespace A { namespace B.C { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.C.Goo f; } } namespace A { namespace B.C { class Goo { } } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithConstructorMembers() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var f = new [|$$Goo|](bar: 1, baz: 2); } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { static void Main(string[] args) { var f = new Goo(bar: 1, baz: 2); } } class Goo { private int bar; private int baz; public Goo(int bar, int baz) { this.bar = bar; this.baz = baz; } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithBaseTypes() { await TestWithMockedGenerateTypeDialog( initial: @"using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> f = new [|$$Goo|](); } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> f = new Goo(); } } class Goo : List<int> { }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithPublicInterface() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.C.Goo$$|] f; } } namespace A { namespace B.C { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.C.Goo f; } } namespace A { namespace B.C { public interface Goo { } } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithInternalStruct() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.C.Goo$$|] f; } } namespace A { namespace B.C { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.C.Goo f; } } namespace A { namespace B.C { internal struct Goo { } } }", accessibility: Accessibility.Internal, typeKind: TypeKind.Struct, isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithDefaultEnum() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A { namespace B { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.Goo f; } } namespace A { namespace B { enum Goo { } } }", accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithDefaultEnum_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|Goo$$|] f; } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"using ConsoleApplication; class Program { void Main() { Goo f; } } namespace ConsoleApplication { enum Goo { } }", defaultNamespace: "ConsoleApplication", accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithDefaultEnum_DefaultNamespace_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A { namespace B { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.Goo f; } } namespace A { namespace B { enum Goo { } } }", defaultNamespace: "ConsoleApplication", accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); } #endregion // Working is very similar to the adding to the same file #region SameProject_ExistingFile [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> <Document FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile_Usings_Folders() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> <Document Folders= ""outer\inner"" FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace outer.inner { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile_Usings_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> <Document FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile_Usings_Folders_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> <Document Folders= ""outer\inner"" FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication.outer.inner { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication.outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile_NoUsings_Folders_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> <Document FilePath=""Test2.cs"" Folders= ""outer\inner""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } #endregion #region SameProject_NewFile [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInNewFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray<string>.Empty, newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> namespace outer { namespace inner { class Program { void Main() { [|Goo$$|] f; } } } } </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace outer.inner { public interface Goo { } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer", "inner"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNeeded_InNewFile_InFolder() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace outer.inner { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer", "inner"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer", "inner"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNeeded_InNewFile_InFolder_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication.outer.inner { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication.outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer", "inner"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> namespace ConsoleApplication.outer { class Program { void Main() { [|Goo$$|] f; } } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication.outer { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" namespace ConsoleApplication.outer { class Program { void Main() { Goo f; } } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_DefaultNamespace_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" class Program { void Main() { A.B.Goo f; } } namespace A.B { }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer"), newFileName: "Test2.cs"); } [WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_InValidFolderNameNotMadeNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> namespace outer { namespace inner { class Program { void Main() { [|Goo$$|] f; } } } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", defaultNamespace: "ConsoleApplication", expected: @"namespace ConsoleApplication { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication; namespace outer { namespace inner { class Program { void Main() { Goo f; } } } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, areFoldersValidIdentifiers: false, newFileFolderContainers: ImmutableArray.Create("123", "456"), newFileName: "Test2.cs"); } #endregion #endregion #region SameLanguageDifferentProject #region SameLanguageDifferentProject_ExistingFile [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectEmptyFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectExistingFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document Folders=""outer\inner"" FilePath=""Test2.cs""> namespace A { namespace B { } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" namespace A { namespace B { public interface Goo { } } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectExistingFile_Usings_Folders() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document Folders=""outer\inner"" FilePath=""Test2.cs""> namespace A { namespace B { } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" namespace A { namespace B { } } namespace outer.inner { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); } #endregion #region SameLanguageDifferentProject_NewFile [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace outer.inner { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication.outer.inner { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication.outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } #endregion #endregion #region DifferentLanguage [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_Usings() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace outer.inner Public Class Goo End Class End Namespace ", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_Usings_RootNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <CompilationOptions RootNamespace=""BarBaz""/> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace outer.inner Public Class Goo End Class End Namespace ", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using BarBaz.outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName_RootNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <CompilationOptions RootNamespace=""BarBaz""/> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName_RootNamespace_ProjectReference() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <CompilationOptions RootNamespace=""BarBaz""/> <Document FilePath=""Test2.vb""> Namespace A.B Public Class Goo End Class End Namespace </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <ProjectReference>Assembly2</ProjectReference> <Document FilePath=""Test1.cs""> using BarBaz.A; class Program { void Main() { [|BarBaz.A.B.Bar$$|] f; } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"Namespace A.B Public Class Bar End Class End Namespace ", defaultNamespace: "ConsoleApplication", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test3.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFileAdjustFileExtension() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageExistingEmptyFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document Folders=""outer\inner"" FilePath=""Test2.vb""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageExistingEmptyFile_Usings_Folder() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document Folders=""outer\inner"" FilePath=""Test2.vb""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace outer.inner Public Class Goo End Class End Namespace ", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageExistingNonEmptyFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document FilePath=""Test2.vb""> Namespace A End Namespace </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" Namespace A End Namespace Namespace Global.A.B Public Class Goo End Class End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageExistingNonEmptyTargetFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document FilePath=""Test2.vb""> Namespace Global Namespace A Namespace C End Namespace Namespace B End Namespace End Namespace End Namespace</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" Namespace Global Namespace A Namespace C End Namespace Namespace B Public Class Goo End Class End Namespace End Namespace End Namespace", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); } [WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] [WorkItem(869593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869593")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateModuleFromCSharpToVisualBasicInTypeContext() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.Goo$$|].Bar f; } } namespace A { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A Public Module Goo End Module End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Module, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2", assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); } #endregion #region Bugfix [WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] [WorkItem(873066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/873066")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityAndTypeKind_1() { await TestWithMockedGenerateTypeDialog( initial: @" public class C : [|$$D|] { }", languageName: LanguageNames.CSharp, typeName: "D", expected: @" public class C : D { } public class D { }", accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList, false)); } [WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityAndTypeKind_2() { await TestWithMockedGenerateTypeDialog( initial: @"public interface CCC : [|$$DDD|] { }", languageName: LanguageNames.CSharp, typeName: "DDD", expected: @"public interface CCC : DDD { } public interface DDD { }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Interface, false)); } [WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityAndTypeKind_3() { await TestWithMockedGenerateTypeDialog( initial: @"public struct CCC : [|$$DDD|] { }", languageName: LanguageNames.CSharp, typeName: "DDD", expected: @"public struct CCC : DDD { } public interface DDD { }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Interface, false)); } [WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessExpression() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$A.B|]; } }", languageName: LanguageNames.CSharp, typeName: "A", expected: @"class Program { static void Main(string[] args) { var s = A.B; } } public class A { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); } [WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessExpressionInNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$A.B.C|]; } } namespace A { }", languageName: LanguageNames.CSharp, typeName: "B", expected: @"class Program { static void Main(string[] args) { var s = A.B.C; } } namespace A { public class B { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithoutEnumForGenericsInMemberAccess() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$Goo<Bar>|].D; } } class Bar { }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { static void Main(string[] args) { var s = Goo<Bar>.D; } } class Bar { } public class Goo<T> { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithoutEnumForGenericsInNameContext() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$Goo<Bar>|] baz; } } internal class Bar { }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { static void Main(string[] args) { Goo<Bar> baz; } } internal class Bar { } public class Goo<T> { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Interface | TypeKindOptions.Delegate)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessWithNSForModule() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|Goo.$$Bar|].Baz; } } namespace Goo { }", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { var s = Goo.Bar.Baz; } } namespace Goo { public class Bar { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessWithGlobalNSForModule() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$Bar|].Baz; } }", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { var s = Bar.Baz; } } public class Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessWithoutNS() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$Bar|].Baz; } } namespace Bar { }", languageName: LanguageNames.CSharp, typeName: "Bar", isMissing: true); } [WorkItem(876202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876202")] [WorkItem(883531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883531")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_NoParameterLessConstructorForStruct() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = new [|$$Bar|](); } }", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { var s = new Bar(); } } public struct Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Structure, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure, false)); } #endregion #region Delegates [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_MethodGroup() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s2 = new [|$$MyD|](goo); } static void goo() { } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s2 = new MyD(goo); } static void goo() { } } public delegate void MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_MethodGroup_Generics() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s2 = new [|$$MyD|](goo); } static void goo<T>() { } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s2 = new MyD(goo); } static void goo<T>() { } } public delegate void MyD<T>(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_Delegate() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { MyD1 d = null; var s1 = new [|$$MyD2|](d); } public delegate object MyD1(); }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD1 d = null; var s1 = new MyD2(d); } public delegate object MyD1(); } public delegate object MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_Action() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Action<int> action1 = null; var s3 = new [|$$MyD|](action1); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Action<int> action1 = null; var s3 = new MyD(action1); } } public delegate void MyD(int obj); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_Func() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Func<int> lambda = () => { return 0; }; var s4 = new [|$$MyD|](lambda); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Func<int> lambda = () => { return 0; }; var s4 = new MyD(lambda); } } public delegate int MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_ParenLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s5 = new [|$$MyD|]((int n) => { return n; }); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s5 = new MyD((int n) => { return n; }); } } public delegate int MyD(int n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_SimpleLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s6 = new [|$$MyD|](n => { return n; }); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s6 = new MyD(n => { return n; }); } } public delegate void MyD(object n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [WorkItem(872935, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872935")] [Fact(Skip = "872935"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_SimpleLambdaEmpty() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s7 = new [|$$MyD3|](() => { }); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s7 = new MyD3(() => { }); } } public delegate void MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_MethodGroup() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$MyD|] z1 = goo; } static void goo() { } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD z1 = goo; } static void goo() { } } public delegate void MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_Delegate() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { MyD1 temp = null; [|$$MyD|] z2 = temp; // Still Error } } public delegate object MyD1();", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD1 temp = null; MyD z2 = temp; // Still Error } } public delegate object MyD1(); public delegate object MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_Action() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Action<int, int, int> action2 = null; [|$$MyD|] z3 = action2; // Still Error } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Action<int, int, int> action2 = null; MyD z3 = action2; // Still Error } } public delegate void MyD(int arg1, int arg2, int arg3); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_Func() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Func<int> lambda2 = () => { return 0; }; [|$$MyD|] z4 = lambda2; // Still Error } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Func<int> lambda2 = () => { return 0; }; MyD z4 = lambda2; // Still Error } } public delegate int MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_ParenLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$MyD|] z5 = (int n) => { return n; }; } } ", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD z5 = (int n) => { return n; }; } } public delegate int MyD(int n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_SimpleLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$MyD|] z6 = n => { return n; }; } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD z6 = n => { return n; }; } } public delegate void MyD(object n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_MethodGroup() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var zz1 = ([|$$MyD|])goo; } static void goo() { } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var zz1 = (MyD)goo; } static void goo() { } } public delegate void MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_Delegate() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { MyDDD temp1 = null; var zz2 = ([|$$MyD|])temp1; // Still Error } } public delegate object MyDDD();", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyDDD temp1 = null; var zz2 = (MyD)temp1; // Still Error } } public delegate object MyDDD(); public delegate object MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_Action() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Action<int, int, int> action3 = null; var zz3 = ([|$$MyD|])action3; // Still Error } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Action<int, int, int> action3 = null; var zz3 = (MyD)action3; // Still Error } } public delegate void MyD(int arg1, int arg2, int arg3); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_Func() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Func<int> lambda3 = () => { return 0; }; var zz4 = ([|$$MyD|])lambda3; // Still Error } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Func<int> lambda3 = () => { return 0; }; var zz4 = (MyD)lambda3; // Still Error } } public delegate int MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_ParenLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var zz5 = ([|$$MyD|])((int n) => { return n; }); } } ", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var zz5 = (MyD)((int n) => { return n; }); } } public delegate int MyD(int n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_SimpleLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var zz6 = ([|$$MyD|])(n => { return n; }); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var zz6 = (MyD)(n => { return n; }); } } public delegate void MyD(object n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateTypeIntoDifferentLanguageNewFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { var f = ([|A.B.Goo$$|])Main; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Delegate Sub Goo() End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2"); } [WorkItem(860210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860210")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_NoInfo() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$MyD<int>|] d; } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD<int> d; } } public delegate void MyD<T>(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false); } #endregion #region Dev12Filtering [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_NoEnum_InvocationExpression_0() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s2 = [|$$B|].C(); } }", languageName: LanguageNames.CSharp, typeName: "B", expected: @"class Program { static void Main(string[] args) { var s2 = B.C(); } } public class B { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertTypeKindAbsent: new[] { TypeKindOptions.Enum }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_NoEnum_InvocationExpression_1() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s2 = [|A.$$B|].C(); } } namespace A { }", languageName: LanguageNames.CSharp, typeName: "B", expected: @"class Program { static void Main(string[] args) { var s2 = A.B.C(); } } namespace A { public class B { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertTypeKindAbsent: new[] { TypeKindOptions.Enum }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_TypeConstraint_1() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { } } public class F<T> where T : [|$$Bar|] { } ", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { } } public class F<T> where T : Bar { } public class Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_TypeConstraint_2() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { } } class outer { public class F<T> where T : [|$$Bar|] { } } ", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { } } class outer { public class F<T> where T : Bar { } } public class Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_TypeConstraint_3() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { } } public class outerOuter { public class outer { public class F<T> where T : [|$$Bar|] { } } } ", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { } } public class outerOuter { public class outer { public class F<T> where T : Bar { } } } public class Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityWithNesting_1() { await TestWithMockedGenerateTypeDialog( initial: @" public class B { public class C : [|$$D|] { } }", languageName: LanguageNames.CSharp, typeName: "D", expected: @" public class B { public class C : D { } } public class D { }", accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList, false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityWithNesting_2() { await TestWithMockedGenerateTypeDialog( initial: @" class B { public class C : [|$$D|] { } }", languageName: LanguageNames.CSharp, typeName: "D", expected: @" class B { public class C : D { } } public class D { }", accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList, false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityWithNesting_3() { await TestWithMockedGenerateTypeDialog( initial: @" class A { public class B { public class C : [|$$D|] { } } }", languageName: LanguageNames.CSharp, typeName: "D", expected: @" class A { public class B { public class C : D { } } } public class D { }", accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList, false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_1() { await TestWithMockedGenerateTypeDialog( initial: @" class A { event [|$$goo|] name1 { add { } remove { } } }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { event goo name1 { add { } remove { } } } public delegate void goo(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_2() { await TestWithMockedGenerateTypeDialog( initial: @" class A { public event [|$$goo|] name2; }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { public event goo name2; } public delegate void goo(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_3() { await TestWithMockedGenerateTypeDialog( initial: @" class A { event [|NS.goo$$|] name1 { add { } remove { } } }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { event NS.goo name1 { add { } remove { } } } namespace NS { public delegate void goo(); }", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_4() { await TestWithMockedGenerateTypeDialog( initial: @" class A { public event [|NS.goo$$|] name2; }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { public event NS.goo name2; } namespace NS { public delegate void goo(); }", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_5() { await TestWithMockedGenerateTypeDialog( initial: @" class A { event [|$$NS.goo.Mydel|] name1 { add { } remove { } } } namespace NS { }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { event NS.goo.Mydel name1 { add { } remove { } } } namespace NS { public class goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_6() { await TestWithMockedGenerateTypeDialog( initial: @" class A { public event [|$$NS.goo.Mydel|] name2; } namespace NS { }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { public event NS.goo.Mydel name2; } namespace NS { public class goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_7() { await TestWithMockedGenerateTypeDialog( initial: @" public class A { public event [|$$goo|] name1 { add { } remove { } } }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" public class A { public event goo name1 { add { } remove { } } } public delegate void goo(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_8() { await TestWithMockedGenerateTypeDialog( initial: @" public class outer { public class A { public event [|$$goo|] name1 { add { } remove { } } } }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" public class outer { public class A { public event goo name1 { add { } remove { } } } } public delegate void goo(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Delegate)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.GenerateTypeTests { public partial class GenerateTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { #region SameProject #region SameProject_SameFile [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeDefaultValues() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|Goo$$|] f; } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { Goo f; } } class Goo { }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInsideNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.Goo$$|] f; } } namespace A { }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.Goo f; } } namespace A { class Goo { } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInsideFileScopedNamespace1() { await TestWithMockedGenerateTypeDialog( initial: @" namespace A; class Program { void Main() { [|A.Goo$$|] f; } } ", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" namespace A; class Program { void Main() { A.Goo f; } } class Goo { }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInsideFileScopedNamespace2() { await TestWithMockedGenerateTypeDialog( initial: @" namespace A; class Program { void Main() { [|Goo$$|] f; } } ", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" namespace A; class Program { void Main() { Goo f; } } class Goo { }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInsideQualifiedNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.Goo f; } } namespace A.B { class Goo { } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithinQualifiedNestedNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.C.Goo$$|] f; } } namespace A.B { namespace C { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.C.Goo f; } } namespace A.B { namespace C { class Goo { } } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithinNestedQualifiedNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.C.Goo$$|] f; } } namespace A { namespace B.C { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.C.Goo f; } } namespace A { namespace B.C { class Goo { } } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithConstructorMembers() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var f = new [|$$Goo|](bar: 1, baz: 2); } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { static void Main(string[] args) { var f = new Goo(bar: 1, baz: 2); } } class Goo { private int bar; private int baz; public Goo(int bar, int baz) { this.bar = bar; this.baz = baz; } }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithBaseTypes() { await TestWithMockedGenerateTypeDialog( initial: @"using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> f = new [|$$Goo|](); } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> f = new Goo(); } } class Goo : List<int> { }", isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithPublicInterface() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.C.Goo$$|] f; } } namespace A { namespace B.C { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.C.Goo f; } } namespace A { namespace B.C { public interface Goo { } } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithInternalStruct() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.C.Goo$$|] f; } } namespace A { namespace B.C { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.C.Goo f; } } namespace A { namespace B.C { internal struct Goo { } } }", accessibility: Accessibility.Internal, typeKind: TypeKind.Struct, isNewFile: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithDefaultEnum() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A { namespace B { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.Goo f; } } namespace A { namespace B { enum Goo { } } }", accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithDefaultEnum_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|Goo$$|] f; } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"using ConsoleApplication; class Program { void Main() { Goo f; } } namespace ConsoleApplication { enum Goo { } }", defaultNamespace: "ConsoleApplication", accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithDefaultEnum_DefaultNamespace_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A { namespace B { } }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { void Main() { A.B.Goo f; } } namespace A { namespace B { enum Goo { } } }", defaultNamespace: "ConsoleApplication", accessibility: Accessibility.NotApplicable, typeKind: TypeKind.Enum, isNewFile: false); } #endregion // Working is very similar to the adding to the same file #region SameProject_ExistingFile [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> <Document FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile_Usings_Folders() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> <Document Folders= ""outer\inner"" FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace outer.inner { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile_Usings_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> <Document FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile_Usings_Folders_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> <Document Folders= ""outer\inner"" FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication.outer.inner { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication.outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInExistingEmptyFile_NoUsings_Folders_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> <Document FilePath=""Test2.cs"" Folders= ""outer\inner""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs"); } #endregion #region SameProject_NewFile [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInNewFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray<string>.Empty, newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> namespace outer { namespace inner { class Program { void Main() { [|Goo$$|] f; } } } } </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace outer.inner { public interface Goo { } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer", "inner"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNeeded_InNewFile_InFolder() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace outer.inner { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer", "inner"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer", "inner"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNeeded_InNewFile_InFolder_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication.outer.inner { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication.outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer", "inner"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> namespace ConsoleApplication.outer { class Program { void Main() { [|Goo$$|] f; } } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication.outer { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" namespace ConsoleApplication.outer { class Program { void Main() { Goo f; } } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer"), newFileName: "Test2.cs"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_UsingsNotNeeded_InNewFile_InFolder_DefaultNamespace_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" class Program { void Main() { A.B.Goo f; } } namespace A.B { }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileFolderContainers: ImmutableArray.Create("outer"), newFileName: "Test2.cs"); } [WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_InValidFolderNameNotMadeNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> namespace outer { namespace inner { class Program { void Main() { [|Goo$$|] f; } } } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", defaultNamespace: "ConsoleApplication", expected: @"namespace ConsoleApplication { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication; namespace outer { namespace inner { class Program { void Main() { Goo f; } } } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, areFoldersValidIdentifiers: false, newFileFolderContainers: ImmutableArray.Create("123", "456"), newFileName: "Test2.cs"); } #endregion #endregion #region SameLanguageDifferentProject #region SameLanguageDifferentProject_ExistingFile [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectEmptyFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document FilePath=""Test2.cs""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectExistingFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document Folders=""outer\inner"" FilePath=""Test2.cs""> namespace A { namespace B { } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" namespace A { namespace B { public interface Goo { } } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectExistingFile_Usings_Folders() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document Folders=""outer\inner"" FilePath=""Test2.cs""> namespace A { namespace B { } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" namespace A { namespace B { } } namespace outer.inner { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, existingFilename: "Test2.cs", projectName: "Assembly2"); } #endregion #region SameLanguageDifferentProject_NewFile [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace outer.inner { public interface Goo { } }", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace ConsoleApplication.outer.inner { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using ConsoleApplication.outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName_DefaultNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"namespace A.B { public interface Goo { } }", defaultNamespace: "ConsoleApplication", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: true, newFileName: "Test2.cs", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } #endregion #endregion #region DifferentLanguage [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_Usings() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace outer.inner Public Class Goo End Class End Namespace ", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_Usings_RootNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <CompilationOptions RootNamespace=""BarBaz""/> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace outer.inner Public Class Goo End Class End Namespace ", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using BarBaz.outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName_RootNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <CompilationOptions RootNamespace=""BarBaz""/> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFile_Folders_NoUsings_NotSimpleName_RootNamespace_ProjectReference() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <CompilationOptions RootNamespace=""BarBaz""/> <Document FilePath=""Test2.vb""> Namespace A.B Public Class Goo End Class End Namespace </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <ProjectReference>Assembly2</ProjectReference> <Document FilePath=""Test1.cs""> using BarBaz.A; class Program { void Main() { [|BarBaz.A.B.Bar$$|] f; } }</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"Namespace A.B Public Class Bar End Class End Namespace ", defaultNamespace: "ConsoleApplication", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test3.vb", newFileFolderContainers: ImmutableArray.Create("outer", "inner"), projectName: "Assembly2"); } [WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageNewFileAdjustFileExtension() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageExistingEmptyFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document Folders=""outer\inner"" FilePath=""Test2.vb""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Class Goo End Class End Namespace ", checkIfUsingsNotIncluded: true, accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); } [WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageExistingEmptyFile_Usings_Folder() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|Goo$$|] f; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document Folders=""outer\inner"" FilePath=""Test2.vb""> </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace outer.inner Public Class Goo End Class End Namespace ", checkIfUsingsIncluded: true, expectedTextWithUsings: @" using outer.inner; class Program { void Main() { Goo f; } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageExistingNonEmptyFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document FilePath=""Test2.vb""> Namespace A End Namespace </Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" Namespace A End Namespace Namespace Global.A.B Public Class Goo End Class End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeIntoDifferentLanguageExistingNonEmptyTargetFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.B.Goo$$|] f; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document FilePath=""Test2.vb""> Namespace Global Namespace A Namespace C End Namespace Namespace B End Namespace End Namespace End Namespace</Document> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @" Namespace Global Namespace A Namespace C End Namespace Namespace B Public Class Goo End Class End Namespace End Namespace End Namespace", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, existingFilename: "Test2.vb", projectName: "Assembly2"); } [WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] [WorkItem(869593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869593")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateModuleFromCSharpToVisualBasicInTypeContext() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { [|A.Goo$$|].Bar f; } } namespace A { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A Public Module Goo End Module End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Module, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2", assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); } #endregion #region Bugfix [WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] [WorkItem(873066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/873066")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityAndTypeKind_1() { await TestWithMockedGenerateTypeDialog( initial: @" public class C : [|$$D|] { }", languageName: LanguageNames.CSharp, typeName: "D", expected: @" public class C : D { } public class D { }", accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList, false)); } [WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityAndTypeKind_2() { await TestWithMockedGenerateTypeDialog( initial: @"public interface CCC : [|$$DDD|] { }", languageName: LanguageNames.CSharp, typeName: "DDD", expected: @"public interface CCC : DDD { } public interface DDD { }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Interface, false)); } [WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityAndTypeKind_3() { await TestWithMockedGenerateTypeDialog( initial: @"public struct CCC : [|$$DDD|] { }", languageName: LanguageNames.CSharp, typeName: "DDD", expected: @"public struct CCC : DDD { } public interface DDD { }", accessibility: Accessibility.Public, typeKind: TypeKind.Interface, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Interface, false)); } [WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessExpression() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$A.B|]; } }", languageName: LanguageNames.CSharp, typeName: "A", expected: @"class Program { static void Main(string[] args) { var s = A.B; } } public class A { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); } [WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessExpressionInNamespace() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$A.B.C|]; } } namespace A { }", languageName: LanguageNames.CSharp, typeName: "B", expected: @"class Program { static void Main(string[] args) { var s = A.B.C; } } namespace A { public class B { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithoutEnumForGenericsInMemberAccess() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$Goo<Bar>|].D; } } class Bar { }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { static void Main(string[] args) { var s = Goo<Bar>.D; } } class Bar { } public class Goo<T> { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithoutEnumForGenericsInNameContext() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$Goo<Bar>|] baz; } } internal class Bar { }", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"class Program { static void Main(string[] args) { Goo<Bar> baz; } } internal class Bar { } public class Goo<T> { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Interface | TypeKindOptions.Delegate)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessWithNSForModule() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|Goo.$$Bar|].Baz; } } namespace Goo { }", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { var s = Goo.Bar.Baz; } } namespace Goo { public class Bar { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessWithGlobalNSForModule() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$Bar|].Baz; } }", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { var s = Bar.Baz; } } public class Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.MemberAccessWithNamespace)); } [WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeInMemberAccessWithoutNS() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = [|$$Bar|].Baz; } } namespace Bar { }", languageName: LanguageNames.CSharp, typeName: "Bar", isMissing: true); } [WorkItem(876202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876202")] [WorkItem(883531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883531")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_NoParameterLessConstructorForStruct() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s = new [|$$Bar|](); } }", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { var s = new Bar(); } } public struct Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Structure, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure, false)); } #endregion #region Delegates [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_MethodGroup() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s2 = new [|$$MyD|](goo); } static void goo() { } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s2 = new MyD(goo); } static void goo() { } } public delegate void MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_MethodGroup_Generics() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s2 = new [|$$MyD|](goo); } static void goo<T>() { } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s2 = new MyD(goo); } static void goo<T>() { } } public delegate void MyD<T>(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_Delegate() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { MyD1 d = null; var s1 = new [|$$MyD2|](d); } public delegate object MyD1(); }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD1 d = null; var s1 = new MyD2(d); } public delegate object MyD1(); } public delegate object MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_Action() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Action<int> action1 = null; var s3 = new [|$$MyD|](action1); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Action<int> action1 = null; var s3 = new MyD(action1); } } public delegate void MyD(int obj); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_Func() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Func<int> lambda = () => { return 0; }; var s4 = new [|$$MyD|](lambda); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Func<int> lambda = () => { return 0; }; var s4 = new MyD(lambda); } } public delegate int MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_ParenLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s5 = new [|$$MyD|]((int n) => { return n; }); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s5 = new MyD((int n) => { return n; }); } } public delegate int MyD(int n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_SimpleLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s6 = new [|$$MyD|](n => { return n; }); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s6 = new MyD(n => { return n; }); } } public delegate void MyD(object n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Delegate)); } [WorkItem(872935, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872935")] [Fact(Skip = "872935"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_ObjectCreationExpression_SimpleLambdaEmpty() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s7 = new [|$$MyD3|](() => { }); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var s7 = new MyD3(() => { }); } } public delegate void MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_MethodGroup() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$MyD|] z1 = goo; } static void goo() { } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD z1 = goo; } static void goo() { } } public delegate void MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_Delegate() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { MyD1 temp = null; [|$$MyD|] z2 = temp; // Still Error } } public delegate object MyD1();", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD1 temp = null; MyD z2 = temp; // Still Error } } public delegate object MyD1(); public delegate object MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_Action() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Action<int, int, int> action2 = null; [|$$MyD|] z3 = action2; // Still Error } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Action<int, int, int> action2 = null; MyD z3 = action2; // Still Error } } public delegate void MyD(int arg1, int arg2, int arg3); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_Func() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Func<int> lambda2 = () => { return 0; }; [|$$MyD|] z4 = lambda2; // Still Error } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Func<int> lambda2 = () => { return 0; }; MyD z4 = lambda2; // Still Error } } public delegate int MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_ParenLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$MyD|] z5 = (int n) => { return n; }; } } ", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD z5 = (int n) => { return n; }; } } public delegate int MyD(int n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_VarDecl_SimpleLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$MyD|] z6 = n => { return n; }; } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD z6 = n => { return n; }; } } public delegate void MyD(object n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_MethodGroup() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var zz1 = ([|$$MyD|])goo; } static void goo() { } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var zz1 = (MyD)goo; } static void goo() { } } public delegate void MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_Delegate() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { MyDDD temp1 = null; var zz2 = ([|$$MyD|])temp1; // Still Error } } public delegate object MyDDD();", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyDDD temp1 = null; var zz2 = (MyD)temp1; // Still Error } } public delegate object MyDDD(); public delegate object MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_Action() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Action<int, int, int> action3 = null; var zz3 = ([|$$MyD|])action3; // Still Error } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Action<int, int, int> action3 = null; var zz3 = (MyD)action3; // Still Error } } public delegate void MyD(int arg1, int arg2, int arg3); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_Func() { await TestWithMockedGenerateTypeDialog( initial: @"using System; class Program { static void Main(string[] args) { Func<int> lambda3 = () => { return 0; }; var zz4 = ([|$$MyD|])lambda3; // Still Error } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"using System; class Program { static void Main(string[] args) { Func<int> lambda3 = () => { return 0; }; var zz4 = (MyD)lambda3; // Still Error } } public delegate int MyD(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_ParenLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var zz5 = ([|$$MyD|])((int n) => { return n; }); } } ", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var zz5 = (MyD)((int n) => { return n; }); } } public delegate int MyD(int n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_Cast_SimpleLambda() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var zz6 = ([|$$MyD|])(n => { return n; }); } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { var zz6 = (MyD)(n => { return n; }); } } public delegate void MyD(object n); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.AllOptions)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateTypeIntoDifferentLanguageNewFile() { await TestWithMockedGenerateTypeDialog( initial: @"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""Test1.cs""> class Program { void Main() { var f = ([|A.B.Goo$$|])Main; } } namespace A.B { } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true""> </Project> </Workspace>", languageName: LanguageNames.CSharp, typeName: "Goo", expected: @"Namespace Global.A.B Public Delegate Sub Goo() End Namespace ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: true, newFileName: "Test2.vb", newFileFolderContainers: ImmutableArray<string>.Empty, projectName: "Assembly2"); } [WorkItem(860210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860210")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_NoInfo() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { [|$$MyD<int>|] d; } }", languageName: LanguageNames.CSharp, typeName: "MyD", expected: @"class Program { static void Main(string[] args) { MyD<int> d; } } public delegate void MyD<T>(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false); } #endregion #region Dev12Filtering [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_NoEnum_InvocationExpression_0() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s2 = [|$$B|].C(); } }", languageName: LanguageNames.CSharp, typeName: "B", expected: @"class Program { static void Main(string[] args) { var s2 = B.C(); } } public class B { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertTypeKindAbsent: new[] { TypeKindOptions.Enum }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateDelegateType_NoEnum_InvocationExpression_1() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { var s2 = [|A.$$B|].C(); } } namespace A { }", languageName: LanguageNames.CSharp, typeName: "B", expected: @"class Program { static void Main(string[] args) { var s2 = A.B.C(); } } namespace A { public class B { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertTypeKindAbsent: new[] { TypeKindOptions.Enum }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_TypeConstraint_1() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { } } public class F<T> where T : [|$$Bar|] { } ", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { } } public class F<T> where T : Bar { } public class Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_TypeConstraint_2() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { } } class outer { public class F<T> where T : [|$$Bar|] { } } ", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { } } class outer { public class F<T> where T : Bar { } } public class Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_TypeConstraint_3() { await TestWithMockedGenerateTypeDialog( initial: @"class Program { static void Main(string[] args) { } } public class outerOuter { public class outer { public class F<T> where T : [|$$Bar|] { } } } ", languageName: LanguageNames.CSharp, typeName: "Bar", expected: @"class Program { static void Main(string[] args) { } } public class outerOuter { public class outer { public class F<T> where T : Bar { } } } public class Bar { }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityWithNesting_1() { await TestWithMockedGenerateTypeDialog( initial: @" public class B { public class C : [|$$D|] { } }", languageName: LanguageNames.CSharp, typeName: "D", expected: @" public class B { public class C : D { } } public class D { }", accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.BaseList, false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityWithNesting_2() { await TestWithMockedGenerateTypeDialog( initial: @" class B { public class C : [|$$D|] { } }", languageName: LanguageNames.CSharp, typeName: "D", expected: @" class B { public class C : D { } } public class D { }", accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList, false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateTypeWithProperAccessibilityWithNesting_3() { await TestWithMockedGenerateTypeDialog( initial: @" class A { public class B { public class C : [|$$D|] { } } }", languageName: LanguageNames.CSharp, typeName: "D", expected: @" class A { public class B { public class C : D { } } } public class D { }", accessibility: Accessibility.Public, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.BaseList, false)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_1() { await TestWithMockedGenerateTypeDialog( initial: @" class A { event [|$$goo|] name1 { add { } remove { } } }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { event goo name1 { add { } remove { } } } public delegate void goo(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_2() { await TestWithMockedGenerateTypeDialog( initial: @" class A { public event [|$$goo|] name2; }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { public event goo name2; } public delegate void goo(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_3() { await TestWithMockedGenerateTypeDialog( initial: @" class A { event [|NS.goo$$|] name1 { add { } remove { } } }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { event NS.goo name1 { add { } remove { } } } namespace NS { public delegate void goo(); }", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_4() { await TestWithMockedGenerateTypeDialog( initial: @" class A { public event [|NS.goo$$|] name2; }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { public event NS.goo name2; } namespace NS { public delegate void goo(); }", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_5() { await TestWithMockedGenerateTypeDialog( initial: @" class A { event [|$$NS.goo.Mydel|] name1 { add { } remove { } } } namespace NS { }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { event NS.goo.Mydel name1 { add { } remove { } } } namespace NS { public class goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_6() { await TestWithMockedGenerateTypeDialog( initial: @" class A { public event [|$$NS.goo.Mydel|] name2; } namespace NS { }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" class A { public event NS.goo.Mydel name2; } namespace NS { public class goo { } }", accessibility: Accessibility.Public, typeKind: TypeKind.Class, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(false, TypeKindOptions.Class | TypeKindOptions.Structure | TypeKindOptions.Module)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_7() { await TestWithMockedGenerateTypeDialog( initial: @" public class A { public event [|$$goo|] name1 { add { } remove { } } }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" public class A { public event goo name1 { add { } remove { } } } public delegate void goo(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Delegate)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public async Task GenerateType_Event_8() { await TestWithMockedGenerateTypeDialog( initial: @" public class outer { public class A { public event [|$$goo|] name1 { add { } remove { } } } }", languageName: LanguageNames.CSharp, typeName: "goo", expected: @" public class outer { public class A { public event goo name1 { add { } remove { } } } } public delegate void goo(); ", accessibility: Accessibility.Public, typeKind: TypeKind.Delegate, isNewFile: false, assertGenerateTypeDialogOptions: new GenerateTypeDialogOptions(true, TypeKindOptions.Delegate)); } #endregion } }
1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace { [ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeNamespaceService : AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpChangeNamespaceService() { } protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync( Document document, SyntaxNode container, CancellationToken cancellationToken) { if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles || document.IsGeneratedCode(cancellationToken)) { return default; } TextSpan containerSpan; if (container is BaseNamespaceDeclarationSyntax) { containerSpan = container.Span; } else if (container is CompilationUnitSyntax) { // A compilation unit as container means user want to move all its members from global to some namespace. // We use an empty span to indicate this case. containerSpan = default; } else { throw ExceptionUtilities.Unreachable; } if (!IsSupportedLinkedDocument(document, out var allDocumentIds)) return default; return await TryGetApplicableContainersFromAllDocumentsAsync( document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false); } protected override string GetDeclaredNamespace(SyntaxNode container) { if (container is CompilationUnitSyntax) return string.Empty; if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl); throw ExceptionUtilities.Unreachable; } protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container) { if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return namespaceDecl.Members; if (container is CompilationUnitSyntax compilationUnit) return compilationUnit.Members; throw ExceptionUtilities.Unreachable; } /// <summary> /// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed. /// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on /// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead. /// </summary> /// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from /// `SymbolFinder.FindReferencesAsync`.</param> /// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference /// will be replaced with given namespace in the new node.</param> /// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param> /// <param name="newNode">The replacement node.</param> public override bool TryGetReplacementReferenceSyntax( SyntaxNode reference, ImmutableArray<string> newNamespaceParts, ISyntaxFactsService syntaxFacts, [NotNullWhen(returnValue: true)] out SyntaxNode? oldNode, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (reference is not SimpleNameSyntax nameRef) { oldNode = newNode = null; return false; } // A few different cases are handled here: // // 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done. // And both old and new will point to the original reference. // // 2. When the new namespace is not specified, we don't need to change the qualified part of reference. // Both old and new will point to the qualified reference. // // 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace. // As a result, we need replace qualified reference with the simple name. // // 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global // namespace. We need to replace the qualified reference with a new qualified reference (which is qualified // with new namespace.) // // Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases. if (syntaxFacts.IsRightSideOfQualifiedName(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) || syntaxFacts.IsNameOfMemberBindingExpression(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref) { // This is the case where the reference is the right most part of a qualified name in `cref`. // for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`. // This is the form of `cref` we need to handle as a spacial case when changing namespace name or // changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the // same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`. var container = qualifiedCref.Container; var aliasQualifier = GetAliasQualifier(container); if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { // We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`, // which is a alias qualified simple name, similar to the regular case above. oldNode = qualifiedCref; newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!); } else { // if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`, // which is just a regular namespace node, no cref node involve here. oldNode = container; newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); } return true; } // Simple name reference, nothing to be done. // The name will be resolved by adding proper import. oldNode = newNode = nameRef; return false; } private static bool TryGetGlobalQualifiedName( ImmutableArray<string> newNamespaceParts, SimpleNameSyntax nameNode, string? aliasQualifier, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (IsGlobalNamespace(newNamespaceParts)) { // If new namespace is "", then name will be declared in global namespace. // We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified) var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia()); return true; } newNode = null; return false; } /// <summary> /// Try to change the namespace declaration based on the following rules: /// - if neither declared nor target namespace are "" (i.e. global namespace), /// then we try to change the name of the namespace. /// - if declared namespace is "", then we try to move all types declared /// in global namespace in the document into a new namespace declaration. /// - if target namespace is "", then we try to move all members in declared /// namespace to global namespace (i.e. remove the namespace declaration). /// </summary> protected override CompilationUnitSyntax ChangeNamespaceDeclaration( CompilationUnitSyntax root, ImmutableArray<string> declaredNamespaceParts, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault); var container = root.GetAnnotatedNodes(ContainerAnnotation).Single(); if (container is CompilationUnitSyntax compilationUnit) { // Move everything from global namespace to a namespace declaration Debug.Assert(IsGlobalNamespace(declaredNamespaceParts)); return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts); } if (container is BaseNamespaceDeclarationSyntax namespaceDecl) { // Move everything to global namespace if (IsGlobalNamespace(targetNamespaceParts)) return MoveMembersFromNamespaceToGlobal(root, namespaceDecl); // Change namespace name return root.ReplaceNode( namespaceDecl, namespaceDecl.WithName( CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation)) .WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added } throw ExceptionUtilities.Unreachable; } private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal( CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl) { var (namespaceOpeningTrivia, namespaceClosingTrivia) = GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl); var members = namespaceDecl.Members; var eofToken = root.EndOfFileToken .WithAdditionalAnnotations(WarningAnnotation); // Try to preserve trivia from original namespace declaration. // If there's any member inside the declaration, we attach them to the // first and last member, otherwise, simply attach all to the EOF token. if (members.Count > 0) { var first = members.First(); var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia); members = members.Replace(first, firstWithTrivia); var last = members.Last(); var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia); members = members.Replace(last, lastWithTrivia); } else { eofToken = eofToken.WithPrependedLeadingTrivia( namespaceOpeningTrivia.Concat(namespaceClosingTrivia)); } // Moving inner imports out of the namespace declaration can lead to a break in semantics. // For example: // // namespace A.B.C // { // using D.E.F; // } // // The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside, // it may fail to resolve. return root.Update( root.Externs.AddRange(namespaceDecl.Externs), root.Usings.AddRange(namespaceDecl.Usings), root.AttributeLists, root.Members.ReplaceRange(namespaceDecl, members), eofToken); } private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax)); var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration( name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithAdditionalAnnotations(WarningAnnotation), externs: default, usings: default, members: compilationUnit.Members); return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl)) .WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added } /// <summary> /// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace /// declaration or a compilation unit, contain no partial declarations and meet the following additional /// requirements: /// /// - If a namespace declaration: /// 1. It doesn't contain or is nested in other namespace declarations /// 2. The name of the namespace is valid (i.e. no errors) /// /// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration /// inside (i.e. all members are declared in global namespace) /// </summary> protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(syntaxRoot); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; SyntaxNode? container = null; // Empty span means that user wants to move all types declared in the document to a new namespace. // This action is only supported when everything in the document is declared in global namespace, // which we use the number of namespace declaration nodes to decide. if (span.IsEmpty) { if (ContainsNamespaceDeclaration(compilationUnit)) return null; container = compilationUnit; } else { // Otherwise, the span should contain a namespace declaration node, which must be the only one // in the entire syntax spine to enable the change namespace operation. if (!compilationUnit.Span.Contains(span)) return null; var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true); var namespaceDecl = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().SingleOrDefault(); if (namespaceDecl == null) return null; if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error)) return null; if (ContainsNamespaceDeclaration(node)) return null; container = namespaceDecl; } var containsPartial = await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false); if (containsPartial) return null; return container; static bool ContainsNamespaceDeclaration(SyntaxNode node) => node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>().Any(); } private static string? GetAliasQualifier(SyntaxNode? name) { while (true) { switch (name) { case QualifiedNameSyntax qualifiedNameNode: name = qualifiedNameNode.Left; continue; case MemberAccessExpressionSyntax memberAccessNode: name = memberAccessNode.Expression; continue; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return aliasQualifiedNameNode.Alias.Identifier.ValueText; } return null; } } private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece); } private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) { return aliasQualifier == null ? (NameSyntax)namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); } return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1), namePiece); } /// <summary> /// return trivia attached to namespace declaration. /// Leading trivia of the node and trivia around opening brace, as well as /// trivia around closing brace are concatenated together respectively. /// </summary> private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia) GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace) { var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); openingBuilder.AddRange(baseNamespace.GetLeadingTrivia()); if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration) { openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia); openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia); } else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia); } return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace { [ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeNamespaceService : AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpChangeNamespaceService() { } protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync( Document document, SyntaxNode container, CancellationToken cancellationToken) { if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles || document.IsGeneratedCode(cancellationToken)) { return default; } TextSpan containerSpan; if (container is BaseNamespaceDeclarationSyntax) { containerSpan = container.Span; } else if (container is CompilationUnitSyntax) { // A compilation unit as container means user want to move all its members from global to some namespace. // We use an empty span to indicate this case. containerSpan = default; } else { throw ExceptionUtilities.Unreachable; } if (!IsSupportedLinkedDocument(document, out var allDocumentIds)) return default; return await TryGetApplicableContainersFromAllDocumentsAsync( document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false); } protected override string GetDeclaredNamespace(SyntaxNode container) { if (container is CompilationUnitSyntax) return string.Empty; if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl); throw ExceptionUtilities.Unreachable; } protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container) { if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return namespaceDecl.Members; if (container is CompilationUnitSyntax compilationUnit) return compilationUnit.Members; throw ExceptionUtilities.Unreachable; } /// <summary> /// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed. /// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on /// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead. /// </summary> /// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from /// `SymbolFinder.FindReferencesAsync`.</param> /// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference /// will be replaced with given namespace in the new node.</param> /// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param> /// <param name="newNode">The replacement node.</param> public override bool TryGetReplacementReferenceSyntax( SyntaxNode reference, ImmutableArray<string> newNamespaceParts, ISyntaxFactsService syntaxFacts, [NotNullWhen(returnValue: true)] out SyntaxNode? oldNode, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (reference is not SimpleNameSyntax nameRef) { oldNode = newNode = null; return false; } // A few different cases are handled here: // // 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done. // And both old and new will point to the original reference. // // 2. When the new namespace is not specified, we don't need to change the qualified part of reference. // Both old and new will point to the qualified reference. // // 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace. // As a result, we need replace qualified reference with the simple name. // // 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global // namespace. We need to replace the qualified reference with a new qualified reference (which is qualified // with new namespace.) // // Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases. if (syntaxFacts.IsRightSideOfQualifiedName(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) || syntaxFacts.IsNameOfMemberBindingExpression(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref) { // This is the case where the reference is the right most part of a qualified name in `cref`. // for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`. // This is the form of `cref` we need to handle as a spacial case when changing namespace name or // changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the // same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`. var container = qualifiedCref.Container; var aliasQualifier = GetAliasQualifier(container); if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { // We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`, // which is a alias qualified simple name, similar to the regular case above. oldNode = qualifiedCref; newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!); } else { // if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`, // which is just a regular namespace node, no cref node involve here. oldNode = container; newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); } return true; } // Simple name reference, nothing to be done. // The name will be resolved by adding proper import. oldNode = newNode = nameRef; return false; } private static bool TryGetGlobalQualifiedName( ImmutableArray<string> newNamespaceParts, SimpleNameSyntax nameNode, string? aliasQualifier, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (IsGlobalNamespace(newNamespaceParts)) { // If new namespace is "", then name will be declared in global namespace. // We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified) var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia()); return true; } newNode = null; return false; } /// <summary> /// Try to change the namespace declaration based on the following rules: /// - if neither declared nor target namespace are "" (i.e. global namespace), /// then we try to change the name of the namespace. /// - if declared namespace is "", then we try to move all types declared /// in global namespace in the document into a new namespace declaration. /// - if target namespace is "", then we try to move all members in declared /// namespace to global namespace (i.e. remove the namespace declaration). /// </summary> protected override CompilationUnitSyntax ChangeNamespaceDeclaration( CompilationUnitSyntax root, ImmutableArray<string> declaredNamespaceParts, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault); var container = root.GetAnnotatedNodes(ContainerAnnotation).Single(); if (container is CompilationUnitSyntax compilationUnit) { // Move everything from global namespace to a namespace declaration Debug.Assert(IsGlobalNamespace(declaredNamespaceParts)); return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts); } if (container is BaseNamespaceDeclarationSyntax namespaceDecl) { // Move everything to global namespace if (IsGlobalNamespace(targetNamespaceParts)) return MoveMembersFromNamespaceToGlobal(root, namespaceDecl); // Change namespace name return root.ReplaceNode( namespaceDecl, namespaceDecl.WithName( CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation)) .WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added } throw ExceptionUtilities.Unreachable; } private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal( CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl) { var (namespaceOpeningTrivia, namespaceClosingTrivia) = GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl); var members = namespaceDecl.Members; var eofToken = root.EndOfFileToken .WithAdditionalAnnotations(WarningAnnotation); // Try to preserve trivia from original namespace declaration. // If there's any member inside the declaration, we attach them to the // first and last member, otherwise, simply attach all to the EOF token. if (members.Count > 0) { var first = members.First(); var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia); members = members.Replace(first, firstWithTrivia); var last = members.Last(); var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia); members = members.Replace(last, lastWithTrivia); } else { eofToken = eofToken.WithPrependedLeadingTrivia( namespaceOpeningTrivia.Concat(namespaceClosingTrivia)); } // Moving inner imports out of the namespace declaration can lead to a break in semantics. // For example: // // namespace A.B.C // { // using D.E.F; // } // // The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside, // it may fail to resolve. return root.Update( root.Externs.AddRange(namespaceDecl.Externs), root.Usings.AddRange(namespaceDecl.Usings), root.AttributeLists, root.Members.ReplaceRange(namespaceDecl, members), eofToken); } private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax)); var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration( name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithAdditionalAnnotations(WarningAnnotation), externs: default, usings: default, members: compilationUnit.Members); return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl)) .WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added } /// <summary> /// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace /// declaration or a compilation unit, contain no partial declarations and meet the following additional /// requirements: /// /// - If a namespace declaration: /// 1. It doesn't contain or is nested in other namespace declarations /// 2. The name of the namespace is valid (i.e. no errors) /// /// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration /// inside (i.e. all members are declared in global namespace) /// </summary> protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(syntaxRoot); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; SyntaxNode? container = null; // Empty span means that user wants to move all types declared in the document to a new namespace. // This action is only supported when everything in the document is declared in global namespace, // which we use the number of namespace declaration nodes to decide. if (span.IsEmpty) { if (ContainsNamespaceDeclaration(compilationUnit)) return null; container = compilationUnit; } else { // Otherwise, the span should contain a namespace declaration node, which must be the only one // in the entire syntax spine to enable the change namespace operation. if (!compilationUnit.Span.Contains(span)) return null; var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true); var namespaceDecls = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().ToImmutableArray(); if (namespaceDecls.Length != 1) return null; var namespaceDecl = namespaceDecls[0]; if (namespaceDecl == null) return null; if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error)) return null; if (ContainsNamespaceDeclaration(node)) return null; container = namespaceDecl; } var containsPartial = await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false); if (containsPartial) return null; return container; static bool ContainsNamespaceDeclaration(SyntaxNode node) => node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>().Any(); } private static string? GetAliasQualifier(SyntaxNode? name) { while (true) { switch (name) { case QualifiedNameSyntax qualifiedNameNode: name = qualifiedNameNode.Left; continue; case MemberAccessExpressionSyntax memberAccessNode: name = memberAccessNode.Expression; continue; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return aliasQualifiedNameNode.Alias.Identifier.ValueText; } return null; } } private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece); } private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) { return aliasQualifier == null ? (NameSyntax)namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); } return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1), namePiece); } /// <summary> /// return trivia attached to namespace declaration. /// Leading trivia of the node and trivia around opening brace, as well as /// trivia around closing brace are concatenated together respectively. /// </summary> private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia) GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace) { var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); openingBuilder.AddRange(baseNamespace.GetLeadingTrivia()); if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration) { openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia); openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia); } else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia); } return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree()); } } }
1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/CSharp/Portable/GenerateType/CSharpGenerateTypeService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateType { [ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared] internal class CSharpGenerateTypeService : AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateTypeService() { } protected override string DefaultFileExtension => ".cs"; protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName) => simpleName.GetLeftSideOfDot(); protected override bool IsInCatchDeclaration(ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.CatchDeclaration); protected override bool IsArrayElementType(ExpressionSyntax expression) { return expression.IsParentKind(SyntaxKind.ArrayType) && expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression); } protected override bool IsInValueTypeConstraintContext( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList, out TypeArgumentListSyntax typeArgumentList)) { var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken); var symbol = symbolInfo.GetAnySymbol(); if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression); if (symbol is INamedTypeSymbol type) { type = type.OriginalDefinition; var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } if (symbol is IMethodSymbol method) { method = method.OriginalDefinition; var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } } return false; } protected override bool IsInInterfaceList(ExpressionSyntax expression) { if (expression is TypeSyntax && expression.Parent is BaseTypeSyntax baseType && baseType.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax baseList) && baseType.Type == expression) { // If it's after the first item, then it's definitely an interface. if (baseList.Types[0] != expression.Parent) { return true; } // If it's in the base list of an interface or struct, then it's definitely an // interface. return baseList.IsParentKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration); } if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax typeConstraint) && typeConstraint.IsParentKind(SyntaxKind.TypeParameterConstraintClause, out TypeParameterConstraintClauseSyntax constraintClause)) { var index = constraintClause.Constraints.IndexOf(typeConstraint); // If it's after the first item, then it's definitely an interface. return index > 0; } return false; } protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts) { return expression.TryGetNameParts(out nameParts); } protected override bool TryInitializeState( SemanticDocument document, SimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions) { generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions(); if (simpleName.IsVar) { return false; } if (SyntaxFacts.IsAliasQualifier(simpleName)) { return false; } // Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly // unlikely that this would be a location where a user would be wanting to generate // something. They're really just trying to reference something that exists but // isn't available for some reason (i.e. a missing reference). var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword) { return false; } ExpressionSyntax nameOrMemberAccessExpression = null; if (simpleName.IsRightSideOfDot()) { // This simplename comes from the cref if (simpleName.IsParentKind(SyntaxKind.NameMemberCref)) { return false; } nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent; // If we're on the right side of a dot, then the left side better be a name (and // not an arbitrary expression). var leftSideExpression = simpleName.GetLeftSideOfDot(); if (!leftSideExpression.IsKind( SyntaxKind.QualifiedName, SyntaxKind.IdentifierName, SyntaxKind.AliasQualifiedName, SyntaxKind.GenericName, SyntaxKind.SimpleMemberAccessExpression)) { return false; } } else { nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName; } // BUG(5712): Don't offer generate type in an enum's base list. if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax && nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression && nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration)) { return false; } // If we can guarantee it's a type only context, great. Otherwise, we may not want to // provide this here. var semanticModel = document.SemanticModel; if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { // Don't offer Generate Type in an expression context *unless* we're on the left // side of a dot. In that case the user might be making a type that they're // accessing a static off of. var syntaxTree = semanticModel.SyntaxTree; var start = nameOrMemberAccessExpression.SpanStart; var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken); var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel); var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken); var isExpressionOrStatementContext = isExpressionContext || isStatementContext; // Delegate Type Creation is not allowed in Non Type Namespace Context generateTypeServiceStateOptions.IsDelegateAllowed = false; if (!isExpressionOrStatementContext) { return false; } if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOfExpression(semanticModel, cancellationToken)) { if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot()) { return false; } var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol; var token = simpleName.GetLastToken().GetNextToken(); // We let only the Namespace to be left of the Dot if (leftSymbol == null || !leftSymbol.IsKind(SymbolKind.Namespace) || !token.IsKind(SyntaxKind.DotToken)) { return false; } else { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } // Global Namespace if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess && !SyntaxFacts.IsInNamespaceOrTypeContext(simpleName)) { var token = simpleName.GetLastToken().GetNextToken(); if (token.IsKind(SyntaxKind.DotToken) && simpleName.Parent == token.Parent) { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } } var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null && fieldDeclaration.Parent is CompilationUnitSyntax && document.Document.SourceCodeKind == SourceCodeKind.Regular) { return false; } // Check to see if Module could be an option in the Type Generation in Cross Language Generation var nextToken = simpleName.GetLastToken().GetNextToken(); if (simpleName.IsLeftSideOfDot() || nextToken.IsKind(SyntaxKind.DotToken)) { if (simpleName.IsRightSideOfDot()) { if (simpleName.Parent is QualifiedNameSyntax parent) { var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol; if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace)) { generateTypeServiceStateOptions.IsMembersWithModule = true; } } } } if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { if (nextToken.IsKind(SyntaxKind.DotToken)) { // In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName generateTypeServiceStateOptions.IsDelegateAllowed = false; generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; generateTypeServiceStateOptions.IsMembersWithModule = true; } // case: class Goo<T> where T: MyType if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any()) { generateTypeServiceStateOptions.IsClassInterfaceTypes = true; return true; } // Events if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() || nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any()) { // Case : event goo name11 // Only Delegate if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax)) { generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } // Case : event SomeSymbol.goo name11 if (nameOrMemberAccessExpression is QualifiedNameSyntax) { // Only Namespace, Class, Struct and Module are allowed to contain Delegate // Case : event Something.Mytype.<Delegate> Identifier if (nextToken.IsKind(SyntaxKind.DotToken)) { if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax) { return true; } throw ExceptionUtilities.Unreachable; } else { // Case : event Something.<Delegate> Identifier generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } } } } else { // MemberAccessExpression if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) && nameOrMemberAccessExpression.IsLeftSideOfDot()) { // Check to see if the expression is part of Invocation Expression ExpressionSyntax outerMostMemberAccessExpression = null; if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { outerMostMemberAccessExpression = nameOrMemberAccessExpression; } else { Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)); outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent; } outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile(n => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault(); if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax) { generateTypeServiceStateOptions.IsEnumNotAllowed = true; } } } // Cases: // // 1 - Function Address // var s2 = new MyD2(goo); // // 2 - Delegate // MyD1 d = null; // var s1 = new MyD2(d); // // 3 - Action // Action action1 = null; // var s3 = new MyD2(action1); // // 4 - Func // Func<int> lambda = () => { return 0; }; // var s4 = new MyD3(lambda); if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax) { var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent; // Enum and Interface not Allowed in Object Creation Expression generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; if (objectCreationExpressionOpt.ArgumentList != null) { if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing) { return false; } // Get the Method symbol for the Delegate to be created if (generateTypeServiceStateOptions.IsDelegateAllowed && objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 && objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression.Kind() != SyntaxKind.DeclarationExpression) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken); } else { generateTypeServiceStateOptions.IsDelegateAllowed = false; } } if (objectCreationExpressionOpt.Initializer != null) { foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions) { if (!(expression is AssignmentExpressionSyntax simpleAssignmentExpression)) { continue; } if (!(simpleAssignmentExpression.Left is SimpleNameSyntax name)) { continue; } generateTypeServiceStateOptions.PropertiesToGenerate.Add(name); } } } if (generateTypeServiceStateOptions.IsDelegateAllowed) { // MyD1 z1 = goo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax variableDeclaration) && variableDeclaration.Variables.Count != 0) { var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null); if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken); } } // var w1 = (MyD1)goo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) && castExpression.Expression != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken); } } return true; } private static IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression == null) { return null; } var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken); if (memberGroup.Length != 0) { return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null; } var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType.IsDelegateType()) { return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod; } var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (expressionSymbol.IsKind(SymbolKind.Method)) { return (IMethodSymbol)expressionSymbol; } return null; } private static Accessibility DetermineAccessibilityConstraint( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.DetermineAccessibilityConstraint( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } private static bool AllContainingTypesArePublicOrProtected( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.AllContainingTypesArePublicOrProtected( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } protected override ImmutableArray<ITypeParameterSymbol> GetTypeParameters( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { if (state.SimpleName is GenericNameSyntax) { var genericName = (GenericNameSyntax)state.SimpleName; var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count ? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList() : Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity); return GetTypeParameters(state, semanticModel, typeArguments, cancellationToken); } return ImmutableArray<ITypeParameterSymbol>.Empty; } protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList) { if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null) { argumentList = objectCreationExpression.ArgumentList.Arguments.ToList(); return true; } argumentList = null; return false; } protected override IList<ParameterName> GenerateParameterNames( SemanticModel semanticModel, IList<ArgumentSyntax> arguments, CancellationToken cancellationToken) { return semanticModel.GenerateParameterNames(arguments, reservedNames: null, cancellationToken: cancellationToken); } public override string GetRootNamespace(CompilationOptions options) => string.Empty; protected override bool IsInVariableTypeContext(ExpressionSyntax expression) => false; protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken) => semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken); protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken) { var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken); if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess) { var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken); if (accessibilityConstraint == Accessibility.Public || accessibilityConstraint == Accessibility.Internal) { accessibility = accessibilityConstraint; } else if (accessibilityConstraint == Accessibility.Protected || accessibilityConstraint == Accessibility.ProtectedOrInternal) { // If nested type is declared in public type then we should generate public type instead of internal accessibility = AllContainingTypesArePublicOrProtected(state, semanticModel, cancellationToken) ? Accessibility.Public : Accessibility.Internal; } } return accessibility; } protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) => argument.DetermineParameterType(semanticModel, cancellationToken); protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) => compilation.ClassifyConversion(sourceType, targetType).IsImplicit; public override async Task<(INamespaceSymbol, INamespaceOrTypeSymbol, Location)> GetOrGenerateEnclosingNamespaceSymbolAsync( INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken) { var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot; var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (containers.Length != 0) { // Search the NS declaration in the root var containerList = new List<string>(containers); var enclosingNamespace = FindNamespaceInMemberDeclarations(compilationUnit.Members, indexDone: 0, containerList); if (enclosingNamespace != null) { var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken); if (enclosingNamespaceSymbol.Symbol != null) { return ((INamespaceSymbol)enclosingNamespaceSymbol.Symbol, namedTypeSymbol, enclosingNamespace.CloseBraceToken.GetLocation()); } } } var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken); var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers); var lastMember = compilationUnit.Members.LastOrDefault(); var afterThisLocation = lastMember != null ? semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0)) : semanticModel.SyntaxTree.GetLocation(new TextSpan()); return (globalNamespace, rootNamespaceOrType, afterThisLocation); } private NamespaceDeclarationSyntax FindNamespaceInMemberDeclarations(SyntaxList<MemberDeclarationSyntax> members, int indexDone, List<string> containers) { foreach (var member in members) { if (member is NamespaceDeclarationSyntax namespaceDeclaration) { var found = FindNamespaceInNamespace(namespaceDeclaration, indexDone, containers); if (found != null) return found; } } return null; } private NamespaceDeclarationSyntax FindNamespaceInNamespace(NamespaceDeclarationSyntax namespaceDecl, int indexDone, List<string> containers) { if (namespaceDecl.Name is AliasQualifiedNameSyntax) return null; var namespaceContainers = new List<string>(); GetNamespaceContainers(namespaceDecl.Name, namespaceContainers); if (namespaceContainers.Count + indexDone > containers.Count || !IdentifierMatches(indexDone, namespaceContainers, containers)) { return null; } indexDone += namespaceContainers.Count; if (indexDone == containers.Count) return namespaceDecl; return FindNamespaceInMemberDeclarations(namespaceDecl.Members, indexDone, containers); } private static bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers) { for (var i = 0; i < namespaceContainers.Count; ++i) { if (namespaceContainers[i] != containers[indexDone + i]) { return false; } } return true; } private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers) { if (name is QualifiedNameSyntax qualifiedName) { GetNamespaceContainers(qualifiedName.Left, namespaceContainers); namespaceContainers.Add(qualifiedName.Right.Identifier.ValueText); } else { Debug.Assert(name is SimpleNameSyntax); namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText); } } internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue) { typeKindValue = TypeKindOptions.AllOptions; if (expression == null) { return false; } var node = expression as SyntaxNode; while (node != null) { if (node is BaseListSyntax) { if (node.Parent.IsKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration)) { typeKindValue = TypeKindOptions.Interface; return true; } typeKindValue = TypeKindOptions.BaseList; return true; } node = node.Parent; } return false; } internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project) { if (expression == null) { return false; } if (GeneratedTypesMustBePublic(project)) { return true; } var node = expression as SyntaxNode; SyntaxNode previousNode = null; while (node != null) { // Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { if (node.Parent is TypeDeclarationSyntax typeDecl) { if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return IsAllContainingTypeDeclsPublic(typeDecl); } else { // The Type Decl which contains the BaseList does not contain Public return false; } } throw ExceptionUtilities.Unreachable; } if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { // Make sure the GFU is not inside the Accessors if (previousNode != null && previousNode is AccessorListSyntax) { return false; } // Make sure that Event Declaration themselves are Public in the first place if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return false; } return IsAllContainingTypeDeclsPublic(node); } previousNode = node; node = node.Parent; } return false; } private static bool IsAllContainingTypeDeclsPublic(SyntaxNode node) { // Make sure that all the containing Type Declarations are also Public var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>(); if (containingTypeDeclarations.Count() == 0) { return true; } else { return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)); } } internal override bool IsGenericName(SimpleNameSyntax simpleName) => simpleName is GenericNameSyntax; internal override bool IsSimpleName(ExpressionSyntax expression) => expression is SimpleNameSyntax; internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken) { // Nothing to include if (string.IsNullOrWhiteSpace(includeUsingsOrImports)) { return updatedSolution; } SyntaxNode root = null; if (modifiedRoot == null) { root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } else { root = modifiedRoot; } if (root is CompilationUnitSyntax compilationRoot) { var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports)); // Check if the usings is already present if (compilationRoot.Usings.Where(n => n != null && n.Alias == null) .Select(n => n.Name.ToString()) .Any(n => n.Equals(includeUsingsOrImports))) { return updatedSolution; } // Check if the GFU is triggered from the namespace same as the usings namespace if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false)) { return updatedSolution; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity); } return updatedSolution; } private static ITypeSymbol GetPropertyType( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken) { if (propertyName.Parent is AssignmentExpressionSyntax parentAssignment) { return typeInference.InferType( semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken); } if (propertyName.Parent is IsPatternExpressionSyntax isPatternExpression) { return typeInference.InferType( semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken); } return null; } private static IPropertySymbol CreatePropertySymbol( SimpleNameSyntax propertyName, ITypeSymbol propertyType) { return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), explicitInterfaceImplementations: default, name: propertyName.Identifier.ValueText, type: propertyType, refKind: RefKind.None, parameters: default, getMethod: s_accessor, setMethod: s_accessor, isIndexer: false); } private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default, accessibility: Accessibility.Public, statements: default); internal override bool TryGenerateProperty( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property) { var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken); if (propertyType == null || propertyType is IErrorTypeSymbol) { property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType); return property != null; } property = CreatePropertySymbol(propertyName, propertyType); return property != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateType { [ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared] internal class CSharpGenerateTypeService : AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateTypeService() { } protected override string DefaultFileExtension => ".cs"; protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName) => simpleName.GetLeftSideOfDot(); protected override bool IsInCatchDeclaration(ExpressionSyntax expression) => expression.IsParentKind(SyntaxKind.CatchDeclaration); protected override bool IsArrayElementType(ExpressionSyntax expression) { return expression.IsParentKind(SyntaxKind.ArrayType) && expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression); } protected override bool IsInValueTypeConstraintContext( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList, out TypeArgumentListSyntax typeArgumentList)) { var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken); var symbol = symbolInfo.GetAnySymbol(); if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression); if (symbol is INamedTypeSymbol type) { type = type.OriginalDefinition; var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } if (symbol is IMethodSymbol method) { method = method.OriginalDefinition; var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null; return typeParameter != null && typeParameter.HasValueTypeConstraint; } } return false; } protected override bool IsInInterfaceList(ExpressionSyntax expression) { if (expression is TypeSyntax && expression.Parent is BaseTypeSyntax baseType && baseType.IsParentKind(SyntaxKind.BaseList, out BaseListSyntax baseList) && baseType.Type == expression) { // If it's after the first item, then it's definitely an interface. if (baseList.Types[0] != expression.Parent) { return true; } // If it's in the base list of an interface or struct, then it's definitely an // interface. return baseList.IsParentKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration); } if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax typeConstraint) && typeConstraint.IsParentKind(SyntaxKind.TypeParameterConstraintClause, out TypeParameterConstraintClauseSyntax constraintClause)) { var index = constraintClause.Constraints.IndexOf(typeConstraint); // If it's after the first item, then it's definitely an interface. return index > 0; } return false; } protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts) { return expression.TryGetNameParts(out nameParts); } protected override bool TryInitializeState( SemanticDocument document, SimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions) { generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions(); if (simpleName.IsVar) { return false; } if (SyntaxFacts.IsAliasQualifier(simpleName)) { return false; } // Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly // unlikely that this would be a location where a user would be wanting to generate // something. They're really just trying to reference something that exists but // isn't available for some reason (i.e. a missing reference). var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword) { return false; } ExpressionSyntax nameOrMemberAccessExpression = null; if (simpleName.IsRightSideOfDot()) { // This simplename comes from the cref if (simpleName.IsParentKind(SyntaxKind.NameMemberCref)) { return false; } nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent; // If we're on the right side of a dot, then the left side better be a name (and // not an arbitrary expression). var leftSideExpression = simpleName.GetLeftSideOfDot(); if (!leftSideExpression.IsKind( SyntaxKind.QualifiedName, SyntaxKind.IdentifierName, SyntaxKind.AliasQualifiedName, SyntaxKind.GenericName, SyntaxKind.SimpleMemberAccessExpression)) { return false; } } else { nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName; } // BUG(5712): Don't offer generate type in an enum's base list. if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax && nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) && ((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression && nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration)) { return false; } // If we can guarantee it's a type only context, great. Otherwise, we may not want to // provide this here. var semanticModel = document.SemanticModel; if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { // Don't offer Generate Type in an expression context *unless* we're on the left // side of a dot. In that case the user might be making a type that they're // accessing a static off of. var syntaxTree = semanticModel.SyntaxTree; var start = nameOrMemberAccessExpression.SpanStart; var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken); var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel); var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken); var isExpressionOrStatementContext = isExpressionContext || isStatementContext; // Delegate Type Creation is not allowed in Non Type Namespace Context generateTypeServiceStateOptions.IsDelegateAllowed = false; if (!isExpressionOrStatementContext) { return false; } if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOfExpression(semanticModel, cancellationToken)) { if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot()) { return false; } var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol; var token = simpleName.GetLastToken().GetNextToken(); // We let only the Namespace to be left of the Dot if (leftSymbol == null || !leftSymbol.IsKind(SymbolKind.Namespace) || !token.IsKind(SyntaxKind.DotToken)) { return false; } else { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } // Global Namespace if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess && !SyntaxFacts.IsInNamespaceOrTypeContext(simpleName)) { var token = simpleName.GetLastToken().GetNextToken(); if (token.IsKind(SyntaxKind.DotToken) && simpleName.Parent == token.Parent) { generateTypeServiceStateOptions.IsMembersWithModule = true; generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true; } } } var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null && fieldDeclaration.Parent is CompilationUnitSyntax && document.Document.SourceCodeKind == SourceCodeKind.Regular) { return false; } // Check to see if Module could be an option in the Type Generation in Cross Language Generation var nextToken = simpleName.GetLastToken().GetNextToken(); if (simpleName.IsLeftSideOfDot() || nextToken.IsKind(SyntaxKind.DotToken)) { if (simpleName.IsRightSideOfDot()) { if (simpleName.Parent is QualifiedNameSyntax parent) { var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol; if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace)) { generateTypeServiceStateOptions.IsMembersWithModule = true; } } } } if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression)) { if (nextToken.IsKind(SyntaxKind.DotToken)) { // In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName generateTypeServiceStateOptions.IsDelegateAllowed = false; generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; generateTypeServiceStateOptions.IsMembersWithModule = true; } // case: class Goo<T> where T: MyType if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any()) { generateTypeServiceStateOptions.IsClassInterfaceTypes = true; return true; } // Events if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() || nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any()) { // Case : event goo name11 // Only Delegate if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax)) { generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } // Case : event SomeSymbol.goo name11 if (nameOrMemberAccessExpression is QualifiedNameSyntax) { // Only Namespace, Class, Struct and Module are allowed to contain Delegate // Case : event Something.Mytype.<Delegate> Identifier if (nextToken.IsKind(SyntaxKind.DotToken)) { if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax) { return true; } throw ExceptionUtilities.Unreachable; } else { // Case : event Something.<Delegate> Identifier generateTypeServiceStateOptions.IsDelegateOnly = true; return true; } } } } else { // MemberAccessExpression if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression))) && nameOrMemberAccessExpression.IsLeftSideOfDot()) { // Check to see if the expression is part of Invocation Expression ExpressionSyntax outerMostMemberAccessExpression = null; if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { outerMostMemberAccessExpression = nameOrMemberAccessExpression; } else { Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)); outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent; } outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile(n => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault(); if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax) { generateTypeServiceStateOptions.IsEnumNotAllowed = true; } } } // Cases: // // 1 - Function Address // var s2 = new MyD2(goo); // // 2 - Delegate // MyD1 d = null; // var s1 = new MyD2(d); // // 3 - Action // Action action1 = null; // var s3 = new MyD2(action1); // // 4 - Func // Func<int> lambda = () => { return 0; }; // var s4 = new MyD3(lambda); if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax) { var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent; // Enum and Interface not Allowed in Object Creation Expression generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true; if (objectCreationExpressionOpt.ArgumentList != null) { if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing) { return false; } // Get the Method symbol for the Delegate to be created if (generateTypeServiceStateOptions.IsDelegateAllowed && objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 && objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression.Kind() != SyntaxKind.DeclarationExpression) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken); } else { generateTypeServiceStateOptions.IsDelegateAllowed = false; } } if (objectCreationExpressionOpt.Initializer != null) { foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions) { if (!(expression is AssignmentExpressionSyntax simpleAssignmentExpression)) { continue; } if (!(simpleAssignmentExpression.Left is SimpleNameSyntax name)) { continue; } generateTypeServiceStateOptions.PropertiesToGenerate.Add(name); } } } if (generateTypeServiceStateOptions.IsDelegateAllowed) { // MyD1 z1 = goo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax variableDeclaration) && variableDeclaration.Variables.Count != 0) { var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null); if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken); } } // var w1 = (MyD1)goo; if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) && castExpression.Expression != null) { generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken); } } return true; } private static IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { if (expression == null) { return null; } var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken); if (memberGroup.Length != 0) { return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null; } var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType.IsDelegateType()) { return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod; } var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol; if (expressionSymbol.IsKind(SymbolKind.Method)) { return (IMethodSymbol)expressionSymbol; } return null; } private static Accessibility DetermineAccessibilityConstraint( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.DetermineAccessibilityConstraint( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } private static bool AllContainingTypesArePublicOrProtected( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { return semanticModel.AllContainingTypesArePublicOrProtected( state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken); } protected override ImmutableArray<ITypeParameterSymbol> GetTypeParameters( State state, SemanticModel semanticModel, CancellationToken cancellationToken) { if (state.SimpleName is GenericNameSyntax) { var genericName = (GenericNameSyntax)state.SimpleName; var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count ? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList() : Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity); return GetTypeParameters(state, semanticModel, typeArguments, cancellationToken); } return ImmutableArray<ITypeParameterSymbol>.Empty; } protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList) { if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null) { argumentList = objectCreationExpression.ArgumentList.Arguments.ToList(); return true; } argumentList = null; return false; } protected override IList<ParameterName> GenerateParameterNames( SemanticModel semanticModel, IList<ArgumentSyntax> arguments, CancellationToken cancellationToken) { return semanticModel.GenerateParameterNames(arguments, reservedNames: null, cancellationToken: cancellationToken); } public override string GetRootNamespace(CompilationOptions options) => string.Empty; protected override bool IsInVariableTypeContext(ExpressionSyntax expression) => false; protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken) => semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken); protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken) { var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken); if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess) { var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken); if (accessibilityConstraint == Accessibility.Public || accessibilityConstraint == Accessibility.Internal) { accessibility = accessibilityConstraint; } else if (accessibilityConstraint == Accessibility.Protected || accessibilityConstraint == Accessibility.ProtectedOrInternal) { // If nested type is declared in public type then we should generate public type instead of internal accessibility = AllContainingTypesArePublicOrProtected(state, semanticModel, cancellationToken) ? Accessibility.Public : Accessibility.Internal; } } return accessibility; } protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) => argument.DetermineParameterType(semanticModel, cancellationToken); protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) => compilation.ClassifyConversion(sourceType, targetType).IsImplicit; public override async Task<(INamespaceSymbol, INamespaceOrTypeSymbol, Location)> GetOrGenerateEnclosingNamespaceSymbolAsync( INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken) { var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot; var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (containers.Length != 0) { // Search the NS declaration in the root var containerList = new List<string>(containers); var enclosingNamespace = FindNamespaceInMemberDeclarations(compilationUnit.Members, indexDone: 0, containerList); if (enclosingNamespace != null) { var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken); if (enclosingNamespaceSymbol.Symbol is INamespaceSymbol namespaceSymbol) return (namespaceSymbol, namedTypeSymbol, enclosingNamespace.GetLastToken().GetLocation()); } } var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken); var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers); var lastMember = compilationUnit.Members.LastOrDefault(); var afterThisLocation = lastMember != null ? semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0)) : semanticModel.SyntaxTree.GetLocation(new TextSpan()); return (globalNamespace, rootNamespaceOrType, afterThisLocation); } private BaseNamespaceDeclarationSyntax FindNamespaceInMemberDeclarations(SyntaxList<MemberDeclarationSyntax> members, int indexDone, List<string> containers) { foreach (var member in members) { if (member is BaseNamespaceDeclarationSyntax namespaceDeclaration) { var found = FindNamespaceInNamespace(namespaceDeclaration, indexDone, containers); if (found != null) return found; } } return null; } private BaseNamespaceDeclarationSyntax FindNamespaceInNamespace(BaseNamespaceDeclarationSyntax namespaceDecl, int indexDone, List<string> containers) { if (namespaceDecl.Name is AliasQualifiedNameSyntax) return null; var namespaceContainers = new List<string>(); GetNamespaceContainers(namespaceDecl.Name, namespaceContainers); if (namespaceContainers.Count + indexDone > containers.Count || !IdentifierMatches(indexDone, namespaceContainers, containers)) { return null; } indexDone += namespaceContainers.Count; if (indexDone == containers.Count) return namespaceDecl; return FindNamespaceInMemberDeclarations(namespaceDecl.Members, indexDone, containers); } private static bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers) { for (var i = 0; i < namespaceContainers.Count; ++i) { if (namespaceContainers[i] != containers[indexDone + i]) { return false; } } return true; } private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers) { if (name is QualifiedNameSyntax qualifiedName) { GetNamespaceContainers(qualifiedName.Left, namespaceContainers); namespaceContainers.Add(qualifiedName.Right.Identifier.ValueText); } else { Debug.Assert(name is SimpleNameSyntax); namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText); } } internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue) { typeKindValue = TypeKindOptions.AllOptions; if (expression == null) { return false; } var node = expression as SyntaxNode; while (node != null) { if (node is BaseListSyntax) { if (node.Parent.IsKind(SyntaxKind.InterfaceDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration)) { typeKindValue = TypeKindOptions.Interface; return true; } typeKindValue = TypeKindOptions.BaseList; return true; } node = node.Parent; } return false; } internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project) { if (expression == null) { return false; } if (GeneratedTypesMustBePublic(project)) { return true; } var node = expression as SyntaxNode; SyntaxNode previousNode = null; while (node != null) { // Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { if (node.Parent is TypeDeclarationSyntax typeDecl) { if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return IsAllContainingTypeDeclsPublic(typeDecl); } else { // The Type Decl which contains the BaseList does not contain Public return false; } } throw ExceptionUtilities.Unreachable; } if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) && node.Parent != null && node.Parent is TypeDeclarationSyntax) { // Make sure the GFU is not inside the Accessors if (previousNode != null && previousNode is AccessorListSyntax) { return false; } // Make sure that Event Declaration themselves are Public in the first place if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)) { return false; } return IsAllContainingTypeDeclsPublic(node); } previousNode = node; node = node.Parent; } return false; } private static bool IsAllContainingTypeDeclsPublic(SyntaxNode node) { // Make sure that all the containing Type Declarations are also Public var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>(); if (containingTypeDeclarations.Count() == 0) { return true; } else { return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword)); } } internal override bool IsGenericName(SimpleNameSyntax simpleName) => simpleName is GenericNameSyntax; internal override bool IsSimpleName(ExpressionSyntax expression) => expression is SimpleNameSyntax; internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken) { // Nothing to include if (string.IsNullOrWhiteSpace(includeUsingsOrImports)) { return updatedSolution; } SyntaxNode root = null; if (modifiedRoot == null) { root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } else { root = modifiedRoot; } if (root is CompilationUnitSyntax compilationRoot) { var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports)); // Check if the usings is already present if (compilationRoot.Usings.Where(n => n != null && n.Alias == null) .Select(n => n.Name.ToString()) .Any(n => n.Equals(includeUsingsOrImports))) { return updatedSolution; } // Check if the GFU is triggered from the namespace same as the usings namespace if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false)) { return updatedSolution; } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst); var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity); } return updatedSolution; } private static ITypeSymbol GetPropertyType( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken) { if (propertyName.Parent is AssignmentExpressionSyntax parentAssignment) { return typeInference.InferType( semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken); } if (propertyName.Parent is IsPatternExpressionSyntax isPatternExpression) { return typeInference.InferType( semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken); } return null; } private static IPropertySymbol CreatePropertySymbol( SimpleNameSyntax propertyName, ITypeSymbol propertyType) { return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(), explicitInterfaceImplementations: default, name: propertyName.Identifier.ValueText, type: propertyType, refKind: RefKind.None, parameters: default, getMethod: s_accessor, setMethod: s_accessor, isIndexer: false); } private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default, accessibility: Accessibility.Public, statements: default); internal override bool TryGenerateProperty( SimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property) { var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken); if (propertyType == null || propertyType is IErrorTypeSymbol) { property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType); return property != null; } property = CreatePropertySymbol(propertyName, propertyType); return property != null; } } }
1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.Editor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateType { internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> { protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType); private partial class Editor { private readonly TService _service; private TargetProjectChangeInLanguage _targetProjectChangeInLanguage = TargetProjectChangeInLanguage.NoChange; private IGenerateTypeService _targetLanguageService; private readonly SemanticDocument _semanticDocument; private readonly State _state; private readonly bool _intoNamespace; private readonly bool _inNewFile; private readonly bool _fromDialog; private readonly GenerateTypeOptionsResult _generateTypeOptionsResult; private readonly CancellationToken _cancellationToken; public Editor( TService service, SemanticDocument document, State state, bool intoNamespace, bool inNewFile, CancellationToken cancellationToken) { _service = service; _semanticDocument = document; _state = state; _intoNamespace = intoNamespace; _inNewFile = inNewFile; _cancellationToken = cancellationToken; } public Editor( TService service, SemanticDocument document, State state, bool fromDialog, GenerateTypeOptionsResult generateTypeOptionsResult, CancellationToken cancellationToken) { // the document comes from the same snapshot as the project Contract.ThrowIfFalse(document.Project.Solution == generateTypeOptionsResult.Project.Solution); _service = service; _semanticDocument = document; _state = state; _fromDialog = fromDialog; _generateTypeOptionsResult = generateTypeOptionsResult; _cancellationToken = cancellationToken; } private enum TargetProjectChangeInLanguage { NoChange, CSharpToVisualBasic, VisualBasicToCSharp } internal async Task<IEnumerable<CodeActionOperation>> GetOperationsAsync() { // Check to see if it is from GFU Dialog if (!_fromDialog) { // Generate the actual type declaration. var namedType = await GenerateNamedTypeAsync().ConfigureAwait(false); if (_intoNamespace) { if (_inNewFile) { // Generating into a new file is somewhat complicated. var documentName = GetTypeName(_state) + _service.DefaultFileExtension; return await GetGenerateInNewFileOperationsAsync( namedType, documentName, null, true, null, _semanticDocument.Project, _semanticDocument.Project, isDialog: false).ConfigureAwait(false); } else { return await GetGenerateIntoContainingNamespaceOperationsAsync(namedType).ConfigureAwait(false); } } else { return await GetGenerateIntoTypeOperationsAsync(namedType).ConfigureAwait(false); } } else { var namedType = await GenerateNamedTypeAsync(_generateTypeOptionsResult).ConfigureAwait(false); // Honor the options from the dialog // Check to see if the type is requested to be generated in cross language Project // e.g.: C# -> VB or VB -> C# if (_semanticDocument.Project.Language != _generateTypeOptionsResult.Project.Language) { _targetProjectChangeInLanguage = _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp ? TargetProjectChangeInLanguage.VisualBasicToCSharp : TargetProjectChangeInLanguage.CSharpToVisualBasic; // Get the cross language service _targetLanguageService = _generateTypeOptionsResult.Project.LanguageServices.GetService<IGenerateTypeService>(); } if (_generateTypeOptionsResult.IsNewFile) { return await GetGenerateInNewFileOperationsAsync( namedType, _generateTypeOptionsResult.NewFileName, _generateTypeOptionsResult.Folders, _generateTypeOptionsResult.AreFoldersValidIdentifiers, _generateTypeOptionsResult.FullFilePath, _generateTypeOptionsResult.Project, _semanticDocument.Project, isDialog: true).ConfigureAwait(false); } else { return await GetGenerateIntoExistingDocumentAsync( namedType, _semanticDocument.Project, _generateTypeOptionsResult, isDialog: true).ConfigureAwait(false); } } } private string GetNamespaceToGenerateInto() { var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim(); var rootNamespace = _service.GetRootNamespace(_semanticDocument.SemanticModel.Compilation.Options).Trim(); if (!string.IsNullOrWhiteSpace(rootNamespace)) { if (namespaceToGenerateInto == rootNamespace || namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal)) { namespaceToGenerateInto = namespaceToGenerateInto[rootNamespace.Length..]; } } return namespaceToGenerateInto; } private string GetNamespaceToGenerateIntoForUsageWithNamespace(Project targetProject, Project triggeringProject) { var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim(); if (targetProject.Language == LanguageNames.CSharp || targetProject == triggeringProject) { // If the target project is C# project then we don't have to make any modification to the namespace // or // This is a VB project generation into itself which requires no change as well return namespaceToGenerateInto; } // If the target Project is VB then we have to check if the RootNamespace of the VB project is the parent most namespace of the type being generated // True, Remove the RootNamespace // False, Add Global to the Namespace Debug.Assert(targetProject.Language == LanguageNames.VisualBasic); IGenerateTypeService targetLanguageService; if (_semanticDocument.Project.Language == LanguageNames.VisualBasic) { targetLanguageService = _service; } else { Debug.Assert(_targetLanguageService != null); targetLanguageService = _targetLanguageService; } var rootNamespace = targetLanguageService.GetRootNamespace(targetProject.CompilationOptions).Trim(); if (!string.IsNullOrWhiteSpace(rootNamespace)) { var rootNamespaceLength = CheckIfRootNamespacePresentInNamespace(namespaceToGenerateInto, rootNamespace); if (rootNamespaceLength > -1) { // True, Remove the RootNamespace namespaceToGenerateInto = namespaceToGenerateInto[rootNamespaceLength..]; } else { // False, Add Global to the Namespace namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto); } } else { // False, Add Global to the Namespace namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto); } return namespaceToGenerateInto; } private static string AddGlobalDotToTheNamespace(string namespaceToBeGenerated) => "Global." + namespaceToBeGenerated; // Returns the length of the meaningful rootNamespace substring part of namespaceToGenerateInto private static int CheckIfRootNamespacePresentInNamespace(string namespaceToGenerateInto, string rootNamespace) { if (namespaceToGenerateInto == rootNamespace) { return rootNamespace.Length; } if (namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal)) { return rootNamespace.Length + 1; } return -1; } private static void AddFoldersToNamespaceContainers(List<string> container, IList<string> folders) { // Add the folder as part of the namespace if there are not empty if (folders != null && folders.Count != 0) { // Remove the empty entries and replace the spaces in the folder name to '_' var refinedFolders = folders.Where(n => n != null && !n.IsEmpty()).Select(n => n.Replace(' ', '_')).ToArray(); container.AddRange(refinedFolders); } } private async Task<IEnumerable<CodeActionOperation>> GetGenerateInNewFileOperationsAsync( INamedTypeSymbol namedType, string documentName, IList<string> folders, bool areFoldersValidIdentifiers, string fullFilePath, Project projectToBeUpdated, Project triggeringProject, bool isDialog) { // First, we fork the solution with a new, empty, file in it. var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, debugName: documentName); var newSolution = projectToBeUpdated.Solution.AddDocument(newDocumentId, documentName, string.Empty, folders, fullFilePath); // Now we get the semantic model for that file we just added. We do that to get the // root namespace in that new document, along with location for that new namespace. // That way, when we use the code gen service we can say "add this symbol to the // root namespace" and it will pick the one in the new file. var newDocument = newSolution.GetDocument(newDocumentId); var newSemanticModel = await newDocument.GetSemanticModelAsync(_cancellationToken).ConfigureAwait(false); var enclosingNamespace = newSemanticModel.GetEnclosingNamespace(0, _cancellationToken); var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport( isDialog, folders, areFoldersValidIdentifiers, projectToBeUpdated, triggeringProject); var containers = namespaceContainersAndUsings.containers; var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport; var rootNamespaceOrType = namedType.GenerateRootNamespaceOrType(containers); // Now, actually ask the code gen service to add this namespace or type to the root // namespace in the new file. This will properly generate the code, and add any // additional niceties like imports/usings. var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( newSolution, enclosingNamespace, rootNamespaceOrType, new CodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan())), _cancellationToken).ConfigureAwait(false); // containers is determined to be // 1: folders -> if triggered from Dialog // 2: containers -> if triggered not from a Dialog but from QualifiedName // 3: triggering document folder structure -> if triggered not from a Dialog and a SimpleName var adjustedContainer = isDialog ? folders : _state.SimpleName != _state.NameOrMemberAccessExpression ? containers.ToList() : _semanticDocument.Document.Folders.ToList(); if (newDocument.Project.Language == _semanticDocument.Document.Project.Language) { var formattingService = newDocument.GetLanguageService<INewDocumentFormattingService>(); if (formattingService is not null) { codeGenResult = await formattingService.FormatNewDocumentAsync(codeGenResult, _semanticDocument.Document, _cancellationToken).ConfigureAwait(false); } } // Now, take the code that would be generated and actually create an edit that would // produce a document with that code in it. var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); return await CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync( projectToBeUpdated, triggeringProject, documentName, newRoot, includeUsingsOrImports, adjustedContainer, SourceCodeKind.Regular, _cancellationToken).ConfigureAwait(false); } private async Task<IEnumerable<CodeActionOperation>> CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync( Project projectToBeUpdated, Project triggeringProject, string documentName, SyntaxNode root, string includeUsingsOrImports, IList<string> containers, SourceCodeKind sourceCodeKind, CancellationToken cancellationToken) { // TODO(cyrusn): make sure documentId is unique. var documentId = DocumentId.CreateNewId(projectToBeUpdated.Id, documentName); var updatedSolution = projectToBeUpdated.Solution.AddDocument(DocumentInfo.Create( documentId, documentName, containers, sourceCodeKind)); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity); // Update the Generating Document with a using if required if (includeUsingsOrImports != null) { updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(updatedSolution, null, _semanticDocument.Document, _state.SimpleName, includeUsingsOrImports, cancellationToken).ConfigureAwait(false); } // Add reference of the updated project to the triggering Project if they are 2 different projects updatedSolution = AddProjectReference(projectToBeUpdated, triggeringProject, updatedSolution); return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution), new OpenDocumentOperation(documentId) }; } private static Solution AddProjectReference(Project projectToBeUpdated, Project triggeringProject, Solution updatedSolution) { if (projectToBeUpdated != triggeringProject) { if (!triggeringProject.ProjectReferences.Any(pr => pr.ProjectId == projectToBeUpdated.Id)) { updatedSolution = updatedSolution.AddProjectReference(triggeringProject.Id, new ProjectReference(projectToBeUpdated.Id)); } } return updatedSolution; } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoContainingNamespaceOperationsAsync(INamedTypeSymbol namedType) { var enclosingNamespace = _semanticDocument.SemanticModel.GetEnclosingNamespace( _state.SimpleName.SpanStart, _cancellationToken); var solution = _semanticDocument.Project.Solution; var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync( solution, enclosingNamespace, namedType, new CodeGenerationOptions( afterThisLocation: _semanticDocument.SyntaxTree.GetLocation(_state.SimpleName.Span), options: await _semanticDocument.Document.GetOptionsAsync(_cancellationToken).ConfigureAwait(false)), _cancellationToken).ConfigureAwait(false); return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) }; } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoExistingDocumentAsync( INamedTypeSymbol namedType, Project triggeringProject, GenerateTypeOptionsResult generateTypeOptionsResult, bool isDialog) { var root = await generateTypeOptionsResult.ExistingDocument.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); var folders = generateTypeOptionsResult.ExistingDocument.Folders; var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(isDialog, new List<string>(folders), generateTypeOptionsResult.AreFoldersValidIdentifiers, generateTypeOptionsResult.Project, triggeringProject); var containers = namespaceContainersAndUsings.containers; var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport; (INamespaceSymbol, INamespaceOrTypeSymbol, Location) enclosingNamespaceGeneratedTypeToAddAndLocation; if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange) { enclosingNamespaceGeneratedTypeToAddAndLocation = await _service.GetOrGenerateEnclosingNamespaceSymbolAsync( namedType, containers, generateTypeOptionsResult.ExistingDocument, root, _cancellationToken).ConfigureAwait(false); } else { enclosingNamespaceGeneratedTypeToAddAndLocation = await _targetLanguageService.GetOrGenerateEnclosingNamespaceSymbolAsync( namedType, containers, generateTypeOptionsResult.ExistingDocument, root, _cancellationToken).ConfigureAwait(false); } var solution = _semanticDocument.Project.Solution; var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( solution, enclosingNamespaceGeneratedTypeToAddAndLocation.Item1, enclosingNamespaceGeneratedTypeToAddAndLocation.Item2, new CodeGenerationOptions(afterThisLocation: enclosingNamespaceGeneratedTypeToAddAndLocation.Item3), _cancellationToken) .ConfigureAwait(false); var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); var updatedSolution = solution.WithDocumentSyntaxRoot(generateTypeOptionsResult.ExistingDocument.Id, newRoot, PreservationMode.PreserveIdentity); // Update the Generating Document with a using if required if (includeUsingsOrImports != null) { updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync( updatedSolution, generateTypeOptionsResult.ExistingDocument.Id == _semanticDocument.Document.Id ? newRoot : null, _semanticDocument.Document, _state.SimpleName, includeUsingsOrImports, _cancellationToken).ConfigureAwait(false); } updatedSolution = AddProjectReference(generateTypeOptionsResult.Project, triggeringProject, updatedSolution); return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution) }; } private (string[] containers, string usingOrImport) GetNamespaceContainersAndAddUsingsOrImport( bool isDialog, IList<string> folders, bool areFoldersValidIdentifiers, Project targetProject, Project triggeringProject) { string includeUsingsOrImports = null; if (!areFoldersValidIdentifiers) { folders = SpecializedCollections.EmptyList<string>(); } // Now actually create the symbol that we want to add to the root namespace. The // symbol may either be a named type (if we're not generating into a namespace) or // it may be a namespace symbol. string[] containers = null; if (!isDialog) { // Not generated from the Dialog containers = GetNamespaceToGenerateInto().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); } else if (!_service.IsSimpleName(_state.NameOrMemberAccessExpression)) { // If the usage was with a namespace containers = GetNamespaceToGenerateIntoForUsageWithNamespace(targetProject, triggeringProject).Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); } else { // Generated from the Dialog var containerList = new List<string>(); var rootNamespaceOfTheProjectGeneratedInto = _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange ? _service.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim() : _targetLanguageService.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim(); var defaultNamespace = _generateTypeOptionsResult.DefaultNamespace; // Case 1 : If the type is generated into the same C# project or // Case 2 : If the type is generated from a C# project to a C# Project // Case 3 : If the Type is generated from a VB Project to a C# Project // Using and Namespace will be the DefaultNamespace + Folder Structure if ((_semanticDocument.Project == _generateTypeOptionsResult.Project && _semanticDocument.Project.Language == LanguageNames.CSharp) || (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp) || _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.VisualBasicToCSharp) { if (!string.IsNullOrWhiteSpace(defaultNamespace)) { containerList.Add(defaultNamespace); } // Populate the ContainerList AddFoldersToNamespaceContainers(containerList, folders); containers = containerList.ToArray(); includeUsingsOrImports = string.Join(".", containerList.ToArray()); } // Case 4 : If the type is generated into the same VB project or // Case 5 : If Type is generated from a VB Project to VB Project // Case 6 : If Type is generated from a C# Project to VB Project // Namespace will be Folder Structure and Import will have the RootNamespace of the project generated into as part of the Imports if ((_semanticDocument.Project == _generateTypeOptionsResult.Project && _semanticDocument.Project.Language == LanguageNames.VisualBasic) || (_semanticDocument.Project != _generateTypeOptionsResult.Project && _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.VisualBasic) || _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.CSharpToVisualBasic) { // Populate the ContainerList AddFoldersToNamespaceContainers(containerList, folders); containers = containerList.ToArray(); includeUsingsOrImports = string.Join(".", containerList.ToArray()); if (!string.IsNullOrWhiteSpace(rootNamespaceOfTheProjectGeneratedInto)) { includeUsingsOrImports = string.IsNullOrEmpty(includeUsingsOrImports) ? rootNamespaceOfTheProjectGeneratedInto : rootNamespaceOfTheProjectGeneratedInto + "." + includeUsingsOrImports; } } Debug.Assert(includeUsingsOrImports != null); } return (containers, includeUsingsOrImports); } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoTypeOperationsAsync(INamedTypeSymbol namedType) { var solution = _semanticDocument.Project.Solution; var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync( solution, _state.TypeToGenerateInOpt, namedType, new CodeGenerationOptions(contextLocation: _state.SimpleName.GetLocation()), _cancellationToken) .ConfigureAwait(false); return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) }; } private ImmutableArray<ITypeSymbol> GetArgumentTypes(IList<TArgumentSyntax> argumentList) { var types = argumentList.Select(a => _service.DetermineArgumentType(_semanticDocument.SemanticModel, a, _cancellationToken)); return types.SelectAsArray(FixType); } private ImmutableArray<TExpressionSyntax> GetArgumentExpressions(IList<TArgumentSyntax> argumentList) { var syntaxFacts = _semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>(); return argumentList.SelectAsArray(a => (TExpressionSyntax)syntaxFacts.GetExpressionOfArgument(a)); } private ITypeSymbol FixType( ITypeSymbol typeSymbol) { var compilation = _semanticDocument.SemanticModel.Compilation; return typeSymbol.RemoveUnnamedErrorTypes(compilation); } private async Task<bool> FindExistingOrCreateNewMemberAsync( ParameterName parameterName, ITypeSymbol parameterType, ImmutableDictionary<string, ISymbol>.Builder parameterToFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap) { // If the base types have an accessible field or property with the same name and // an acceptable type, then we should just defer to that. if (_state.BaseTypeOrInterfaceOpt != null) { var expectedFieldName = parameterName.NameBasedOnArgument; var members = from t in _state.BaseTypeOrInterfaceOpt.GetBaseTypesAndThis() from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where IsSymbolAccessible(m) where IsViableFieldOrProperty(parameterType, m) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { parameterToFieldMap[parameterName.BestNameForParameter] = symbol; return true; } } var fieldNamingRule = await _semanticDocument.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, _cancellationToken).ConfigureAwait(false); var nameToUse = fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); parameterToNewFieldMap[parameterName.BestNameForParameter] = nameToUse; return false; } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (symbol != null && !symbol.IsStatic && parameterType.Language == symbol.Language) { if (symbol is IFieldSymbol field) { return !field.IsReadOnly && _service.IsConversionImplicit(_semanticDocument.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.SetMethod != null && IsSymbolAccessible(property.SetMethod) && _service.IsConversionImplicit(_semanticDocument.SemanticModel.Compilation, parameterType, property.Type); } } return false; } private bool IsSymbolAccessible(ISymbol symbol) { // Public and protected constructors are accessible. Internal constructors are // accessible if we have friend access. We can't call the normal accessibility // checkers since they will think that a protected constructor isn't accessible // (since we don't have the destination type that would have access to them yet). switch (symbol.DeclaredAccessibility) { case Accessibility.ProtectedOrInternal: case Accessibility.Protected: case Accessibility.Public: return true; case Accessibility.ProtectedAndInternal: case Accessibility.Internal: // TODO: Code coverage return _semanticDocument.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo( symbol.ContainingAssembly); 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateType { internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> { protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType); private partial class Editor { private readonly TService _service; private TargetProjectChangeInLanguage _targetProjectChangeInLanguage = TargetProjectChangeInLanguage.NoChange; private IGenerateTypeService _targetLanguageService; private readonly SemanticDocument _semanticDocument; private readonly State _state; private readonly bool _intoNamespace; private readonly bool _inNewFile; private readonly bool _fromDialog; private readonly GenerateTypeOptionsResult _generateTypeOptionsResult; private readonly CancellationToken _cancellationToken; public Editor( TService service, SemanticDocument document, State state, bool intoNamespace, bool inNewFile, CancellationToken cancellationToken) { _service = service; _semanticDocument = document; _state = state; _intoNamespace = intoNamespace; _inNewFile = inNewFile; _cancellationToken = cancellationToken; } public Editor( TService service, SemanticDocument document, State state, bool fromDialog, GenerateTypeOptionsResult generateTypeOptionsResult, CancellationToken cancellationToken) { // the document comes from the same snapshot as the project Contract.ThrowIfFalse(document.Project.Solution == generateTypeOptionsResult.Project.Solution); _service = service; _semanticDocument = document; _state = state; _fromDialog = fromDialog; _generateTypeOptionsResult = generateTypeOptionsResult; _cancellationToken = cancellationToken; } private enum TargetProjectChangeInLanguage { NoChange, CSharpToVisualBasic, VisualBasicToCSharp } internal async Task<IEnumerable<CodeActionOperation>> GetOperationsAsync() { // Check to see if it is from GFU Dialog if (!_fromDialog) { // Generate the actual type declaration. var namedType = await GenerateNamedTypeAsync().ConfigureAwait(false); if (_intoNamespace) { if (_inNewFile) { // Generating into a new file is somewhat complicated. var documentName = GetTypeName(_state) + _service.DefaultFileExtension; return await GetGenerateInNewFileOperationsAsync( namedType, documentName, null, true, null, _semanticDocument.Project, _semanticDocument.Project, isDialog: false).ConfigureAwait(false); } else { return await GetGenerateIntoContainingNamespaceOperationsAsync(namedType).ConfigureAwait(false); } } else { return await GetGenerateIntoTypeOperationsAsync(namedType).ConfigureAwait(false); } } else { var namedType = await GenerateNamedTypeAsync(_generateTypeOptionsResult).ConfigureAwait(false); // Honor the options from the dialog // Check to see if the type is requested to be generated in cross language Project // e.g.: C# -> VB or VB -> C# if (_semanticDocument.Project.Language != _generateTypeOptionsResult.Project.Language) { _targetProjectChangeInLanguage = _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp ? TargetProjectChangeInLanguage.VisualBasicToCSharp : TargetProjectChangeInLanguage.CSharpToVisualBasic; // Get the cross language service _targetLanguageService = _generateTypeOptionsResult.Project.LanguageServices.GetService<IGenerateTypeService>(); } if (_generateTypeOptionsResult.IsNewFile) { return await GetGenerateInNewFileOperationsAsync( namedType, _generateTypeOptionsResult.NewFileName, _generateTypeOptionsResult.Folders, _generateTypeOptionsResult.AreFoldersValidIdentifiers, _generateTypeOptionsResult.FullFilePath, _generateTypeOptionsResult.Project, _semanticDocument.Project, isDialog: true).ConfigureAwait(false); } else { return await GetGenerateIntoExistingDocumentAsync( namedType, _semanticDocument.Project, _generateTypeOptionsResult, isDialog: true).ConfigureAwait(false); } } } private string GetNamespaceToGenerateInto() { var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim(); var rootNamespace = _service.GetRootNamespace(_semanticDocument.SemanticModel.Compilation.Options).Trim(); if (!string.IsNullOrWhiteSpace(rootNamespace)) { if (namespaceToGenerateInto == rootNamespace || namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal)) { namespaceToGenerateInto = namespaceToGenerateInto[rootNamespace.Length..]; } } return namespaceToGenerateInto; } private string GetNamespaceToGenerateIntoForUsageWithNamespace(Project targetProject, Project triggeringProject) { var namespaceToGenerateInto = _state.NamespaceToGenerateInOpt.Trim(); if (targetProject.Language == LanguageNames.CSharp || targetProject == triggeringProject) { // If the target project is C# project then we don't have to make any modification to the namespace // or // This is a VB project generation into itself which requires no change as well return namespaceToGenerateInto; } // If the target Project is VB then we have to check if the RootNamespace of the VB project is the parent most namespace of the type being generated // True, Remove the RootNamespace // False, Add Global to the Namespace Debug.Assert(targetProject.Language == LanguageNames.VisualBasic); IGenerateTypeService targetLanguageService; if (_semanticDocument.Project.Language == LanguageNames.VisualBasic) { targetLanguageService = _service; } else { Debug.Assert(_targetLanguageService != null); targetLanguageService = _targetLanguageService; } var rootNamespace = targetLanguageService.GetRootNamespace(targetProject.CompilationOptions).Trim(); if (!string.IsNullOrWhiteSpace(rootNamespace)) { var rootNamespaceLength = CheckIfRootNamespacePresentInNamespace(namespaceToGenerateInto, rootNamespace); if (rootNamespaceLength > -1) { // True, Remove the RootNamespace namespaceToGenerateInto = namespaceToGenerateInto[rootNamespaceLength..]; } else { // False, Add Global to the Namespace namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto); } } else { // False, Add Global to the Namespace namespaceToGenerateInto = AddGlobalDotToTheNamespace(namespaceToGenerateInto); } return namespaceToGenerateInto; } private static string AddGlobalDotToTheNamespace(string namespaceToBeGenerated) => "Global." + namespaceToBeGenerated; // Returns the length of the meaningful rootNamespace substring part of namespaceToGenerateInto private static int CheckIfRootNamespacePresentInNamespace(string namespaceToGenerateInto, string rootNamespace) { if (namespaceToGenerateInto == rootNamespace) { return rootNamespace.Length; } if (namespaceToGenerateInto.StartsWith(rootNamespace + ".", StringComparison.Ordinal)) { return rootNamespace.Length + 1; } return -1; } private static void AddFoldersToNamespaceContainers(List<string> container, IList<string> folders) { // Add the folder as part of the namespace if there are not empty if (folders != null && folders.Count != 0) { // Remove the empty entries and replace the spaces in the folder name to '_' var refinedFolders = folders.Where(n => n != null && !n.IsEmpty()).Select(n => n.Replace(' ', '_')).ToArray(); container.AddRange(refinedFolders); } } private async Task<IEnumerable<CodeActionOperation>> GetGenerateInNewFileOperationsAsync( INamedTypeSymbol namedType, string documentName, IList<string> folders, bool areFoldersValidIdentifiers, string fullFilePath, Project projectToBeUpdated, Project triggeringProject, bool isDialog) { // First, we fork the solution with a new, empty, file in it. var newDocumentId = DocumentId.CreateNewId(projectToBeUpdated.Id, debugName: documentName); var newSolution = projectToBeUpdated.Solution.AddDocument(newDocumentId, documentName, string.Empty, folders, fullFilePath); // Now we get the semantic model for that file we just added. We do that to get the // root namespace in that new document, along with location for that new namespace. // That way, when we use the code gen service we can say "add this symbol to the // root namespace" and it will pick the one in the new file. var newDocument = newSolution.GetDocument(newDocumentId); var newSemanticModel = await newDocument.GetSemanticModelAsync(_cancellationToken).ConfigureAwait(false); var enclosingNamespace = newSemanticModel.GetEnclosingNamespace(0, _cancellationToken); var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport( isDialog, folders, areFoldersValidIdentifiers, projectToBeUpdated, triggeringProject); var containers = namespaceContainersAndUsings.containers; var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport; var rootNamespaceOrType = namedType.GenerateRootNamespaceOrType(containers); // Now, actually ask the code gen service to add this namespace or type to the root // namespace in the new file. This will properly generate the code, and add any // additional niceties like imports/usings. var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( newSolution, enclosingNamespace, rootNamespaceOrType, new CodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan())), _cancellationToken).ConfigureAwait(false); // containers is determined to be // 1: folders -> if triggered from Dialog // 2: containers -> if triggered not from a Dialog but from QualifiedName // 3: triggering document folder structure -> if triggered not from a Dialog and a SimpleName var adjustedContainer = isDialog ? folders : _state.SimpleName != _state.NameOrMemberAccessExpression ? containers.ToList() : _semanticDocument.Document.Folders.ToList(); if (newDocument.Project.Language == _semanticDocument.Document.Project.Language) { var formattingService = newDocument.GetLanguageService<INewDocumentFormattingService>(); if (formattingService is not null) { codeGenResult = await formattingService.FormatNewDocumentAsync(codeGenResult, _semanticDocument.Document, _cancellationToken).ConfigureAwait(false); } } // Now, take the code that would be generated and actually create an edit that would // produce a document with that code in it. var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); return await CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync( projectToBeUpdated, triggeringProject, documentName, newRoot, includeUsingsOrImports, adjustedContainer, SourceCodeKind.Regular, _cancellationToken).ConfigureAwait(false); } private async Task<IEnumerable<CodeActionOperation>> CreateAddDocumentAndUpdateUsingsOrImportsOperationsAsync( Project projectToBeUpdated, Project triggeringProject, string documentName, SyntaxNode root, string includeUsingsOrImports, IList<string> containers, SourceCodeKind sourceCodeKind, CancellationToken cancellationToken) { // TODO(cyrusn): make sure documentId is unique. var documentId = DocumentId.CreateNewId(projectToBeUpdated.Id, documentName); var updatedSolution = projectToBeUpdated.Solution.AddDocument(DocumentInfo.Create( documentId, documentName, containers, sourceCodeKind)); updatedSolution = updatedSolution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity); // Update the Generating Document with a using if required if (includeUsingsOrImports != null) { updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync(updatedSolution, null, _semanticDocument.Document, _state.SimpleName, includeUsingsOrImports, cancellationToken).ConfigureAwait(false); } // Add reference of the updated project to the triggering Project if they are 2 different projects updatedSolution = AddProjectReference(projectToBeUpdated, triggeringProject, updatedSolution); return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution), new OpenDocumentOperation(documentId) }; } private static Solution AddProjectReference(Project projectToBeUpdated, Project triggeringProject, Solution updatedSolution) { if (projectToBeUpdated != triggeringProject) { if (!triggeringProject.ProjectReferences.Any(pr => pr.ProjectId == projectToBeUpdated.Id)) { updatedSolution = updatedSolution.AddProjectReference(triggeringProject.Id, new ProjectReference(projectToBeUpdated.Id)); } } return updatedSolution; } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoContainingNamespaceOperationsAsync(INamedTypeSymbol namedType) { var enclosingNamespace = _semanticDocument.SemanticModel.GetEnclosingNamespace( _state.SimpleName.SpanStart, _cancellationToken); var solution = _semanticDocument.Project.Solution; var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync( solution, enclosingNamespace, namedType, new CodeGenerationOptions( afterThisLocation: _semanticDocument.SyntaxTree.GetLocation(_state.SimpleName.Span), options: await _semanticDocument.Document.GetOptionsAsync(_cancellationToken).ConfigureAwait(false)), _cancellationToken).ConfigureAwait(false); return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) }; } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoExistingDocumentAsync( INamedTypeSymbol namedType, Project triggeringProject, GenerateTypeOptionsResult generateTypeOptionsResult, bool isDialog) { var root = await generateTypeOptionsResult.ExistingDocument.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); var folders = generateTypeOptionsResult.ExistingDocument.Folders; var namespaceContainersAndUsings = GetNamespaceContainersAndAddUsingsOrImport(isDialog, new List<string>(folders), generateTypeOptionsResult.AreFoldersValidIdentifiers, generateTypeOptionsResult.Project, triggeringProject); var containers = namespaceContainersAndUsings.containers; var includeUsingsOrImports = namespaceContainersAndUsings.usingOrImport; (INamespaceSymbol, INamespaceOrTypeSymbol, Location) enclosingNamespaceGeneratedTypeToAddAndLocation; if (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange) { enclosingNamespaceGeneratedTypeToAddAndLocation = await _service.GetOrGenerateEnclosingNamespaceSymbolAsync( namedType, containers, generateTypeOptionsResult.ExistingDocument, root, _cancellationToken).ConfigureAwait(false); } else { enclosingNamespaceGeneratedTypeToAddAndLocation = await _targetLanguageService.GetOrGenerateEnclosingNamespaceSymbolAsync( namedType, containers, generateTypeOptionsResult.ExistingDocument, root, _cancellationToken).ConfigureAwait(false); } var solution = _semanticDocument.Project.Solution; var codeGenResult = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( solution, enclosingNamespaceGeneratedTypeToAddAndLocation.Item1, enclosingNamespaceGeneratedTypeToAddAndLocation.Item2, new CodeGenerationOptions(afterThisLocation: enclosingNamespaceGeneratedTypeToAddAndLocation.Item3), _cancellationToken).ConfigureAwait(false); var newRoot = await codeGenResult.GetSyntaxRootAsync(_cancellationToken).ConfigureAwait(false); var updatedSolution = solution.WithDocumentSyntaxRoot(generateTypeOptionsResult.ExistingDocument.Id, newRoot, PreservationMode.PreserveIdentity); // Update the Generating Document with a using if required if (includeUsingsOrImports != null) { updatedSolution = await _service.TryAddUsingsOrImportToDocumentAsync( updatedSolution, generateTypeOptionsResult.ExistingDocument.Id == _semanticDocument.Document.Id ? newRoot : null, _semanticDocument.Document, _state.SimpleName, includeUsingsOrImports, _cancellationToken).ConfigureAwait(false); } updatedSolution = AddProjectReference(generateTypeOptionsResult.Project, triggeringProject, updatedSolution); return new CodeActionOperation[] { new ApplyChangesOperation(updatedSolution) }; } private (string[] containers, string usingOrImport) GetNamespaceContainersAndAddUsingsOrImport( bool isDialog, IList<string> folders, bool areFoldersValidIdentifiers, Project targetProject, Project triggeringProject) { string includeUsingsOrImports = null; if (!areFoldersValidIdentifiers) { folders = SpecializedCollections.EmptyList<string>(); } // Now actually create the symbol that we want to add to the root namespace. The // symbol may either be a named type (if we're not generating into a namespace) or // it may be a namespace symbol. string[] containers = null; if (!isDialog) { // Not generated from the Dialog containers = GetNamespaceToGenerateInto().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); } else if (!_service.IsSimpleName(_state.NameOrMemberAccessExpression)) { // If the usage was with a namespace containers = GetNamespaceToGenerateIntoForUsageWithNamespace(targetProject, triggeringProject).Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); } else { // Generated from the Dialog var containerList = new List<string>(); var rootNamespaceOfTheProjectGeneratedInto = _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange ? _service.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim() : _targetLanguageService.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim(); var defaultNamespace = _generateTypeOptionsResult.DefaultNamespace; // Case 1 : If the type is generated into the same C# project or // Case 2 : If the type is generated from a C# project to a C# Project // Case 3 : If the Type is generated from a VB Project to a C# Project // Using and Namespace will be the DefaultNamespace + Folder Structure if ((_semanticDocument.Project == _generateTypeOptionsResult.Project && _semanticDocument.Project.Language == LanguageNames.CSharp) || (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp) || _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.VisualBasicToCSharp) { if (!string.IsNullOrWhiteSpace(defaultNamespace)) { containerList.Add(defaultNamespace); } // Populate the ContainerList AddFoldersToNamespaceContainers(containerList, folders); containers = containerList.ToArray(); includeUsingsOrImports = string.Join(".", containerList.ToArray()); } // Case 4 : If the type is generated into the same VB project or // Case 5 : If Type is generated from a VB Project to VB Project // Case 6 : If Type is generated from a C# Project to VB Project // Namespace will be Folder Structure and Import will have the RootNamespace of the project generated into as part of the Imports if ((_semanticDocument.Project == _generateTypeOptionsResult.Project && _semanticDocument.Project.Language == LanguageNames.VisualBasic) || (_semanticDocument.Project != _generateTypeOptionsResult.Project && _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.VisualBasic) || _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.CSharpToVisualBasic) { // Populate the ContainerList AddFoldersToNamespaceContainers(containerList, folders); containers = containerList.ToArray(); includeUsingsOrImports = string.Join(".", containerList.ToArray()); if (!string.IsNullOrWhiteSpace(rootNamespaceOfTheProjectGeneratedInto)) { includeUsingsOrImports = string.IsNullOrEmpty(includeUsingsOrImports) ? rootNamespaceOfTheProjectGeneratedInto : rootNamespaceOfTheProjectGeneratedInto + "." + includeUsingsOrImports; } } Debug.Assert(includeUsingsOrImports != null); } return (containers, includeUsingsOrImports); } private async Task<IEnumerable<CodeActionOperation>> GetGenerateIntoTypeOperationsAsync(INamedTypeSymbol namedType) { var solution = _semanticDocument.Project.Solution; var codeGenResult = await CodeGenerator.AddNamedTypeDeclarationAsync( solution, _state.TypeToGenerateInOpt, namedType, new CodeGenerationOptions(contextLocation: _state.SimpleName.GetLocation()), _cancellationToken) .ConfigureAwait(false); return new CodeActionOperation[] { new ApplyChangesOperation(codeGenResult.Project.Solution) }; } private ImmutableArray<ITypeSymbol> GetArgumentTypes(IList<TArgumentSyntax> argumentList) { var types = argumentList.Select(a => _service.DetermineArgumentType(_semanticDocument.SemanticModel, a, _cancellationToken)); return types.SelectAsArray(FixType); } private ImmutableArray<TExpressionSyntax> GetArgumentExpressions(IList<TArgumentSyntax> argumentList) { var syntaxFacts = _semanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>(); return argumentList.SelectAsArray(a => (TExpressionSyntax)syntaxFacts.GetExpressionOfArgument(a)); } private ITypeSymbol FixType( ITypeSymbol typeSymbol) { var compilation = _semanticDocument.SemanticModel.Compilation; return typeSymbol.RemoveUnnamedErrorTypes(compilation); } private async Task<bool> FindExistingOrCreateNewMemberAsync( ParameterName parameterName, ITypeSymbol parameterType, ImmutableDictionary<string, ISymbol>.Builder parameterToFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap) { // If the base types have an accessible field or property with the same name and // an acceptable type, then we should just defer to that. if (_state.BaseTypeOrInterfaceOpt != null) { var expectedFieldName = parameterName.NameBasedOnArgument; var members = from t in _state.BaseTypeOrInterfaceOpt.GetBaseTypesAndThis() from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where IsSymbolAccessible(m) where IsViableFieldOrProperty(parameterType, m) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { parameterToFieldMap[parameterName.BestNameForParameter] = symbol; return true; } } var fieldNamingRule = await _semanticDocument.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, _cancellationToken).ConfigureAwait(false); var nameToUse = fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); parameterToNewFieldMap[parameterName.BestNameForParameter] = nameToUse; return false; } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (symbol != null && !symbol.IsStatic && parameterType.Language == symbol.Language) { if (symbol is IFieldSymbol field) { return !field.IsReadOnly && _service.IsConversionImplicit(_semanticDocument.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.SetMethod != null && IsSymbolAccessible(property.SetMethod) && _service.IsConversionImplicit(_semanticDocument.SemanticModel.Compilation, parameterType, property.Type); } } return false; } private bool IsSymbolAccessible(ISymbol symbol) { // Public and protected constructors are accessible. Internal constructors are // accessible if we have friend access. We can't call the normal accessibility // checkers since they will think that a protected constructor isn't accessible // (since we don't have the destination type that would have access to them yet). switch (symbol.DeclaredAccessibility) { case Accessibility.ProtectedOrInternal: case Accessibility.Protected: case Accessibility.Public: return true; case Accessibility.ProtectedAndInternal: case Accessibility.Internal: // TODO: Code coverage return _semanticDocument.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo( symbol.ContainingAssembly); default: return false; } } } } }
1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmExceptionCode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\Concord\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger { // // Summary: // Defines the HRESULT codes used by this API. public enum DkmExceptionCode { // // Summary: // Unspecified error. E_FAIL = -2147467259, // // Summary: // A debugger is already attached. E_ATTACH_DEBUGGER_ALREADY_ATTACHED = -2147221503, // // Summary: // The process does not have sufficient privileges to be debugged. E_ATTACH_DEBUGGEE_PROCESS_SECURITY_VIOLATION = -2147221502, // // Summary: // The desktop cannot be debugged. E_ATTACH_CANNOT_ATTACH_TO_DESKTOP = -2147221501, // // Summary: // Unmanaged debugging is not available. E_LAUNCH_NO_INTEROP = -2147221499, // // Summary: // Debugging isn't possible due to an incompatibility within the CLR implementation. E_LAUNCH_DEBUGGING_NOT_POSSIBLE = -2147221498, // // Summary: // Visual Studio cannot debug managed applications because a kernel debugger is // enabled on the system. Please see Help for further information. E_LAUNCH_KERNEL_DEBUGGER_ENABLED = -2147221497, // // Summary: // Visual Studio cannot debug managed applications because a kernel debugger is // present on the system. Please see Help for further information. E_LAUNCH_KERNEL_DEBUGGER_PRESENT = -2147221496, // // Summary: // The debugger does not support debugging managed and native code at the same time // on the platform of the target computer/device. Configure the debugger to debug // only native code or only managed code. E_INTEROP_NOT_SUPPORTED = -2147221495, // // Summary: // The maximum number of processes is already being debugged. E_TOO_MANY_PROCESSES = -2147221494, // // Summary: // Script debugging of your application is disabled in Internet Explorer. To enable // script debugging in Internet Explorer, choose Internet Options from the Tools // menu and navigate to the Advanced tab. Under the Browsing category, clear the // 'Disable Script Debugging (Internet Explorer)' checkbox, then restart Internet // Explorer. E_MSHTML_SCRIPT_DEBUGGING_DISABLED = -2147221493, // // Summary: // The correct version of pdm.dll is not registered. Repair your Visual Studio installation, // or run 'regsvr32.exe "%CommonProgramFiles%\Microsoft Shared\VS7Debug\pdm.dll"'. E_SCRIPT_PDM_NOT_REGISTERED = -2147221492, // // Summary: // The .NET debugger has not been installed properly. The most probable cause is // that mscordbi.dll is not properly registered. Click Help for more information // on how to repair the .NET debugger. E_DE_CLR_DBG_SERVICES_NOT_INSTALLED = -2147221491, // // Summary: // There is no managed code running in the process. In order to attach to a process // with the .NET debugger, managed code must be running in the process before attaching. E_ATTACH_NO_CLR_PROGRAMS = -2147221490, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor has been closed on the remote // machine. E_REMOTE_SERVER_CLOSED = -2147221488, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer does // not support debugging code running in the Common Language Runtime. E_CLR_NOT_SUPPORTED = -2147221482, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer does // not support debugging code running in the Common Language Runtime on a 64-bit // computer. E_64BIT_CLR_NOT_SUPPORTED = -2147221481, // // Summary: // Cannot debug minidumps and processes at the same time. E_CANNOT_MIX_MINDUMP_DEBUGGING = -2147221480, E_DEBUG_ENGINE_NOT_REGISTERED = -2147221479, // // Summary: // This application has failed to start because the application configuration is // incorrect. Review the manifest file for possible errors. Reinstalling the application // may fix this problem. For more details, please see the application event log. E_LAUNCH_SXS_ERROR = -2147221478, // // Summary: // Failed to initialize msdbg2.dll for script debugging. If this problem persists, // use 'Add or Remove Programs' in Control Panel to repair your Visual Studio installation. E_FAILED_TO_INITIALIZE_SCRIPT_PROXY = -2147221477, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) does not appear // to be running on the remote computer. This may be because a firewall is preventing // communication to the remote computer. Please see Help for assistance on configuring // remote debugging. E_REMOTE_SERVER_DOES_NOT_EXIST = -2147221472, // // Summary: // Access is denied. Can not connect to Microsoft Visual Studio Remote Debugging // Monitor on the remote computer. E_REMOTE_SERVER_ACCESS_DENIED = -2147221471, // // Summary: // The debugger cannot connect to the remote computer. The debugger was unable to // resolve the specified computer name. E_REMOTE_SERVER_MACHINE_DOES_NOT_EXIST = -2147221470, // // Summary: // The debugger is not properly installed. Run setup to install or repair the debugger. E_DEBUGGER_NOT_REGISTERED_PROPERLY = -2147221469, // // Summary: // Access is denied. This seems to be because the 'Network access: Sharing and security // model for local accounts' security policy does not allow users to authenticate // as themselves. Please use the 'Local Security Settings' administration tool on // the local computer to configure this option. E_FORCE_GUEST_MODE_ENABLED = -2147221468, E_GET_IWAM_USER_FAILURE = -2147221467, // // Summary: // The specified remote server name is not valid. E_REMOTE_SERVER_INVALID_NAME = -2147221466, // // Summary: // Microsoft Visual Studio Debugging Monitor (MSVSMON.EXE) failed to start. If this // problem persists, please repair your Visual Studio installation via 'Add or Remove // Programs' in Control Panel. E_AUTO_LAUNCH_EXEC_FAILURE = -2147221464, // // Summary: // Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) is not running // under your user account and MSVSMON could not be automatically started. MSVSMON // must be manually started, or the Visual Studio remote debugging components must // be installed on the remote computer. Please see Help for assistance. E_REMOTE_COMPONENTS_NOT_REGISTERED = -2147221461, // // Summary: // A DCOM error occurred trying to contact the remote computer. Access is denied. // It may be possible to avoid this error by changing your settings to debug only // native code or only managed code. E_DCOM_ACCESS_DENIED = -2147221460, // // Summary: // Debugging using the Default transport is not possible because the remote machine // has 'Share-level access control' enabled. To enable debugging on the remote machine, // go to Control Panel -> Network -> Access control, and set Access control to be // 'User-level access control'. E_SHARE_LEVEL_ACCESS_CONTROL_ENABLED = -2147221459, // // Summary: // Logon failure: unknown user name or bad password. See help for more information. E_WORKGROUP_REMOTE_LOGON_FAILURE = -2147221458, // // Summary: // Windows authentication is disabled in the Microsoft Visual Studio Remote Debugging // Monitor (MSVSMON). To connect, choose one of the following options. 1. Enable // Windows authentication in MSVSMON 2. Reconfigure your project to disable Windows // authentication 3. Use the 'Remote (native with no authentication)' transport // in the 'Attach to Process' dialog E_WINAUTH_CONNECT_NOT_SUPPORTED = -2147221457, // // Summary: // A previous expression evaluation is still in progress. E_EVALUATE_BUSY_WITH_EVALUATION = -2147221456, // // Summary: // The expression evaluation took too long. E_EVALUATE_TIMEOUT = -2147221455, // // Summary: // Mixed-mode debugging does not support Microsoft.NET Framework versions earlier // than 2.0. E_INTEROP_CLR_TOO_OLD = -2147221454, // // Summary: // Check for one of the following. 1. The application you are trying to debug uses // a version of the Microsoft .NET Framework that is not supported by the debugger. // 2. The debugger has made an incorrect assumption about the Microsoft .NET Framework // version your application is going to use. 3. The Microsoft .NET Framework version // specified by you for debugging is incorrect. Please see the Visual Studio .NET // debugger documentation for correctly specifying the Microsoft .NET Framework // version your application is going to use for debugging. E_CLR_INCOMPATIBLE_PROTOCOL = -2147221453, // // Summary: // Unable to attach because process is running in fiber mode. E_CLR_CANNOT_DEBUG_FIBER_PROCESS = -2147221452, // // Summary: // Visual Studio has insufficient privileges to debug this process. To debug this // process, Visual Studio must be run as an administrator. E_PROCESS_OBJECT_ACCESS_DENIED = -2147221451, // // Summary: // Visual Studio has insufficient privileges to inspect the process's identity. E_PROCESS_TOKEN_ACCESS_DENIED = -2147221450, // // Summary: // Visual Studio was unable to inspect the process's identity. This is most likely // due to service configuration on the computer running the process. E_PROCESS_TOKEN_ACCESS_DENIED_NO_TS = -2147221449, E_OPERATION_REQUIRES_ELEVATION = -2147221448, // // Summary: // Visual Studio has insufficient privileges to debug this process. To debug this // process, Visual Studio must be run as an administrator. E_ATTACH_REQUIRES_ELEVATION = -2147221447, E_MEMORY_NOTSUPPORTED = -2147221440, // // Summary: // The type of code you are currently debugging does not support disassembly. E_DISASM_NOTSUPPORTED = -2147221439, // // Summary: // The specified address does not exist in disassembly. E_DISASM_BADADDRESS = -2147221438, E_DISASM_NOTAVAILABLE = -2147221437, // // Summary: // The breakpoint has been deleted. E_BP_DELETED = -2147221408, // // Summary: // The process has been terminated. E_PROCESS_DESTROYED = -2147221392, E_PROCESS_DEBUGGER_IS_DEBUGGEE = -2147221391, // // Summary: // Terminating this process is not allowed. E_TERMINATE_FORBIDDEN = -2147221390, // // Summary: // The thread has terminated. E_THREAD_DESTROYED = -2147221387, // // Summary: // Cannot find port. Check the remote machine name. E_PORTSUPPLIER_NO_PORT = -2147221376, E_PORT_NO_REQUEST = -2147221360, E_COMPARE_CANNOT_COMPARE = -2147221344, E_JIT_INVALID_PID = -2147221327, E_JIT_VSJITDEBUGGER_NOT_REGISTERED = -2147221325, E_JIT_APPID_NOT_REGISTERED = -2147221324, E_JIT_RUNTIME_VERSION_UNSUPPORTED = -2147221322, E_SESSION_TERMINATE_DETACH_FAILED = -2147221310, E_SESSION_TERMINATE_FAILED = -2147221309, // // Summary: // Detach is not supported on Microsoft Windows 2000 for native code. E_DETACH_NO_PROXY = -2147221296, E_DETACH_TS_UNSUPPORTED = -2147221280, E_DETACH_IMPERSONATE_FAILURE = -2147221264, // // Summary: // This thread has called into a function that cannot be displayed. E_CANNOT_SET_NEXT_STATEMENT_ON_NONLEAF_FRAME = -2147221248, E_TARGET_FILE_MISMATCH = -2147221247, E_IMAGE_NOT_LOADED = -2147221246, E_FIBER_NOT_SUPPORTED = -2147221245, // // Summary: // The next statement cannot be set to another function. E_CANNOT_SETIP_TO_DIFFERENT_FUNCTION = -2147221244, // // Summary: // In order to Set Next Statement, right-click on the active frame in the Call Stack // window and select "Unwind To This Frame". E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = -2147221243, // // Summary: // The next statement cannot be changed until the current statement has completed. E_ENC_SETIP_REQUIRES_CONTINUE = -2147221241, // // Summary: // The next statement cannot be set from outside a finally block to within it. E_CANNOT_SET_NEXT_STATEMENT_INTO_FINALLY = -2147221240, // // Summary: // The next statement cannot be set from within a finally block to a statement outside // of it. E_CANNOT_SET_NEXT_STATEMENT_OUT_OF_FINALLY = -2147221239, // // Summary: // The next statement cannot be set from outside a catch block to within it. E_CANNOT_SET_NEXT_STATEMENT_INTO_CATCH = -2147221238, // // Summary: // The next statement cannot be changed at this time. E_CANNOT_SET_NEXT_STATEMENT_GENERAL = -2147221237, // // Summary: // The next statement cannot be set into or out of a catch filter. E_CANNOT_SET_NEXT_STATEMENT_INTO_OR_OUT_OF_FILTER = -2147221236, // // Summary: // This process is not currently executing the type of code that you selected to // debug. E_ASYNCBREAK_NO_PROGRAMS = -2147221232, // // Summary: // The debugger is still attaching to the process or the process is not currently // executing the type of code selected for debugging. E_ASYNCBREAK_DEBUGGEE_NOT_INITIALIZED = -2147221231, // // Summary: // The debugger is handling debug events or performing evaluations that do not allow // nested break state. Try again. E_ASYNCBREAK_UNABLE_TO_PROCESS = -2147221230, // // Summary: // The web server has been locked down and is blocking the DEBUG verb, which is // required to enable debugging. Please see Help for assistance. E_WEBDBG_DEBUG_VERB_BLOCKED = -2147221215, // // Summary: // ASP debugging is disabled because the ASP process is running as a user that does // not have debug permissions. Please see Help for assistance. E_ASP_USER_ACCESS_DENIED = -2147221211, // // Summary: // The remote debugging components are not registered or running on the web server. // Ensure the proper version of msvsmon is running on the remote computer. E_AUTO_ATTACH_NOT_REGISTERED = -2147221210, // // Summary: // An unexpected DCOM error occurred while trying to automatically attach to the // remote web server. Try manually attaching to the remote web server using the // 'Attach To Process' dialog. E_AUTO_ATTACH_DCOM_ERROR = -2147221209, // // Summary: // Expected failure from web server CoCreating debug verb CLSID E_AUTO_ATTACH_COCREATE_FAILURE = -2147221208, E_AUTO_ATTACH_CLASSNOTREG = -2147221207, // // Summary: // The current thread cannot continue while an expression is being evaluated on // another thread. E_CANNOT_CONTINUE_DURING_PENDING_EXPR_EVAL = -2147221200, E_REMOTE_REDIRECTION_UNSUPPORTED = -2147221195, // // Summary: // The specified working directory does not exist or is not a full path. E_INVALID_WORKING_DIRECTORY = -2147221194, // // Summary: // The application manifest has the uiAccess attribute set to 'true'. Running an // Accessibility application requires following the steps described in Help. E_LAUNCH_FAILED_WITH_ELEVATION = -2147221193, // // Summary: // This program requires additional permissions to start. To debug this program, // restart Visual Studio as an administrator. E_LAUNCH_ELEVATION_REQUIRED = -2147221192, // // Summary: // Cannot locate Microsoft Internet Explorer. E_CANNOT_FIND_INTERNET_EXPLORER = -2147221191, // // Summary: // The Visual Studio Remote Debugger (MSVSMON.EXE) has insufficient privileges to // debug this process. To debug this process, the remote debugger must be run as // an administrator. E_REMOTE_PROCESS_OBJECT_ACCESS_DENIED = -2147221190, // // Summary: // The Visual Studio Remote Debugger (MSVSMON.EXE) has insufficient privileges to // debug this process. To debug this process, launch the remote debugger using 'Run // as administrator'. If the remote debugger has been configured to run as a service, // ensure that it is running under an account that is a member of the Administrators // group. E_REMOTE_ATTACH_REQUIRES_ELEVATION = -2147221189, // // Summary: // This program requires additional permissions to start. To debug this program, // launch the Visual Studio Remote Debugger (MSVSMON.EXE) using 'Run as administrator'. E_REMOTE_LAUNCH_ELEVATION_REQUIRED = -2147221188, // // Summary: // The attempt to unwind the callstack failed. Unwinding is not possible in the // following scenarios: 1. Debugging was started via Just-In-Time debugging. 2. // An unwind is in progress. 3. A System.StackOverflowException or System.Threading.ThreadAbortException // exception has been thrown. E_EXCEPTION_CANNOT_BE_INTERCEPTED = -2147221184, // // Summary: // You can only unwind to the function that caused the exception. E_EXCEPTION_CANNOT_UNWIND_ABOVE_CALLBACK = -2147221183, // // Summary: // Unwinding from the current exception is not supported. E_INTERCEPT_CURRENT_EXCEPTION_NOT_SUPPORTED = -2147221182, // // Summary: // You cannot unwind from an unhandled exception while doing managed and native // code debugging at the same time. E_INTERCEPT_CANNOT_UNWIND_LASTCHANCE_INTEROP = -2147221181, E_JMC_CANNOT_SET_STATUS = -2147221179, // // Summary: // The process has been terminated. E_DESTROYED = -2147220991, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor is either not running on // the remote machine or is running in Windows authentication mode. E_REMOTE_NOMSVCMON = -2147220990, // // Summary: // The IP address for the remote machine is not valid. E_REMOTE_BADIPADDRESS = -2147220989, // // Summary: // The remote machine is not responding. E_REMOTE_MACHINEDOWN = -2147220988, // // Summary: // The remote machine name is not specified. E_REMOTE_MACHINEUNSPECIFIED = -2147220987, // // Summary: // Other programs cannot be debugged during the current mixed dump debugging session. E_CRASHDUMP_ACTIVE = -2147220986, // // Summary: // All of the threads are frozen. Use the Threads window to unfreeze at least one // thread before attempting to step or continue the process. E_ALL_THREADS_SUSPENDED = -2147220985, // // Summary: // The debugger transport DLL cannot be loaded. E_LOAD_DLL_TL = -2147220984, // // Summary: // mspdb110.dll cannot be loaded. E_LOAD_DLL_SH = -2147220983, // // Summary: // MSDIS170.dll cannot be loaded. E_LOAD_DLL_EM = -2147220982, // // Summary: // NatDbgEE.dll cannot be loaded. E_LOAD_DLL_EE = -2147220981, // // Summary: // NatDbgDM.dll cannot be loaded. E_LOAD_DLL_DM = -2147220980, // // Summary: // Old version of DBGHELP.DLL found, does not support minidumps. E_LOAD_DLL_MD = -2147220979, // // Summary: // Input or output cannot be redirected because the specified file is invalid. E_IOREDIR_BADFILE = -2147220978, // // Summary: // Input or output cannot be redirected because the syntax is incorrect. E_IOREDIR_BADSYNTAX = -2147220977, // // Summary: // The remote debugger is not an acceptable version. E_REMOTE_BADVERSION = -2147220976, // // Summary: // This operation is not supported when debugging dump files. E_CRASHDUMP_UNSUPPORTED = -2147220975, // // Summary: // The remote computer does not have a CLR version which is compatible with the // remote debugging components. To install a compatible CLR version, see the instructions // in the 'Remote Components Setup' page on the Visual Studio CD. E_REMOTE_BAD_CLR_VERSION = -2147220974, // // Summary: // The specified file is an unrecognized or unsupported binary format. E_UNSUPPORTED_BINARY = -2147220971, // // Summary: // The process has been soft broken. E_DEBUGGEE_BLOCKED = -2147220970, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer is // running as a different user. E_REMOTE_NOUSERMSVCMON = -2147220969, // // Summary: // Stepping to or from system code on a machine running Windows 95/Windows 98/Windows // ME is not allowed. E_STEP_WIN9xSYSCODE = -2147220968, E_INTEROP_ORPC_INIT = -2147220967, // // Summary: // The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) // cannot be used to debug 32-bit processes or 32-bit dumps. Please use the 32-bit // version instead. E_CANNOT_DEBUG_WIN32 = -2147220965, // // Summary: // The 32-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) // cannot be used to debug 64-bit processes or 64-bit dumps. Please use the 64-bit // version instead. E_CANNOT_DEBUG_WIN64 = -2147220964, // // Summary: // Mini-Dumps cannot be read on this system. Please use a Windows NT based system E_MINIDUMP_READ_WIN9X = -2147220963, // // Summary: // Attaching to a process in a different terminal server session is not supported // on this computer. Try remote debugging to the machine and running the Microsoft // Visual Studio Remote Debugging Monitor in the process's session. E_CROSS_TSSESSION_ATTACH = -2147220962, // // Summary: // A stepping breakpoint could not be set E_STEP_BP_SET_FAILED = -2147220961, // // Summary: // The debugger transport DLL being loaded has an incorrect version. E_LOAD_DLL_TL_INCORRECT_VERSION = -2147220960, // // Summary: // NatDbgDM.dll being loaded has an incorrect version. E_LOAD_DLL_DM_INCORRECT_VERSION = -2147220959, E_REMOTE_NOMSVCMON_PIPE = -2147220958, // // Summary: // msdia120.dll cannot be loaded. E_LOAD_DLL_DIA = -2147220957, // // Summary: // The dump file you opened is corrupted. E_DUMP_CORRUPTED = -2147220956, // // Summary: // Mixed-mode debugging of x64 processes is not supported when using Microsoft.NET // Framework versions earlier than 4.0. E_INTEROP_X64 = -2147220955, // // Summary: // Debugging older format crashdumps is not supported. E_CRASHDUMP_DEPRECATED = -2147220953, // // Summary: // Debugging managed-only minidumps is not supported. Specify 'Mixed' for the 'Debugger // Type' in project properties. E_LAUNCH_MANAGEDONLYMINIDUMP_UNSUPPORTED = -2147220952, // // Summary: // Debugging managed or mixed-mode minidumps is not supported on IA64 platforms. // Specify 'Native' for the 'Debugger Type' in project properties. E_LAUNCH_64BIT_MANAGEDMINIDUMP_UNSUPPORTED = -2147220951, // // Summary: // The remote tools are not signed correctly. E_DEVICEBITS_NOT_SIGNED = -2147220479, // // Summary: // Attach is not enabled for this process with this debug type. E_ATTACH_NOT_ENABLED = -2147220478, // // Summary: // The connection has been broken. E_REMOTE_DISCONNECT = -2147220477, // // Summary: // The threads in the process cannot be suspended at this time. This may be a temporary // condition. E_BREAK_ALL_FAILED = -2147220476, // // Summary: // Access denied. Try again, then check your device for a prompt. E_DEVICE_ACCESS_DENIED_SELECT_YES = -2147220475, // // Summary: // Unable to complete the operation. This could be because the device's security // settings are too restrictive. Please use the Device Security Manager to change // the settings and try again. E_DEVICE_ACCESS_DENIED = -2147220474, // // Summary: // The remote connection to the device has been lost. Verify the device connection // and restart debugging. E_DEVICE_CONNRESET = -2147220473, // // Summary: // Unable to load the CLR. The target device does not have a compatible version // of the CLR installed for the application you are attempting to debug. Verify // that your device supports the appropriate CLR version and has that CLR installed. // Some devices do not support automatic CLR upgrade. E_BAD_NETCF_VERSION = -2147220472, E_REFERENCE_NOT_VALID = -2147220223, E_PROPERTY_NOT_VALID = -2147220207, E_SETVALUE_VALUE_CANNOT_BE_SET = -2147220191, E_SETVALUE_VALUE_IS_READONLY = -2147220190, E_SETVALUEASREFERENCE_NOTSUPPORTED = -2147220189, E_CANNOT_GET_UNMANAGED_MEMORY_CONTEXT = -2147220127, E_GETREFERENCE_NO_REFERENCE = -2147220095, E_CODE_CONTEXT_OUT_OF_SCOPE = -2147220063, E_INVALID_SESSIONID = -2147220062, // // Summary: // The Visual Studio Remote Debugger on the target computer cannot connect back // to this computer. A firewall may be preventing communication via DCOM to the // local computer. It may be possible to avoid this error by changing your settings // to debug only native code or only managed code. E_SERVER_UNAVAILABLE_ON_CALLBACK = -2147220061, // // Summary: // The Visual Studio Remote Debugger on the target computer cannot connect back // to this computer. Authentication failed. It may be possible to avoid this error // by changing your settings to debug only native code or only managed code. E_ACCESS_DENIED_ON_CALLBACK = -2147220060, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer could // not connect to this computer because there was no available authentication service. // It may be possible to avoid this error by changing your settings to debug only // native code or only managed code. E_UNKNOWN_AUTHN_SERVICE_ON_CALLBACK = -2147220059, E_NO_SESSION_AVAILABLE = -2147220058, E_CLIENT_NOT_LOGGED_ON = -2147220057, E_OTHER_USERS_SESSION = -2147220056, E_USER_LEVEL_ACCESS_CONTROL_REQUIRED = -2147220055, // // Summary: // Can not evaluate script expressions while thread is stopped in the CLR. E_SCRIPT_CLR_EE_DISABLED = -2147220048, // // Summary: // Server side-error occurred on sending debug HTTP request. E_HTTP_SERVERERROR = -2147219712, // // Summary: // An authentication error occurred while communicating with the web server. Please // see Help for assistance. E_HTTP_UNAUTHORIZED = -2147219711, // // Summary: // Could not start ASP.NET debugging. More information may be available by starting // the project without debugging. E_HTTP_SENDREQUEST_FAILED = -2147219710, // // Summary: // The web server is not configured correctly. See help for common configuration // errors. Running the web page outside of the debugger may provide further information. E_HTTP_FORBIDDEN = -2147219709, // // Summary: // The server does not support debugging of ASP.NET or ATL Server applications. // Click Help for more information on how to enable debugging. E_HTTP_NOT_SUPPORTED = -2147219708, // // Summary: // Could not start ASP.NET or ATL Server debugging. E_HTTP_NO_CONTENT = -2147219707, // // Summary: // The web server could not find the requested resource. E_HTTP_NOT_FOUND = -2147219706, // // Summary: // The debug request could not be processed by the server due to invalid syntax. E_HTTP_BAD_REQUEST = -2147219705, // // Summary: // You do not have permissions to debug the web server process. You need to either // be running as the same user account as the web server, or have administrator // privilege. E_HTTP_ACCESS_DENIED = -2147219704, // // Summary: // Unable to connect to the web server. Verify that the web server is running and // that incoming HTTP requests are not blocked by a firewall. E_HTTP_CONNECT_FAILED = -2147219703, E_HTTP_EXCEPTION = -2147219702, // // Summary: // The web server did not respond in a timely manner. This may be because another // debugger is already attached to the web server. E_HTTP_TIMEOUT = -2147219701, // // Summary: // IIS does not list a web site that matches the launched URL. E_HTTP_SITE_NOT_FOUND = -2147219700, // // Summary: // IIS does not list an application that matches the launched URL. E_HTTP_APP_NOT_FOUND = -2147219699, // // Summary: // Debugging requires the IIS Management Console. To install, go to Control Panel->Programs->Turn // Windows features on or off. Check Internet Information Services->Web Management // Tools->IIS Management Console. E_HTTP_MANAGEMENT_API_MISSING = -2147219698, // // Summary: // The IIS worker process for the launched URL is not currently running. E_HTTP_NO_PROCESS = -2147219697, E_64BIT_COMPONENTS_NOT_INSTALLED = -2147219632, // // Summary: // The Visual Studio debugger cannot connect to the remote computer. Unable to initiate // DCOM communication. Please see Help for assistance. E_UNMARSHAL_SERVER_FAILED = -2147219631, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer cannot // connect to the local computer. Unable to initiate DCOM communication. Please // see Help for assistance. E_UNMARSHAL_CALLBACK_FAILED = -2147219630, // // Summary: // The Visual Studio debugger cannot connect to the remote computer. An RPC policy // is enabled on the local computer which prevents remote debugging. Please see // Help for assistance. E_RPC_REQUIRES_AUTHENTICATION = -2147219627, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor cannot logon to the local // computer: unknown user name or bad password. It may be possible to avoid this // error by changing your settings to debug only native code or only managed code. E_LOGON_FAILURE_ON_CALLBACK = -2147219626, // // Summary: // The Visual Studio debugger cannot establish a DCOM connection to the remote computer. // A firewall may be preventing communication via DCOM to the remote computer. It // may be possible to avoid this error by changing your settings to debug only native // code or only managed code. E_REMOTE_SERVER_UNAVAILABLE = -2147219625, E_REMOTE_CONNECT_USER_CANCELED = -2147219624, // // Summary: // Windows file sharing has been configured so that you will connect to the remote // computer using a different user name. This is incompatible with remote debugging. // Please see Help for assistance. E_REMOTE_CREDENTIALS_PROHIBITED = -2147219623, // // Summary: // Windows Firewall does not currently allow exceptions. Use Control Panel to change // the Windows Firewall settings so that exceptions are allowed. E_FIREWALL_NO_EXCEPTIONS = -2147219622, // // Summary: // Cannot add an application to the Windows Firewall exception list. Use the Control // Panel to manually configure the Windows Firewall. E_FIREWALL_CANNOT_OPEN_APPLICATION = -2147219621, // // Summary: // Cannot add a port to the Windows Firewall exception list. Use the Control Panel // to manually configure the Windows Firewall. E_FIREWALL_CANNOT_OPEN_PORT = -2147219620, // // Summary: // Cannot add 'File and Printer Sharing' to the Windows Firewall exception list. // Use the Control Panel to manually configure the Windows Firewall. E_FIREWALL_CANNOT_OPEN_FILE_SHARING = -2147219619, // // Summary: // Remote debugging is not supported. E_REMOTE_DEBUGGING_UNSUPPORTED = -2147219618, E_REMOTE_BAD_MSDBG2 = -2147219617, E_ATTACH_USER_CANCELED = -2147219616, // // Summary: // Maximum packet length exceeded. If the problem continues, reduce the number of // network host names or network addresses that are assigned to the computer running // Visual Studio computer or to the target computer. E_REMOTE_PACKET_TOO_BIG = -2147219615, // // Summary: // The target process is running a version of the Microsoft .NET Framework newer // than this version of Visual Studio. Visual Studio cannot debug this process. E_UNSUPPORTED_FUTURE_CLR_VERSION = -2147219614, // // Summary: // This version of Visual Studio does not support debugging code that uses Microsoft // .NET Framework v1.0. Use Visual Studio 2008 or earlier to debug this process. E_UNSUPPORTED_CLR_V1 = -2147219613, // // Summary: // Mixed-mode debugging of IA64 processes is not supported. E_INTEROP_IA64 = -2147219612, // // Summary: // See help for common configuration errors. Running the web page outside of the // debugger may provide further information. E_HTTP_GENERAL = -2147219611, // // Summary: // IDebugCoreServer* implementation does not have a connection to the remote computer. // This can occur in T-SQL debugging when there is no remote debugging monitor. E_REMOTE_NO_CONNECTION = -2147219610, // // Summary: // The specified remote debugging proxy server name is invalid. E_REMOTE_INVALID_PROXY_SERVER_NAME = -2147219609, // // Summary: // Operation is not permitted on IDebugCoreServer* implementation which has a weak // connection to the remote msvsmon instance. Weak connections are used when no // process is being debugged. E_REMOTE_WEAK_CONNECTION = -2147219608, // // Summary: // Remote program providers are no longer supported before debugging begins (ex: // process enumeration). E_REMOTE_PROGRAM_PROVIDERS_UNSUPPORTED = -2147219607, // // Summary: // Connection request was rejected by the remote debugger. Ensure that the remote // debugger is running in 'No Authentication' mode. E_REMOTE_REJECTED_NO_AUTH_REQUEST = -2147219606, // // Summary: // Connection request was rejected by the remote debugger. Ensure that the remote // debugger is running in 'Windows Authentication' mode. E_REMOTE_REJECTED_WIN_AUTH_REQUEST = -2147219605, // // Summary: // The debugger was unable to create a localhost TCP/IP connection, which is required // for 64-bit debugging. E_PSEUDOREMOTE_NO_LOCALHOST_TCPIP_CONNECTION = -2147219604, // // Summary: // This operation requires the Windows Web Services API to be installed, and it // is not currently installed on this computer. E_REMOTE_WWS_NOT_INSTALLED = -2147219603, // // Summary: // This operation requires the Windows Web Services API to be installed, and it // is not currently installed on this computer. To install Windows Web Services, // please restart Visual Studio as an administrator on this computer. E_REMOTE_WWS_INSTALL_REQUIRES_ADMIN = -2147219602, // // Summary: // The expression has not yet been translated to native machine code. E_FUNCTION_NOT_JITTED = -2147219456, E_NO_CODE_CONTEXT = -2147219455, // // Summary: // A Microsoft .NET Framework component, diasymreader.dll, is not correctly installed. // Please repair your Microsoft .NET Framework installation via 'Add or Remove Programs' // in Control Panel. E_BAD_CLR_DIASYMREADER = -2147219454, // // Summary: // Unable to load the CLR. If a CLR version was specified for debugging, check that // it was valid and installed on the machine. If the problem persists, please repair // your Microsoft .NET Framework installation via 'Programs and Features' in Control // Panel. E_CLR_SHIM_ERROR = -2147219453, // // Summary: // Unable to map the debug start page URL to a machine name. E_AUTOATTACH_WEBSERVER_NOT_FOUND = -2147219199, E_DBGEXTENSION_NOT_FOUND = -2147219184, E_DBGEXTENSION_FUNCTION_NOT_FOUND = -2147219183, E_DBGEXTENSION_FAULTED = -2147219182, E_DBGEXTENSION_RESULT_INVALID = -2147219181, E_PROGRAM_IN_RUNMODE = -2147219180, // // Summary: // The remote procedure could not be debugged. This usually indicates that debugging // has not been enabled on the server. See help for more information. E_CAUSALITY_NO_SERVER_RESPONSE = -2147219168, // // Summary: // Please install the Visual Studio Remote Debugger on the server to enable this // functionality. E_CAUSALITY_REMOTE_NOT_REGISTERED = -2147219167, // // Summary: // The debugger failed to stop in the server process. E_CAUSALITY_BREAKPOINT_NOT_HIT = -2147219166, // // Summary: // Unable to determine a stopping location. Verify symbols are loaded. E_CAUSALITY_BREAKPOINT_BIND_ERROR = -2147219165, // // Summary: // Debugging this project is disabled. Debugging can be re-enabled from 'Start Options' // under project properties. E_CAUSALITY_PROJECT_DISABLED = -2147219164, // // Summary: // Unable to attach the debugger to TSQL code. E_NO_ATTACH_WHILE_DDD = -2147218944, // // Summary: // Click Help for more information. E_SQLLE_ACCESSDENIED = -2147218943, // // Summary: // Click Help for more information. E_SQL_SP_ENABLE_PERMISSION_DENIED = -2147218942, // // Summary: // Click Help for more information. E_SQL_DEBUGGING_NOT_ENABLED_ON_SERVER = -2147218941, // // Summary: // Click Help for more information. E_SQL_CANT_FIND_SSDEBUGPS_ON_CLIENT = -2147218940, // // Summary: // Click Help for more information. E_SQL_EXECUTED_BUT_NOT_DEBUGGED = -2147218939, // // Summary: // Click Help for more information. E_SQL_VDT_INIT_RETURNED_SQL_ERROR = -2147218938, E_ATTACH_FAILED_ABORT_SILENTLY = -2147218937, // // Summary: // Click Help for more information. E_SQL_REGISTER_FAILED = -2147218936, E_DE_NOT_SUPPORTED_PRE_8_0 = -2147218688, E_PROGRAM_DESTROY_PENDING = -2147218687, // // Summary: // The operation isn't supported for the Common Language Runtime version used by // the process being debugged. E_MANAGED_FEATURE_NOTSUPPORTED = -2147218515, // // Summary: // The Visual Studio Remote Debugger does not support this edition of Windows. E_OS_PERSONAL = -2147218432, // // Summary: // Source server support is disabled because the assembly is partially trusted. E_SOURCE_SERVER_DISABLE_PARTIAL_TRUST = -2147218431, // // Summary: // Operation is not supported on the platform of the target computer/device. E_REMOTE_UNSUPPORTED_OPERATION_ON_PLATFORM = -2147218430, // // Summary: // Unable to load Visual Studio debugger component (vsdebugeng.dll). If this problem // persists, repair your installation via 'Add or Remove Programs' in Control Panel. E_LOAD_VSDEBUGENG_FAILED = -2147218416, // // Summary: // Unable to initialize Visual Studio debugger component (vsdebugeng.dll). If this // problem persists, repair your installation via 'Add or Remove Programs' in Control // Panel. E_LOAD_VSDEBUGENG_IMPORTS_FAILED = -2147218415, // // Summary: // Unable to initialize Visual Studio debugger due to a configuration error. If // this problem persists, repair your installation via 'Add or Remove Programs' // in Control Panel. E_LOAD_VSDEBUGENG_CONFIG_ERROR = -2147218414, // // Summary: // Failed to launch minidump. The minidump file is corrupt. E_CORRUPT_MINIDUMP = -2147218413, // // Summary: // Unable to load a Visual Studio component (VSDebugScriptAgent110.dll). If the // problem persists, repair your installation via 'Add or Remove Programs' in Control // Panel. E_LOAD_SCRIPT_AGENT_LOCAL_FAILURE = -2147218412, // // Summary: // Remote script debugging requires that the remote debugger is registered on the // target computer. Run the Visual Studio Remote Debugger setup (rdbgsetup_<processor>.exe) // on the target computer. E_LOAD_SCRIPT_AGENT_REMOTE_FAILURE = -2147218410, // // Summary: // The debugger was unable to find the registration for the target application. // If the problem persists, try uninstalling and then reinstalling this application. E_APPX_REGISTRATION_NOT_FOUND = -2147218409, // // Summary: // Unable to find a Visual Studio component (VsDebugLaunchNotify.exe). For remote // debugging, this file must be present on the target computer. If the problem persists, // repair your installation via 'Add or Remove Programs' in Control Panel. E_VSDEBUGLAUNCHNOTIFY_NOT_INSTALLED = -2147218408, // // Summary: // Windows 8 build# 8017 or higher is required to debug Windows Store apps. E_WIN8_TOO_OLD = -2147218404, E_THREAD_NOT_FOUND = -2147218175, // // Summary: // Cannot auto-attach to the SQL Server, possibly because the firewall is configured // incorrectly or auto-attach is forbidden by the operating system. E_CANNOT_AUTOATTACH_TO_SQLSERVER = -2147218174, E_OBJECT_OUT_OF_SYNC = -2147218173, E_PROCESS_ALREADY_CONTINUED = -2147218172, // // Summary: // Debugging multiple GPU processes is not supported. E_CANNOT_DEBUG_MULTI_GPU_PROCS = -2147218171, // // Summary: // No available devices supported by the selected debug engine. Please select a // different engine. E_GPU_ADAPTOR_NOT_FOUND = -2147218170, // // Summary: // A Microsoft Windows component is not correctly registered. Please ensure that // the Desktop Experience is enabled in Server Manager -> Manage -> Add Server Roles // and Features. E_WINDOWS_GRAPHICAL_SHELL_UNINSTALLED_ERROR = -2147218169, // // Summary: // Windows 8 or higher was required for GPU debugging on the software emulator. // For the most up-to-date information, please visit the link below. http://go.microsoft.com/fwlink/p/?LinkId=330081 E_GPU_DEBUG_NOT_SUPPORTED_PRE_DX_11_1 = -2147218168, // // Summary: // There is a configuration issue with the selected Debugging Accelerator Type. // For information on specific Accelerator providers, visit http://go.microsoft.com/fwlink/p/?LinkId=323500 E_GPU_DEBUG_CONFIG_ISSUE = -2147218167, // // Summary: // Local debugging is not supported for the selected Debugging Accelerator Type. // Use Remote Windows Debugger instead or change the Debugging Accelerator Type E_GPU_LOCAL_DEBUGGING_ERROR = -2147218166, // // Summary: // The debug driver for the selected Debugging Accelerator Type is not installed // on the target machine. For more information, visit http://go.microsoft.com/fwlink/p/?LinkId=323500 E_GPU_LOAD_VSD3D_FAILURE = -2147218165, // // Summary: // Timeout Detection and Recovery (TDR) must be disabled at the remote site. For // more information search for 'TdrLevel' in MSDN or visit the link below. http://go.microsoft.com/fwlink/p/?LinkId=323500 E_GPU_TDR_ENABLED_FAILURE = -2147218164, // // Summary: // Remote debugger does not support mixed (managed and native) debugger type. E_CANNOT_REMOTE_DEBUG_MIXED = -2147218163, // // Summary: // Background Task activation failed Please see Help for further information. E_BG_TASK_ACTIVATION_FAILED = -2147218162, // // Summary: // This version of the Visual Studio Remote Debugger does not support this operation. // Please upgrade to the latest version. http://go.microsoft.com/fwlink/p/?LinkId=219549 E_REMOTE_VERSION = -2147218161, // // Summary: // Unable to load a Visual Studio component (symbollocator.resources.dll). If the // problem persists, repair your installation via 'Add or Remove Programs' in Control // Panel. E_SYMBOL_LOCATOR_INSTALL_ERROR = -2147218160, // // Summary: // The format of the PE module is invalid. E_INVALID_PE_FORMAT = -2147218159, // // Summary: // This dump is already being debugged. E_DUMP_ALREADY_LAUNCHED = -2147218158, // // Summary: // The next statement cannot be set because the current assembly is optimized. E_CANNOT_SET_NEXT_STATEMENT_IN_OPTIMIZED_CODE = -2147218157, // // Summary: // Debugging of ARM minidumps requires Windows 8 or above. E_ARMDUMP_NOT_SUPPORTED_PRE_WIN8 = -2147218156, // // Summary: // Cannot detach while process termination is in progress. E_CANNOT_DETACH_WHILE_TERMINATE_IN_PROGRESS = -2147218155, // // Summary: // A required Microsoft Windows component, wldp.dll could not be found on the target // device. E_WLDP_NOT_FOUND = -2147218154, // // Summary: // The target device does not allow debugging this process. E_DEBUGGING_BLOCKED_ON_TARGET = -2147218153, // // Summary: // Unable to debug .NET Native code. Install the Microsoft .NET Native Developer // SDK. Alternatively debug with native code type. E_DOTNETNATIVE_SDK_NOT_INSTALLED = -2147218152, // // Summary: // The operation was canceled. COR_E_OPERATIONCANCELED = -2146233029, // // Summary: // A component dll failed to load. Try to restart this application. If failures // continue, try disabling any installed add-ins or repair your installation. E_XAPI_COMPONENT_LOAD_FAILURE = -1898053632, // // Summary: // Xapi has not been initialized on this thread. Call ComponentManager.InitializeThread. E_XAPI_NOT_INITIALIZED = -1898053631, // // Summary: // Xapi has already been initialized on this thread. E_XAPI_ALREADY_INITIALIZED = -1898053630, // // Summary: // Xapi event thread aborted unexpectedly. E_XAPI_THREAD_ABORTED = -1898053629, // // Summary: // Component failed a call to QueryInterface. QueryInterface implementation or component // configuration is incorrect. E_XAPI_BAD_QUERY_INTERFACE = -1898053628, // // Summary: // Object requested which is not available at the caller's component level. E_XAPI_UNAVAILABLE_OBJECT = -1898053627, // // Summary: // Failed to process configuration file. Try to restart this application. If failures // continue, try to repair your installation. E_XAPI_BAD_CONFIG = -1898053626, // // Summary: // Failed to initialize managed/native marshalling system. Try to restart this application. // If failures continue, try to repair your installation. E_XAPI_MANAGED_DISPATCHER_CONNECT_FAILURE = -1898053625, // // Summary: // This operation may only be preformed while processing the object's 'Create' event. E_XAPI_DURING_CREATE_EVENT_REQUIRED = -1898053624, // // Summary: // This operation may only be preformed by the component which created the object. E_XAPI_CREATOR_REQUIRED = -1898053623, // // Summary: // The work item cannot be appended to the work list because it is already complete. E_XAPI_WORK_LIST_COMPLETE = -1898053622, // // Summary: // 'Execute' may not be called on a work list which has already started. E_XAPI_WORKLIST_ALREADY_STARTED = -1898053621, // // Summary: // The interface implementation released the completion routine without calling // it. E_XAPI_COMPLETION_ROUTINE_RELEASED = -1898053620, // // Summary: // Operation is not supported on this thread. E_XAPI_WRONG_THREAD = -1898053619, // // Summary: // No component with the given component id could be found in the configuration // store. E_XAPI_COMPONENTID_NOT_FOUND = -1898053618, // // Summary: // Call was attempted to a remote connection from a server-side component (component // level > 100000). This is not allowed. E_XAPI_WRONG_CONNECTION_OBJECT = -1898053617, // // Summary: // Destination of this call is on a remote connection and this method doesn't support // remoting. E_XAPI_METHOD_NOT_REMOTED = -1898053616, // // Summary: // The network connection to the Visual Studio Remote Debugger was lost. E_XAPI_REMOTE_DISCONNECTED = -1898053615, // // Summary: // The network connection to the Visual Studio Remote Debugger has been closed. E_XAPI_REMOTE_CLOSED = -1898053614, // // Summary: // A protocol compatibility error occurred between Visual Studio and the Remote // Debugger. Please ensure that the Visual Studio and Remote debugger versions match. E_XAPI_INCOMPATIBLE_PROTOCOL = -1898053613, // // Summary: // Maximum allocation size exceeded while processing a remoting message. E_XAPI_MAX_PACKET_EXCEEDED = -1898053612, // // Summary: // An object already exists with the same key value. E_XAPI_OBJECT_ALREADY_EXISTS = -1898053611, // // Summary: // An object cannot be found with the given key value. E_XAPI_OBJECT_NOT_FOUND = -1898053610, // // Summary: // A data item already exists with the same key value. E_XAPI_DATA_ITEM_ALREADY_EXISTS = -1898053609, // // Summary: // A data item cannot be for this component found with the given data item ID. E_XAPI_DATA_ITEM_NOT_FOUND = -1898053608, // // Summary: // Interface implementation failed to provide a required out param. E_XAPI_NULL_OUT_PARAM = -1898053607, // // Summary: // Strong name signature validation error while trying to load the managed dispatcher E_XAPI_MANAGED_DISPATCHER_SIGNATURE_ERROR = -1898053600, // // Summary: // Method may only be called by components which load in the IDE process (component // level > 100000). E_XAPI_CLIENT_ONLY_METHOD = -1898053599, // // Summary: // Method may only be called by components which load in the remote debugger process // (component level < 100000). E_XAPI_SERVER_ONLY_METHOD = -1898053598, // // Summary: // A component dll could not be found. If failures continue, try disabling any installed // add-ins or repairing your installation. E_XAPI_COMPONENT_DLL_NOT_FOUND = -1898053597, // // Summary: // Operation requires the remote debugger be updated to a newer version. E_XAPI_REMOTE_NEW_VER_REQUIRED = -1898053596, // // Summary: // Symbols are not loaded for the target dll. E_SYMBOLS_NOT_LOADED = -1842151424, // // Summary: // Symbols for the target dll do not contain source information. E_SYMBOLS_STRIPPED = -1842151423, // // Summary: // Breakpoint could not be written at the specified instruction address. E_BP_INVALID_ADDRESS = -1842151422, // // Summary: // Breakpoints cannot be set in optimized code when the debugger option 'Just My // Code' is enabled. E_BP_IN_OPTIMIZED_CODE = -1842151420, // // Summary: // The Common Language Runtime was unable to set the breakpoint. E_BP_CLR_ERROR = -1842151418, // // Summary: // Cannot set breakpoints in .NET Framework methods which are implemented in native // code (ex: 'extern' function). E_BP_CLR_EXTERN_FUNCTION = -1842151417, // // Summary: // Cannot set breakpoint, target module is currently unloaded. E_BP_MODULE_UNLOADED = -1842151416, // // Summary: // Stopping events cannot be sent. See stopping event processing documentation for // more information. E_STOPPING_EVENT_REJECTED = -1842151415, // // Summary: // This operation is not permitted because the target process is already stopped. E_TARGET_ALREADY_STOPPED = -1842151414, // // Summary: // This operation is not permitted because the target process is not stopped. E_TARGET_NOT_STOPPED = -1842151413, // // Summary: // This operation is not allowed on this thread. E_WRONG_THREAD = -1842151412, // // Summary: // This operation is not allowed at this time. E_WRONG_TIME = -1842151411, // // Summary: // The caller is not allowed to request this operation. This operation must be requested // by a different component. E_WRONG_COMPONENT = -1842151410, // // Summary: // Operation is only permitted on the latest version of an edited method. E_WRONG_METHOD_VERSION = -1842151409, // // Summary: // A memory read or write operation failed because the specified memory address // is not currently valid. E_INVALID_MEMORY_ADDRESS = -1842151408, // // Summary: // No source information is available for this instruction. E_INSTRUCTION_NO_SOURCE = -1842151407, // // Summary: // Failed to load localizable resource from vsdebugeng.impl.resources.dll. If this // problem persists, please repair your Visual Studio installation via 'Add or Remove // Programs' in Control Panel. E_VSDEBUGENG_RESOURCE_LOAD_FAILURE = -1842151406, // // Summary: // DkmVariant is of a form that marshalling is not supported. Marshalling is supported // for primitives types, strings, and safe arrays of primitives. E_UNMARSHALLABLE_VARIANT = -1842151405, // // Summary: // An incorrect version of vsdebugeng.dll was loaded into Visual Studio. Please // repair your Visual Studio installation. E_VSDEBUGENG_DEPLOYMENT_ERROR = -1842151404, // // Summary: // The remote debugger was unable to initialize Microsoft Windows Web Services (webservices.dll). // If the problem continues, try reinstalling the Windows Web Services redistributable. // This redistributable can be found under the 'Remote Debugger\Common Resources\Windows // Updates' folder. E_WEBSERVICES_LOAD_FAILURE = -1842151403, // // Summary: // Visual Studio encountered an error while loading a Windows component (Global // Interface Table). If the problem persists, this may be an indication of operating // system corruption, and Windows may need to be reinstalled. E_GLOBAL_INTERFACE_POINTER_FAILURE = -1842151402, // // Summary: // Windows authentication was unable to establish a secure connection to the remote // computer. E_REMOTE_AUTHENTICATION_ERROR = -1842151401, // // Summary: // The Remote Debugger was unable to locate a resource dll (vsdebugeng.impl.resources.dll). // Please ensure that the complete remote debugger folder was copied or installed // on the target computer. E_CANNOT_FIND_REMOTE_RESOURCES = -1842151400, // // Summary: // The hardware does not support monitoring the requested number of bytes. E_INVALID_DATABP_SIZE = -1842151392, // // Summary: // The maximum number of data breakpoints have already been set. E_INVALID_DATABP_ALLREGSUSED = -1842151391, // // Summary: // Breakpoints cannot be set while debugging a minidump. E_DUMPS_DO_NOT_SUPPORT_BREAKPOINTS = -1842151390, // // Summary: // The minidump is from an ARM-based computer and can only be debugged on an ARM // computer. E_DUMP_ARM_ARCHITECTURE = -1842151389, // // Summary: // The minidump is from an unknown processor, and cannot be debugged with this version // of Visual Studio. E_DUMP_UNKNOWN_ARCHITECTURE = -1842151388, // // Summary: // The shell failed to find a checksum for this file. E_NO_CHECKSUM = -1842151387, // // Summary: // On x64, context control must be included in a SetThreadContext E_CONTEXT_CONTROL_REQUIRED = -1842151386, // // Summary: // The size of the buffer does not match the size of the register. E_INVALID_REGISTER_SIZE = -1842151385, // // Summary: // The requested register was not found in the stack frame's unwound register collection. E_REGISTER_NOT_FOUND = -1842151384, // // Summary: // Cannot set a read-only register. E_REGISTER_READONLY = -1842151383, // // Summary: // Cannot set a register in a frame that is not the top of the stack. E_REG_NOT_TOP_STACK = -1842151376, // // Summary: // String could not be read within the specified maximum number of characters. E_STRING_TOO_LONG = -1842151375, // // Summary: // The memory region does not meet the requested protection flags. E_INVALID_MEMORY_PROTECT = -1842151374, // // Summary: // Instruction is invalid or unknown to the disassembler. E_UNKNOWN_CPU_INSTRUCTION = -1842151373, // // Summary: // An invalid runtime was specified for this operation. E_INVALID_RUNTIME = -1842151372, // // Summary: // Variable is optimized away. E_VARIABLE_OPTIMIZED_AWAY = -1842151371, // // Summary: // The text span is not currently loaded in the specified script document. E_TEXT_SPAN_NOT_LOADED = -1842151370, // // Summary: // This location could not be mapped to client side script. E_SCRIPT_SPAN_MAPPING_FAILED = -1842151369, // // Summary: // The file requested must be less than 100 megabytes in size E_DEPLOY_FILE_TOO_LARGE = -1842151368, // // Summary: // The file path requested could not be written to as it is invalid. Ensure the // path does not contain a file where a directory is expected. E_DEPLOY_FILE_PATH_INVALID = -1842151367, // // Summary: // Script debugging is not enabled for WWAHost.exe. E_SCRIPT_DEBUGGING_DISABLED_WWAHOST_ATTACH_FAILED = -1842151360, // // Summary: // The file path requested for deletion does not exist. E_DEPLOY_FILE_NOT_EXIST = -1842151359, // // Summary: // A command is already executing, only one may execute at a time. Please wait for // the executable to exit, or abort the command. E_EXECUTE_COMMAND_IN_PROGRESS = -1842151358, // // Summary: // The specified file path is a relative or unknown path format. File paths must // be fully qualified. E_INVALID_FULL_PATH = -1842151357, // // Summary: // Windows Store app debugging is not possible when the remote debugger is running // as a service. Run the Remote Debugger Configuration Wizard on the target computer, // and uncheck the option to start the remote debugger service. Then start the Visual // Studio Remote Debugging Monitor application. E_CANNOT_DEBUG_APP_PACKAGE_IN_RDBSERVICE = -1842151356, // // Summary: // Applications cannot be launched under the debugger when the remote debugger is // running as a service. Run the Remote Debugger Configuration Wizard on the target // computer, and uncheck the option to start the remote debugger service. Then start // the Visual Studio Remote Debugging Monitor application. E_CANNOT_LAUNCH_IN_RDBSERVICE = -1842151355, // // Summary: // The AD7 AL Causality bridge has already been initialized. E_CAUSALITY_BRIDGE_ALREADY_INITIALIZED = -1842151354, // // Summary: // App Packages may only be shutdown as part of a Visual Studio build operation. E_DEPLOY_APPX_SHUTDOWN_WRONG_TIME = -1842151353, // // Summary: // A Microsoft Windows component is not correctly registered. If the problem persists, // try repairing your Windows installation, or reinstalling Windows. E_WINDOWS_REG_ERROR = -1842151352, // // Summary: // The application never reached a suspended state. E_APP_PACKAGE_NEVER_SUSPENDED = -1842151351, // // Summary: // A different version of this script file has been loaded by the debugged process. // The script file may need to be reloaded. E_SCRIPT_FILE_DIFFERENT_CONTENT = -1842151350, // // Summary: // No stack frame was found. E_NO_FRAME = -1842151349, // // Summary: // Operation is not supported while interop debugging. E_NOT_SUPPORTED_INTEROP = -1842151348, // // Summary: // The selected accelerator does not support the run current tile to cursor operation. E_GPU_BARRIER_BREAKPOINT_NOT_SUPPORTED = -1842151347, // // Summary: // Data breakpoints are not supported on this platform. E_DATABPS_NOTSUPPORTED = -1842151346, // // Summary: // The debugger failed to attach to the process requested in the DkmDebugProcessRequest. E_DEBUG_PROCESS_REQUEST_FAILED = -1842151345, // // Summary: // An invalid NativeOffset or CPUInstructionPart value was used with a DkmClrInstructionAddress // or DkmClrInstructionSymbol E_INVALID_CLR_INSTRUCTION_NATIVE_OFFSET = -1842151339, // // Summary: // Managed heap is not in a state that can be enumerated E_MANAGED_HEAP_NOT_ENUMERABLE = -1842151338, // // Summary: // This operation is unavailable when mixed mode debugging with Script E_OPERATION_UNAVAILABLE_SCRIPT_INTEROP = -1842151337, // // Summary: // This operation is unavailable when debugging native-compiled .NET code. E_OPERATION_UNAVAILABLE_CLR_NC = -1842151336, // // Summary: // Symbol file contains data which is in an unexpected format. E_BAD_SYMBOL_DATA = -1842151335, // // Summary: // Dynamically enabling script debugging in the target process failed. E_ENABLE_SCRIPT_DEBUGGING_FAILED = -1842151334, // // Summary: // Expression evaluation is not available in async call stack frames. E_SCRIPT_ASYNC_FRAME_EE_UNAVAILABLE = -1842151333, // // Summary: // This dump does not contain any thread information or the thread information is // corrupt. Visual Studio does not support debugging of dumps without valid thread // information. E_DUMP_NO_THREADS = -1842151332, // // Summary: // DkmLoadCompleteEventDeferral.Add cannot be called after the load complete event // has been sent. E_LOAD_COMPLETE_ALREADY_SENT = -1842151331, // // Summary: // DkmLoadCompleteEventDeferral was not present in the list during a call to DkmLoadCompleteEventDeferral.Remove. E_LOAD_COMPLETE_DEFERRAL_NOT_FOUND = -1842151330, // // Summary: // The buffer size specified was too large to marshal over the remote boundary. E_MARSHALLING_SIZE_TOO_LARGE = -1842151329, // // Summary: // Emulation of iterator for results view failed. This is typically caused when // the iterator calls into native code. E_CANNOT_EMULATE_RESULTS_VIEW = -1842151328, // // Summary: // Managed heap enumeration is attempted on running target. This is typically caused // by continuing the process while heap enumeration is in progress. E_MANAGED_HEAP_ENUMERATION_TARGET_NOT_STOPPED = -1842151327 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\Concord\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger { // // Summary: // Defines the HRESULT codes used by this API. public enum DkmExceptionCode { // // Summary: // Unspecified error. E_FAIL = -2147467259, // // Summary: // A debugger is already attached. E_ATTACH_DEBUGGER_ALREADY_ATTACHED = -2147221503, // // Summary: // The process does not have sufficient privileges to be debugged. E_ATTACH_DEBUGGEE_PROCESS_SECURITY_VIOLATION = -2147221502, // // Summary: // The desktop cannot be debugged. E_ATTACH_CANNOT_ATTACH_TO_DESKTOP = -2147221501, // // Summary: // Unmanaged debugging is not available. E_LAUNCH_NO_INTEROP = -2147221499, // // Summary: // Debugging isn't possible due to an incompatibility within the CLR implementation. E_LAUNCH_DEBUGGING_NOT_POSSIBLE = -2147221498, // // Summary: // Visual Studio cannot debug managed applications because a kernel debugger is // enabled on the system. Please see Help for further information. E_LAUNCH_KERNEL_DEBUGGER_ENABLED = -2147221497, // // Summary: // Visual Studio cannot debug managed applications because a kernel debugger is // present on the system. Please see Help for further information. E_LAUNCH_KERNEL_DEBUGGER_PRESENT = -2147221496, // // Summary: // The debugger does not support debugging managed and native code at the same time // on the platform of the target computer/device. Configure the debugger to debug // only native code or only managed code. E_INTEROP_NOT_SUPPORTED = -2147221495, // // Summary: // The maximum number of processes is already being debugged. E_TOO_MANY_PROCESSES = -2147221494, // // Summary: // Script debugging of your application is disabled in Internet Explorer. To enable // script debugging in Internet Explorer, choose Internet Options from the Tools // menu and navigate to the Advanced tab. Under the Browsing category, clear the // 'Disable Script Debugging (Internet Explorer)' checkbox, then restart Internet // Explorer. E_MSHTML_SCRIPT_DEBUGGING_DISABLED = -2147221493, // // Summary: // The correct version of pdm.dll is not registered. Repair your Visual Studio installation, // or run 'regsvr32.exe "%CommonProgramFiles%\Microsoft Shared\VS7Debug\pdm.dll"'. E_SCRIPT_PDM_NOT_REGISTERED = -2147221492, // // Summary: // The .NET debugger has not been installed properly. The most probable cause is // that mscordbi.dll is not properly registered. Click Help for more information // on how to repair the .NET debugger. E_DE_CLR_DBG_SERVICES_NOT_INSTALLED = -2147221491, // // Summary: // There is no managed code running in the process. In order to attach to a process // with the .NET debugger, managed code must be running in the process before attaching. E_ATTACH_NO_CLR_PROGRAMS = -2147221490, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor has been closed on the remote // machine. E_REMOTE_SERVER_CLOSED = -2147221488, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer does // not support debugging code running in the Common Language Runtime. E_CLR_NOT_SUPPORTED = -2147221482, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer does // not support debugging code running in the Common Language Runtime on a 64-bit // computer. E_64BIT_CLR_NOT_SUPPORTED = -2147221481, // // Summary: // Cannot debug minidumps and processes at the same time. E_CANNOT_MIX_MINDUMP_DEBUGGING = -2147221480, E_DEBUG_ENGINE_NOT_REGISTERED = -2147221479, // // Summary: // This application has failed to start because the application configuration is // incorrect. Review the manifest file for possible errors. Reinstalling the application // may fix this problem. For more details, please see the application event log. E_LAUNCH_SXS_ERROR = -2147221478, // // Summary: // Failed to initialize msdbg2.dll for script debugging. If this problem persists, // use 'Add or Remove Programs' in Control Panel to repair your Visual Studio installation. E_FAILED_TO_INITIALIZE_SCRIPT_PROXY = -2147221477, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) does not appear // to be running on the remote computer. This may be because a firewall is preventing // communication to the remote computer. Please see Help for assistance on configuring // remote debugging. E_REMOTE_SERVER_DOES_NOT_EXIST = -2147221472, // // Summary: // Access is denied. Can not connect to Microsoft Visual Studio Remote Debugging // Monitor on the remote computer. E_REMOTE_SERVER_ACCESS_DENIED = -2147221471, // // Summary: // The debugger cannot connect to the remote computer. The debugger was unable to // resolve the specified computer name. E_REMOTE_SERVER_MACHINE_DOES_NOT_EXIST = -2147221470, // // Summary: // The debugger is not properly installed. Run setup to install or repair the debugger. E_DEBUGGER_NOT_REGISTERED_PROPERLY = -2147221469, // // Summary: // Access is denied. This seems to be because the 'Network access: Sharing and security // model for local accounts' security policy does not allow users to authenticate // as themselves. Please use the 'Local Security Settings' administration tool on // the local computer to configure this option. E_FORCE_GUEST_MODE_ENABLED = -2147221468, E_GET_IWAM_USER_FAILURE = -2147221467, // // Summary: // The specified remote server name is not valid. E_REMOTE_SERVER_INVALID_NAME = -2147221466, // // Summary: // Microsoft Visual Studio Debugging Monitor (MSVSMON.EXE) failed to start. If this // problem persists, please repair your Visual Studio installation via 'Add or Remove // Programs' in Control Panel. E_AUTO_LAUNCH_EXEC_FAILURE = -2147221464, // // Summary: // Microsoft Visual Studio Remote Debugging Monitor (MSVSMON.EXE) is not running // under your user account and MSVSMON could not be automatically started. MSVSMON // must be manually started, or the Visual Studio remote debugging components must // be installed on the remote computer. Please see Help for assistance. E_REMOTE_COMPONENTS_NOT_REGISTERED = -2147221461, // // Summary: // A DCOM error occurred trying to contact the remote computer. Access is denied. // It may be possible to avoid this error by changing your settings to debug only // native code or only managed code. E_DCOM_ACCESS_DENIED = -2147221460, // // Summary: // Debugging using the Default transport is not possible because the remote machine // has 'Share-level access control' enabled. To enable debugging on the remote machine, // go to Control Panel -> Network -> Access control, and set Access control to be // 'User-level access control'. E_SHARE_LEVEL_ACCESS_CONTROL_ENABLED = -2147221459, // // Summary: // Logon failure: unknown user name or bad password. See help for more information. E_WORKGROUP_REMOTE_LOGON_FAILURE = -2147221458, // // Summary: // Windows authentication is disabled in the Microsoft Visual Studio Remote Debugging // Monitor (MSVSMON). To connect, choose one of the following options. 1. Enable // Windows authentication in MSVSMON 2. Reconfigure your project to disable Windows // authentication 3. Use the 'Remote (native with no authentication)' transport // in the 'Attach to Process' dialog E_WINAUTH_CONNECT_NOT_SUPPORTED = -2147221457, // // Summary: // A previous expression evaluation is still in progress. E_EVALUATE_BUSY_WITH_EVALUATION = -2147221456, // // Summary: // The expression evaluation took too long. E_EVALUATE_TIMEOUT = -2147221455, // // Summary: // Mixed-mode debugging does not support Microsoft.NET Framework versions earlier // than 2.0. E_INTEROP_CLR_TOO_OLD = -2147221454, // // Summary: // Check for one of the following. 1. The application you are trying to debug uses // a version of the Microsoft .NET Framework that is not supported by the debugger. // 2. The debugger has made an incorrect assumption about the Microsoft .NET Framework // version your application is going to use. 3. The Microsoft .NET Framework version // specified by you for debugging is incorrect. Please see the Visual Studio .NET // debugger documentation for correctly specifying the Microsoft .NET Framework // version your application is going to use for debugging. E_CLR_INCOMPATIBLE_PROTOCOL = -2147221453, // // Summary: // Unable to attach because process is running in fiber mode. E_CLR_CANNOT_DEBUG_FIBER_PROCESS = -2147221452, // // Summary: // Visual Studio has insufficient privileges to debug this process. To debug this // process, Visual Studio must be run as an administrator. E_PROCESS_OBJECT_ACCESS_DENIED = -2147221451, // // Summary: // Visual Studio has insufficient privileges to inspect the process's identity. E_PROCESS_TOKEN_ACCESS_DENIED = -2147221450, // // Summary: // Visual Studio was unable to inspect the process's identity. This is most likely // due to service configuration on the computer running the process. E_PROCESS_TOKEN_ACCESS_DENIED_NO_TS = -2147221449, E_OPERATION_REQUIRES_ELEVATION = -2147221448, // // Summary: // Visual Studio has insufficient privileges to debug this process. To debug this // process, Visual Studio must be run as an administrator. E_ATTACH_REQUIRES_ELEVATION = -2147221447, E_MEMORY_NOTSUPPORTED = -2147221440, // // Summary: // The type of code you are currently debugging does not support disassembly. E_DISASM_NOTSUPPORTED = -2147221439, // // Summary: // The specified address does not exist in disassembly. E_DISASM_BADADDRESS = -2147221438, E_DISASM_NOTAVAILABLE = -2147221437, // // Summary: // The breakpoint has been deleted. E_BP_DELETED = -2147221408, // // Summary: // The process has been terminated. E_PROCESS_DESTROYED = -2147221392, E_PROCESS_DEBUGGER_IS_DEBUGGEE = -2147221391, // // Summary: // Terminating this process is not allowed. E_TERMINATE_FORBIDDEN = -2147221390, // // Summary: // The thread has terminated. E_THREAD_DESTROYED = -2147221387, // // Summary: // Cannot find port. Check the remote machine name. E_PORTSUPPLIER_NO_PORT = -2147221376, E_PORT_NO_REQUEST = -2147221360, E_COMPARE_CANNOT_COMPARE = -2147221344, E_JIT_INVALID_PID = -2147221327, E_JIT_VSJITDEBUGGER_NOT_REGISTERED = -2147221325, E_JIT_APPID_NOT_REGISTERED = -2147221324, E_JIT_RUNTIME_VERSION_UNSUPPORTED = -2147221322, E_SESSION_TERMINATE_DETACH_FAILED = -2147221310, E_SESSION_TERMINATE_FAILED = -2147221309, // // Summary: // Detach is not supported on Microsoft Windows 2000 for native code. E_DETACH_NO_PROXY = -2147221296, E_DETACH_TS_UNSUPPORTED = -2147221280, E_DETACH_IMPERSONATE_FAILURE = -2147221264, // // Summary: // This thread has called into a function that cannot be displayed. E_CANNOT_SET_NEXT_STATEMENT_ON_NONLEAF_FRAME = -2147221248, E_TARGET_FILE_MISMATCH = -2147221247, E_IMAGE_NOT_LOADED = -2147221246, E_FIBER_NOT_SUPPORTED = -2147221245, // // Summary: // The next statement cannot be set to another function. E_CANNOT_SETIP_TO_DIFFERENT_FUNCTION = -2147221244, // // Summary: // In order to Set Next Statement, right-click on the active frame in the Call Stack // window and select "Unwind To This Frame". E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = -2147221243, // // Summary: // The next statement cannot be changed until the current statement has completed. E_ENC_SETIP_REQUIRES_CONTINUE = -2147221241, // // Summary: // The next statement cannot be set from outside a finally block to within it. E_CANNOT_SET_NEXT_STATEMENT_INTO_FINALLY = -2147221240, // // Summary: // The next statement cannot be set from within a finally block to a statement outside // of it. E_CANNOT_SET_NEXT_STATEMENT_OUT_OF_FINALLY = -2147221239, // // Summary: // The next statement cannot be set from outside a catch block to within it. E_CANNOT_SET_NEXT_STATEMENT_INTO_CATCH = -2147221238, // // Summary: // The next statement cannot be changed at this time. E_CANNOT_SET_NEXT_STATEMENT_GENERAL = -2147221237, // // Summary: // The next statement cannot be set into or out of a catch filter. E_CANNOT_SET_NEXT_STATEMENT_INTO_OR_OUT_OF_FILTER = -2147221236, // // Summary: // This process is not currently executing the type of code that you selected to // debug. E_ASYNCBREAK_NO_PROGRAMS = -2147221232, // // Summary: // The debugger is still attaching to the process or the process is not currently // executing the type of code selected for debugging. E_ASYNCBREAK_DEBUGGEE_NOT_INITIALIZED = -2147221231, // // Summary: // The debugger is handling debug events or performing evaluations that do not allow // nested break state. Try again. E_ASYNCBREAK_UNABLE_TO_PROCESS = -2147221230, // // Summary: // The web server has been locked down and is blocking the DEBUG verb, which is // required to enable debugging. Please see Help for assistance. E_WEBDBG_DEBUG_VERB_BLOCKED = -2147221215, // // Summary: // ASP debugging is disabled because the ASP process is running as a user that does // not have debug permissions. Please see Help for assistance. E_ASP_USER_ACCESS_DENIED = -2147221211, // // Summary: // The remote debugging components are not registered or running on the web server. // Ensure the proper version of msvsmon is running on the remote computer. E_AUTO_ATTACH_NOT_REGISTERED = -2147221210, // // Summary: // An unexpected DCOM error occurred while trying to automatically attach to the // remote web server. Try manually attaching to the remote web server using the // 'Attach To Process' dialog. E_AUTO_ATTACH_DCOM_ERROR = -2147221209, // // Summary: // Expected failure from web server CoCreating debug verb CLSID E_AUTO_ATTACH_COCREATE_FAILURE = -2147221208, E_AUTO_ATTACH_CLASSNOTREG = -2147221207, // // Summary: // The current thread cannot continue while an expression is being evaluated on // another thread. E_CANNOT_CONTINUE_DURING_PENDING_EXPR_EVAL = -2147221200, E_REMOTE_REDIRECTION_UNSUPPORTED = -2147221195, // // Summary: // The specified working directory does not exist or is not a full path. E_INVALID_WORKING_DIRECTORY = -2147221194, // // Summary: // The application manifest has the uiAccess attribute set to 'true'. Running an // Accessibility application requires following the steps described in Help. E_LAUNCH_FAILED_WITH_ELEVATION = -2147221193, // // Summary: // This program requires additional permissions to start. To debug this program, // restart Visual Studio as an administrator. E_LAUNCH_ELEVATION_REQUIRED = -2147221192, // // Summary: // Cannot locate Microsoft Internet Explorer. E_CANNOT_FIND_INTERNET_EXPLORER = -2147221191, // // Summary: // The Visual Studio Remote Debugger (MSVSMON.EXE) has insufficient privileges to // debug this process. To debug this process, the remote debugger must be run as // an administrator. E_REMOTE_PROCESS_OBJECT_ACCESS_DENIED = -2147221190, // // Summary: // The Visual Studio Remote Debugger (MSVSMON.EXE) has insufficient privileges to // debug this process. To debug this process, launch the remote debugger using 'Run // as administrator'. If the remote debugger has been configured to run as a service, // ensure that it is running under an account that is a member of the Administrators // group. E_REMOTE_ATTACH_REQUIRES_ELEVATION = -2147221189, // // Summary: // This program requires additional permissions to start. To debug this program, // launch the Visual Studio Remote Debugger (MSVSMON.EXE) using 'Run as administrator'. E_REMOTE_LAUNCH_ELEVATION_REQUIRED = -2147221188, // // Summary: // The attempt to unwind the callstack failed. Unwinding is not possible in the // following scenarios: 1. Debugging was started via Just-In-Time debugging. 2. // An unwind is in progress. 3. A System.StackOverflowException or System.Threading.ThreadAbortException // exception has been thrown. E_EXCEPTION_CANNOT_BE_INTERCEPTED = -2147221184, // // Summary: // You can only unwind to the function that caused the exception. E_EXCEPTION_CANNOT_UNWIND_ABOVE_CALLBACK = -2147221183, // // Summary: // Unwinding from the current exception is not supported. E_INTERCEPT_CURRENT_EXCEPTION_NOT_SUPPORTED = -2147221182, // // Summary: // You cannot unwind from an unhandled exception while doing managed and native // code debugging at the same time. E_INTERCEPT_CANNOT_UNWIND_LASTCHANCE_INTEROP = -2147221181, E_JMC_CANNOT_SET_STATUS = -2147221179, // // Summary: // The process has been terminated. E_DESTROYED = -2147220991, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor is either not running on // the remote machine or is running in Windows authentication mode. E_REMOTE_NOMSVCMON = -2147220990, // // Summary: // The IP address for the remote machine is not valid. E_REMOTE_BADIPADDRESS = -2147220989, // // Summary: // The remote machine is not responding. E_REMOTE_MACHINEDOWN = -2147220988, // // Summary: // The remote machine name is not specified. E_REMOTE_MACHINEUNSPECIFIED = -2147220987, // // Summary: // Other programs cannot be debugged during the current mixed dump debugging session. E_CRASHDUMP_ACTIVE = -2147220986, // // Summary: // All of the threads are frozen. Use the Threads window to unfreeze at least one // thread before attempting to step or continue the process. E_ALL_THREADS_SUSPENDED = -2147220985, // // Summary: // The debugger transport DLL cannot be loaded. E_LOAD_DLL_TL = -2147220984, // // Summary: // mspdb110.dll cannot be loaded. E_LOAD_DLL_SH = -2147220983, // // Summary: // MSDIS170.dll cannot be loaded. E_LOAD_DLL_EM = -2147220982, // // Summary: // NatDbgEE.dll cannot be loaded. E_LOAD_DLL_EE = -2147220981, // // Summary: // NatDbgDM.dll cannot be loaded. E_LOAD_DLL_DM = -2147220980, // // Summary: // Old version of DBGHELP.DLL found, does not support minidumps. E_LOAD_DLL_MD = -2147220979, // // Summary: // Input or output cannot be redirected because the specified file is invalid. E_IOREDIR_BADFILE = -2147220978, // // Summary: // Input or output cannot be redirected because the syntax is incorrect. E_IOREDIR_BADSYNTAX = -2147220977, // // Summary: // The remote debugger is not an acceptable version. E_REMOTE_BADVERSION = -2147220976, // // Summary: // This operation is not supported when debugging dump files. E_CRASHDUMP_UNSUPPORTED = -2147220975, // // Summary: // The remote computer does not have a CLR version which is compatible with the // remote debugging components. To install a compatible CLR version, see the instructions // in the 'Remote Components Setup' page on the Visual Studio CD. E_REMOTE_BAD_CLR_VERSION = -2147220974, // // Summary: // The specified file is an unrecognized or unsupported binary format. E_UNSUPPORTED_BINARY = -2147220971, // // Summary: // The process has been soft broken. E_DEBUGGEE_BLOCKED = -2147220970, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer is // running as a different user. E_REMOTE_NOUSERMSVCMON = -2147220969, // // Summary: // Stepping to or from system code on a machine running Windows 95/Windows 98/Windows // ME is not allowed. E_STEP_WIN9xSYSCODE = -2147220968, E_INTEROP_ORPC_INIT = -2147220967, // // Summary: // The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) // cannot be used to debug 32-bit processes or 32-bit dumps. Please use the 32-bit // version instead. E_CANNOT_DEBUG_WIN32 = -2147220965, // // Summary: // The 32-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) // cannot be used to debug 64-bit processes or 64-bit dumps. Please use the 64-bit // version instead. E_CANNOT_DEBUG_WIN64 = -2147220964, // // Summary: // Mini-Dumps cannot be read on this system. Please use a Windows NT based system E_MINIDUMP_READ_WIN9X = -2147220963, // // Summary: // Attaching to a process in a different terminal server session is not supported // on this computer. Try remote debugging to the machine and running the Microsoft // Visual Studio Remote Debugging Monitor in the process's session. E_CROSS_TSSESSION_ATTACH = -2147220962, // // Summary: // A stepping breakpoint could not be set E_STEP_BP_SET_FAILED = -2147220961, // // Summary: // The debugger transport DLL being loaded has an incorrect version. E_LOAD_DLL_TL_INCORRECT_VERSION = -2147220960, // // Summary: // NatDbgDM.dll being loaded has an incorrect version. E_LOAD_DLL_DM_INCORRECT_VERSION = -2147220959, E_REMOTE_NOMSVCMON_PIPE = -2147220958, // // Summary: // msdia120.dll cannot be loaded. E_LOAD_DLL_DIA = -2147220957, // // Summary: // The dump file you opened is corrupted. E_DUMP_CORRUPTED = -2147220956, // // Summary: // Mixed-mode debugging of x64 processes is not supported when using Microsoft.NET // Framework versions earlier than 4.0. E_INTEROP_X64 = -2147220955, // // Summary: // Debugging older format crashdumps is not supported. E_CRASHDUMP_DEPRECATED = -2147220953, // // Summary: // Debugging managed-only minidumps is not supported. Specify 'Mixed' for the 'Debugger // Type' in project properties. E_LAUNCH_MANAGEDONLYMINIDUMP_UNSUPPORTED = -2147220952, // // Summary: // Debugging managed or mixed-mode minidumps is not supported on IA64 platforms. // Specify 'Native' for the 'Debugger Type' in project properties. E_LAUNCH_64BIT_MANAGEDMINIDUMP_UNSUPPORTED = -2147220951, // // Summary: // The remote tools are not signed correctly. E_DEVICEBITS_NOT_SIGNED = -2147220479, // // Summary: // Attach is not enabled for this process with this debug type. E_ATTACH_NOT_ENABLED = -2147220478, // // Summary: // The connection has been broken. E_REMOTE_DISCONNECT = -2147220477, // // Summary: // The threads in the process cannot be suspended at this time. This may be a temporary // condition. E_BREAK_ALL_FAILED = -2147220476, // // Summary: // Access denied. Try again, then check your device for a prompt. E_DEVICE_ACCESS_DENIED_SELECT_YES = -2147220475, // // Summary: // Unable to complete the operation. This could be because the device's security // settings are too restrictive. Please use the Device Security Manager to change // the settings and try again. E_DEVICE_ACCESS_DENIED = -2147220474, // // Summary: // The remote connection to the device has been lost. Verify the device connection // and restart debugging. E_DEVICE_CONNRESET = -2147220473, // // Summary: // Unable to load the CLR. The target device does not have a compatible version // of the CLR installed for the application you are attempting to debug. Verify // that your device supports the appropriate CLR version and has that CLR installed. // Some devices do not support automatic CLR upgrade. E_BAD_NETCF_VERSION = -2147220472, E_REFERENCE_NOT_VALID = -2147220223, E_PROPERTY_NOT_VALID = -2147220207, E_SETVALUE_VALUE_CANNOT_BE_SET = -2147220191, E_SETVALUE_VALUE_IS_READONLY = -2147220190, E_SETVALUEASREFERENCE_NOTSUPPORTED = -2147220189, E_CANNOT_GET_UNMANAGED_MEMORY_CONTEXT = -2147220127, E_GETREFERENCE_NO_REFERENCE = -2147220095, E_CODE_CONTEXT_OUT_OF_SCOPE = -2147220063, E_INVALID_SESSIONID = -2147220062, // // Summary: // The Visual Studio Remote Debugger on the target computer cannot connect back // to this computer. A firewall may be preventing communication via DCOM to the // local computer. It may be possible to avoid this error by changing your settings // to debug only native code or only managed code. E_SERVER_UNAVAILABLE_ON_CALLBACK = -2147220061, // // Summary: // The Visual Studio Remote Debugger on the target computer cannot connect back // to this computer. Authentication failed. It may be possible to avoid this error // by changing your settings to debug only native code or only managed code. E_ACCESS_DENIED_ON_CALLBACK = -2147220060, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer could // not connect to this computer because there was no available authentication service. // It may be possible to avoid this error by changing your settings to debug only // native code or only managed code. E_UNKNOWN_AUTHN_SERVICE_ON_CALLBACK = -2147220059, E_NO_SESSION_AVAILABLE = -2147220058, E_CLIENT_NOT_LOGGED_ON = -2147220057, E_OTHER_USERS_SESSION = -2147220056, E_USER_LEVEL_ACCESS_CONTROL_REQUIRED = -2147220055, // // Summary: // Can not evaluate script expressions while thread is stopped in the CLR. E_SCRIPT_CLR_EE_DISABLED = -2147220048, // // Summary: // Server side-error occurred on sending debug HTTP request. E_HTTP_SERVERERROR = -2147219712, // // Summary: // An authentication error occurred while communicating with the web server. Please // see Help for assistance. E_HTTP_UNAUTHORIZED = -2147219711, // // Summary: // Could not start ASP.NET debugging. More information may be available by starting // the project without debugging. E_HTTP_SENDREQUEST_FAILED = -2147219710, // // Summary: // The web server is not configured correctly. See help for common configuration // errors. Running the web page outside of the debugger may provide further information. E_HTTP_FORBIDDEN = -2147219709, // // Summary: // The server does not support debugging of ASP.NET or ATL Server applications. // Click Help for more information on how to enable debugging. E_HTTP_NOT_SUPPORTED = -2147219708, // // Summary: // Could not start ASP.NET or ATL Server debugging. E_HTTP_NO_CONTENT = -2147219707, // // Summary: // The web server could not find the requested resource. E_HTTP_NOT_FOUND = -2147219706, // // Summary: // The debug request could not be processed by the server due to invalid syntax. E_HTTP_BAD_REQUEST = -2147219705, // // Summary: // You do not have permissions to debug the web server process. You need to either // be running as the same user account as the web server, or have administrator // privilege. E_HTTP_ACCESS_DENIED = -2147219704, // // Summary: // Unable to connect to the web server. Verify that the web server is running and // that incoming HTTP requests are not blocked by a firewall. E_HTTP_CONNECT_FAILED = -2147219703, E_HTTP_EXCEPTION = -2147219702, // // Summary: // The web server did not respond in a timely manner. This may be because another // debugger is already attached to the web server. E_HTTP_TIMEOUT = -2147219701, // // Summary: // IIS does not list a web site that matches the launched URL. E_HTTP_SITE_NOT_FOUND = -2147219700, // // Summary: // IIS does not list an application that matches the launched URL. E_HTTP_APP_NOT_FOUND = -2147219699, // // Summary: // Debugging requires the IIS Management Console. To install, go to Control Panel->Programs->Turn // Windows features on or off. Check Internet Information Services->Web Management // Tools->IIS Management Console. E_HTTP_MANAGEMENT_API_MISSING = -2147219698, // // Summary: // The IIS worker process for the launched URL is not currently running. E_HTTP_NO_PROCESS = -2147219697, E_64BIT_COMPONENTS_NOT_INSTALLED = -2147219632, // // Summary: // The Visual Studio debugger cannot connect to the remote computer. Unable to initiate // DCOM communication. Please see Help for assistance. E_UNMARSHAL_SERVER_FAILED = -2147219631, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor on the remote computer cannot // connect to the local computer. Unable to initiate DCOM communication. Please // see Help for assistance. E_UNMARSHAL_CALLBACK_FAILED = -2147219630, // // Summary: // The Visual Studio debugger cannot connect to the remote computer. An RPC policy // is enabled on the local computer which prevents remote debugging. Please see // Help for assistance. E_RPC_REQUIRES_AUTHENTICATION = -2147219627, // // Summary: // The Microsoft Visual Studio Remote Debugging Monitor cannot logon to the local // computer: unknown user name or bad password. It may be possible to avoid this // error by changing your settings to debug only native code or only managed code. E_LOGON_FAILURE_ON_CALLBACK = -2147219626, // // Summary: // The Visual Studio debugger cannot establish a DCOM connection to the remote computer. // A firewall may be preventing communication via DCOM to the remote computer. It // may be possible to avoid this error by changing your settings to debug only native // code or only managed code. E_REMOTE_SERVER_UNAVAILABLE = -2147219625, E_REMOTE_CONNECT_USER_CANCELED = -2147219624, // // Summary: // Windows file sharing has been configured so that you will connect to the remote // computer using a different user name. This is incompatible with remote debugging. // Please see Help for assistance. E_REMOTE_CREDENTIALS_PROHIBITED = -2147219623, // // Summary: // Windows Firewall does not currently allow exceptions. Use Control Panel to change // the Windows Firewall settings so that exceptions are allowed. E_FIREWALL_NO_EXCEPTIONS = -2147219622, // // Summary: // Cannot add an application to the Windows Firewall exception list. Use the Control // Panel to manually configure the Windows Firewall. E_FIREWALL_CANNOT_OPEN_APPLICATION = -2147219621, // // Summary: // Cannot add a port to the Windows Firewall exception list. Use the Control Panel // to manually configure the Windows Firewall. E_FIREWALL_CANNOT_OPEN_PORT = -2147219620, // // Summary: // Cannot add 'File and Printer Sharing' to the Windows Firewall exception list. // Use the Control Panel to manually configure the Windows Firewall. E_FIREWALL_CANNOT_OPEN_FILE_SHARING = -2147219619, // // Summary: // Remote debugging is not supported. E_REMOTE_DEBUGGING_UNSUPPORTED = -2147219618, E_REMOTE_BAD_MSDBG2 = -2147219617, E_ATTACH_USER_CANCELED = -2147219616, // // Summary: // Maximum packet length exceeded. If the problem continues, reduce the number of // network host names or network addresses that are assigned to the computer running // Visual Studio computer or to the target computer. E_REMOTE_PACKET_TOO_BIG = -2147219615, // // Summary: // The target process is running a version of the Microsoft .NET Framework newer // than this version of Visual Studio. Visual Studio cannot debug this process. E_UNSUPPORTED_FUTURE_CLR_VERSION = -2147219614, // // Summary: // This version of Visual Studio does not support debugging code that uses Microsoft // .NET Framework v1.0. Use Visual Studio 2008 or earlier to debug this process. E_UNSUPPORTED_CLR_V1 = -2147219613, // // Summary: // Mixed-mode debugging of IA64 processes is not supported. E_INTEROP_IA64 = -2147219612, // // Summary: // See help for common configuration errors. Running the web page outside of the // debugger may provide further information. E_HTTP_GENERAL = -2147219611, // // Summary: // IDebugCoreServer* implementation does not have a connection to the remote computer. // This can occur in T-SQL debugging when there is no remote debugging monitor. E_REMOTE_NO_CONNECTION = -2147219610, // // Summary: // The specified remote debugging proxy server name is invalid. E_REMOTE_INVALID_PROXY_SERVER_NAME = -2147219609, // // Summary: // Operation is not permitted on IDebugCoreServer* implementation which has a weak // connection to the remote msvsmon instance. Weak connections are used when no // process is being debugged. E_REMOTE_WEAK_CONNECTION = -2147219608, // // Summary: // Remote program providers are no longer supported before debugging begins (ex: // process enumeration). E_REMOTE_PROGRAM_PROVIDERS_UNSUPPORTED = -2147219607, // // Summary: // Connection request was rejected by the remote debugger. Ensure that the remote // debugger is running in 'No Authentication' mode. E_REMOTE_REJECTED_NO_AUTH_REQUEST = -2147219606, // // Summary: // Connection request was rejected by the remote debugger. Ensure that the remote // debugger is running in 'Windows Authentication' mode. E_REMOTE_REJECTED_WIN_AUTH_REQUEST = -2147219605, // // Summary: // The debugger was unable to create a localhost TCP/IP connection, which is required // for 64-bit debugging. E_PSEUDOREMOTE_NO_LOCALHOST_TCPIP_CONNECTION = -2147219604, // // Summary: // This operation requires the Windows Web Services API to be installed, and it // is not currently installed on this computer. E_REMOTE_WWS_NOT_INSTALLED = -2147219603, // // Summary: // This operation requires the Windows Web Services API to be installed, and it // is not currently installed on this computer. To install Windows Web Services, // please restart Visual Studio as an administrator on this computer. E_REMOTE_WWS_INSTALL_REQUIRES_ADMIN = -2147219602, // // Summary: // The expression has not yet been translated to native machine code. E_FUNCTION_NOT_JITTED = -2147219456, E_NO_CODE_CONTEXT = -2147219455, // // Summary: // A Microsoft .NET Framework component, diasymreader.dll, is not correctly installed. // Please repair your Microsoft .NET Framework installation via 'Add or Remove Programs' // in Control Panel. E_BAD_CLR_DIASYMREADER = -2147219454, // // Summary: // Unable to load the CLR. If a CLR version was specified for debugging, check that // it was valid and installed on the machine. If the problem persists, please repair // your Microsoft .NET Framework installation via 'Programs and Features' in Control // Panel. E_CLR_SHIM_ERROR = -2147219453, // // Summary: // Unable to map the debug start page URL to a machine name. E_AUTOATTACH_WEBSERVER_NOT_FOUND = -2147219199, E_DBGEXTENSION_NOT_FOUND = -2147219184, E_DBGEXTENSION_FUNCTION_NOT_FOUND = -2147219183, E_DBGEXTENSION_FAULTED = -2147219182, E_DBGEXTENSION_RESULT_INVALID = -2147219181, E_PROGRAM_IN_RUNMODE = -2147219180, // // Summary: // The remote procedure could not be debugged. This usually indicates that debugging // has not been enabled on the server. See help for more information. E_CAUSALITY_NO_SERVER_RESPONSE = -2147219168, // // Summary: // Please install the Visual Studio Remote Debugger on the server to enable this // functionality. E_CAUSALITY_REMOTE_NOT_REGISTERED = -2147219167, // // Summary: // The debugger failed to stop in the server process. E_CAUSALITY_BREAKPOINT_NOT_HIT = -2147219166, // // Summary: // Unable to determine a stopping location. Verify symbols are loaded. E_CAUSALITY_BREAKPOINT_BIND_ERROR = -2147219165, // // Summary: // Debugging this project is disabled. Debugging can be re-enabled from 'Start Options' // under project properties. E_CAUSALITY_PROJECT_DISABLED = -2147219164, // // Summary: // Unable to attach the debugger to TSQL code. E_NO_ATTACH_WHILE_DDD = -2147218944, // // Summary: // Click Help for more information. E_SQLLE_ACCESSDENIED = -2147218943, // // Summary: // Click Help for more information. E_SQL_SP_ENABLE_PERMISSION_DENIED = -2147218942, // // Summary: // Click Help for more information. E_SQL_DEBUGGING_NOT_ENABLED_ON_SERVER = -2147218941, // // Summary: // Click Help for more information. E_SQL_CANT_FIND_SSDEBUGPS_ON_CLIENT = -2147218940, // // Summary: // Click Help for more information. E_SQL_EXECUTED_BUT_NOT_DEBUGGED = -2147218939, // // Summary: // Click Help for more information. E_SQL_VDT_INIT_RETURNED_SQL_ERROR = -2147218938, E_ATTACH_FAILED_ABORT_SILENTLY = -2147218937, // // Summary: // Click Help for more information. E_SQL_REGISTER_FAILED = -2147218936, E_DE_NOT_SUPPORTED_PRE_8_0 = -2147218688, E_PROGRAM_DESTROY_PENDING = -2147218687, // // Summary: // The operation isn't supported for the Common Language Runtime version used by // the process being debugged. E_MANAGED_FEATURE_NOTSUPPORTED = -2147218515, // // Summary: // The Visual Studio Remote Debugger does not support this edition of Windows. E_OS_PERSONAL = -2147218432, // // Summary: // Source server support is disabled because the assembly is partially trusted. E_SOURCE_SERVER_DISABLE_PARTIAL_TRUST = -2147218431, // // Summary: // Operation is not supported on the platform of the target computer/device. E_REMOTE_UNSUPPORTED_OPERATION_ON_PLATFORM = -2147218430, // // Summary: // Unable to load Visual Studio debugger component (vsdebugeng.dll). If this problem // persists, repair your installation via 'Add or Remove Programs' in Control Panel. E_LOAD_VSDEBUGENG_FAILED = -2147218416, // // Summary: // Unable to initialize Visual Studio debugger component (vsdebugeng.dll). If this // problem persists, repair your installation via 'Add or Remove Programs' in Control // Panel. E_LOAD_VSDEBUGENG_IMPORTS_FAILED = -2147218415, // // Summary: // Unable to initialize Visual Studio debugger due to a configuration error. If // this problem persists, repair your installation via 'Add or Remove Programs' // in Control Panel. E_LOAD_VSDEBUGENG_CONFIG_ERROR = -2147218414, // // Summary: // Failed to launch minidump. The minidump file is corrupt. E_CORRUPT_MINIDUMP = -2147218413, // // Summary: // Unable to load a Visual Studio component (VSDebugScriptAgent110.dll). If the // problem persists, repair your installation via 'Add or Remove Programs' in Control // Panel. E_LOAD_SCRIPT_AGENT_LOCAL_FAILURE = -2147218412, // // Summary: // Remote script debugging requires that the remote debugger is registered on the // target computer. Run the Visual Studio Remote Debugger setup (rdbgsetup_<processor>.exe) // on the target computer. E_LOAD_SCRIPT_AGENT_REMOTE_FAILURE = -2147218410, // // Summary: // The debugger was unable to find the registration for the target application. // If the problem persists, try uninstalling and then reinstalling this application. E_APPX_REGISTRATION_NOT_FOUND = -2147218409, // // Summary: // Unable to find a Visual Studio component (VsDebugLaunchNotify.exe). For remote // debugging, this file must be present on the target computer. If the problem persists, // repair your installation via 'Add or Remove Programs' in Control Panel. E_VSDEBUGLAUNCHNOTIFY_NOT_INSTALLED = -2147218408, // // Summary: // Windows 8 build# 8017 or higher is required to debug Windows Store apps. E_WIN8_TOO_OLD = -2147218404, E_THREAD_NOT_FOUND = -2147218175, // // Summary: // Cannot auto-attach to the SQL Server, possibly because the firewall is configured // incorrectly or auto-attach is forbidden by the operating system. E_CANNOT_AUTOATTACH_TO_SQLSERVER = -2147218174, E_OBJECT_OUT_OF_SYNC = -2147218173, E_PROCESS_ALREADY_CONTINUED = -2147218172, // // Summary: // Debugging multiple GPU processes is not supported. E_CANNOT_DEBUG_MULTI_GPU_PROCS = -2147218171, // // Summary: // No available devices supported by the selected debug engine. Please select a // different engine. E_GPU_ADAPTOR_NOT_FOUND = -2147218170, // // Summary: // A Microsoft Windows component is not correctly registered. Please ensure that // the Desktop Experience is enabled in Server Manager -> Manage -> Add Server Roles // and Features. E_WINDOWS_GRAPHICAL_SHELL_UNINSTALLED_ERROR = -2147218169, // // Summary: // Windows 8 or higher was required for GPU debugging on the software emulator. // For the most up-to-date information, please visit the link below. http://go.microsoft.com/fwlink/p/?LinkId=330081 E_GPU_DEBUG_NOT_SUPPORTED_PRE_DX_11_1 = -2147218168, // // Summary: // There is a configuration issue with the selected Debugging Accelerator Type. // For information on specific Accelerator providers, visit http://go.microsoft.com/fwlink/p/?LinkId=323500 E_GPU_DEBUG_CONFIG_ISSUE = -2147218167, // // Summary: // Local debugging is not supported for the selected Debugging Accelerator Type. // Use Remote Windows Debugger instead or change the Debugging Accelerator Type E_GPU_LOCAL_DEBUGGING_ERROR = -2147218166, // // Summary: // The debug driver for the selected Debugging Accelerator Type is not installed // on the target machine. For more information, visit http://go.microsoft.com/fwlink/p/?LinkId=323500 E_GPU_LOAD_VSD3D_FAILURE = -2147218165, // // Summary: // Timeout Detection and Recovery (TDR) must be disabled at the remote site. For // more information search for 'TdrLevel' in MSDN or visit the link below. http://go.microsoft.com/fwlink/p/?LinkId=323500 E_GPU_TDR_ENABLED_FAILURE = -2147218164, // // Summary: // Remote debugger does not support mixed (managed and native) debugger type. E_CANNOT_REMOTE_DEBUG_MIXED = -2147218163, // // Summary: // Background Task activation failed Please see Help for further information. E_BG_TASK_ACTIVATION_FAILED = -2147218162, // // Summary: // This version of the Visual Studio Remote Debugger does not support this operation. // Please upgrade to the latest version. http://go.microsoft.com/fwlink/p/?LinkId=219549 E_REMOTE_VERSION = -2147218161, // // Summary: // Unable to load a Visual Studio component (symbollocator.resources.dll). If the // problem persists, repair your installation via 'Add or Remove Programs' in Control // Panel. E_SYMBOL_LOCATOR_INSTALL_ERROR = -2147218160, // // Summary: // The format of the PE module is invalid. E_INVALID_PE_FORMAT = -2147218159, // // Summary: // This dump is already being debugged. E_DUMP_ALREADY_LAUNCHED = -2147218158, // // Summary: // The next statement cannot be set because the current assembly is optimized. E_CANNOT_SET_NEXT_STATEMENT_IN_OPTIMIZED_CODE = -2147218157, // // Summary: // Debugging of ARM minidumps requires Windows 8 or above. E_ARMDUMP_NOT_SUPPORTED_PRE_WIN8 = -2147218156, // // Summary: // Cannot detach while process termination is in progress. E_CANNOT_DETACH_WHILE_TERMINATE_IN_PROGRESS = -2147218155, // // Summary: // A required Microsoft Windows component, wldp.dll could not be found on the target // device. E_WLDP_NOT_FOUND = -2147218154, // // Summary: // The target device does not allow debugging this process. E_DEBUGGING_BLOCKED_ON_TARGET = -2147218153, // // Summary: // Unable to debug .NET Native code. Install the Microsoft .NET Native Developer // SDK. Alternatively debug with native code type. E_DOTNETNATIVE_SDK_NOT_INSTALLED = -2147218152, // // Summary: // The operation was canceled. COR_E_OPERATIONCANCELED = -2146233029, // // Summary: // A component dll failed to load. Try to restart this application. If failures // continue, try disabling any installed add-ins or repair your installation. E_XAPI_COMPONENT_LOAD_FAILURE = -1898053632, // // Summary: // Xapi has not been initialized on this thread. Call ComponentManager.InitializeThread. E_XAPI_NOT_INITIALIZED = -1898053631, // // Summary: // Xapi has already been initialized on this thread. E_XAPI_ALREADY_INITIALIZED = -1898053630, // // Summary: // Xapi event thread aborted unexpectedly. E_XAPI_THREAD_ABORTED = -1898053629, // // Summary: // Component failed a call to QueryInterface. QueryInterface implementation or component // configuration is incorrect. E_XAPI_BAD_QUERY_INTERFACE = -1898053628, // // Summary: // Object requested which is not available at the caller's component level. E_XAPI_UNAVAILABLE_OBJECT = -1898053627, // // Summary: // Failed to process configuration file. Try to restart this application. If failures // continue, try to repair your installation. E_XAPI_BAD_CONFIG = -1898053626, // // Summary: // Failed to initialize managed/native marshalling system. Try to restart this application. // If failures continue, try to repair your installation. E_XAPI_MANAGED_DISPATCHER_CONNECT_FAILURE = -1898053625, // // Summary: // This operation may only be preformed while processing the object's 'Create' event. E_XAPI_DURING_CREATE_EVENT_REQUIRED = -1898053624, // // Summary: // This operation may only be preformed by the component which created the object. E_XAPI_CREATOR_REQUIRED = -1898053623, // // Summary: // The work item cannot be appended to the work list because it is already complete. E_XAPI_WORK_LIST_COMPLETE = -1898053622, // // Summary: // 'Execute' may not be called on a work list which has already started. E_XAPI_WORKLIST_ALREADY_STARTED = -1898053621, // // Summary: // The interface implementation released the completion routine without calling // it. E_XAPI_COMPLETION_ROUTINE_RELEASED = -1898053620, // // Summary: // Operation is not supported on this thread. E_XAPI_WRONG_THREAD = -1898053619, // // Summary: // No component with the given component id could be found in the configuration // store. E_XAPI_COMPONENTID_NOT_FOUND = -1898053618, // // Summary: // Call was attempted to a remote connection from a server-side component (component // level > 100000). This is not allowed. E_XAPI_WRONG_CONNECTION_OBJECT = -1898053617, // // Summary: // Destination of this call is on a remote connection and this method doesn't support // remoting. E_XAPI_METHOD_NOT_REMOTED = -1898053616, // // Summary: // The network connection to the Visual Studio Remote Debugger was lost. E_XAPI_REMOTE_DISCONNECTED = -1898053615, // // Summary: // The network connection to the Visual Studio Remote Debugger has been closed. E_XAPI_REMOTE_CLOSED = -1898053614, // // Summary: // A protocol compatibility error occurred between Visual Studio and the Remote // Debugger. Please ensure that the Visual Studio and Remote debugger versions match. E_XAPI_INCOMPATIBLE_PROTOCOL = -1898053613, // // Summary: // Maximum allocation size exceeded while processing a remoting message. E_XAPI_MAX_PACKET_EXCEEDED = -1898053612, // // Summary: // An object already exists with the same key value. E_XAPI_OBJECT_ALREADY_EXISTS = -1898053611, // // Summary: // An object cannot be found with the given key value. E_XAPI_OBJECT_NOT_FOUND = -1898053610, // // Summary: // A data item already exists with the same key value. E_XAPI_DATA_ITEM_ALREADY_EXISTS = -1898053609, // // Summary: // A data item cannot be for this component found with the given data item ID. E_XAPI_DATA_ITEM_NOT_FOUND = -1898053608, // // Summary: // Interface implementation failed to provide a required out param. E_XAPI_NULL_OUT_PARAM = -1898053607, // // Summary: // Strong name signature validation error while trying to load the managed dispatcher E_XAPI_MANAGED_DISPATCHER_SIGNATURE_ERROR = -1898053600, // // Summary: // Method may only be called by components which load in the IDE process (component // level > 100000). E_XAPI_CLIENT_ONLY_METHOD = -1898053599, // // Summary: // Method may only be called by components which load in the remote debugger process // (component level < 100000). E_XAPI_SERVER_ONLY_METHOD = -1898053598, // // Summary: // A component dll could not be found. If failures continue, try disabling any installed // add-ins or repairing your installation. E_XAPI_COMPONENT_DLL_NOT_FOUND = -1898053597, // // Summary: // Operation requires the remote debugger be updated to a newer version. E_XAPI_REMOTE_NEW_VER_REQUIRED = -1898053596, // // Summary: // Symbols are not loaded for the target dll. E_SYMBOLS_NOT_LOADED = -1842151424, // // Summary: // Symbols for the target dll do not contain source information. E_SYMBOLS_STRIPPED = -1842151423, // // Summary: // Breakpoint could not be written at the specified instruction address. E_BP_INVALID_ADDRESS = -1842151422, // // Summary: // Breakpoints cannot be set in optimized code when the debugger option 'Just My // Code' is enabled. E_BP_IN_OPTIMIZED_CODE = -1842151420, // // Summary: // The Common Language Runtime was unable to set the breakpoint. E_BP_CLR_ERROR = -1842151418, // // Summary: // Cannot set breakpoints in .NET Framework methods which are implemented in native // code (ex: 'extern' function). E_BP_CLR_EXTERN_FUNCTION = -1842151417, // // Summary: // Cannot set breakpoint, target module is currently unloaded. E_BP_MODULE_UNLOADED = -1842151416, // // Summary: // Stopping events cannot be sent. See stopping event processing documentation for // more information. E_STOPPING_EVENT_REJECTED = -1842151415, // // Summary: // This operation is not permitted because the target process is already stopped. E_TARGET_ALREADY_STOPPED = -1842151414, // // Summary: // This operation is not permitted because the target process is not stopped. E_TARGET_NOT_STOPPED = -1842151413, // // Summary: // This operation is not allowed on this thread. E_WRONG_THREAD = -1842151412, // // Summary: // This operation is not allowed at this time. E_WRONG_TIME = -1842151411, // // Summary: // The caller is not allowed to request this operation. This operation must be requested // by a different component. E_WRONG_COMPONENT = -1842151410, // // Summary: // Operation is only permitted on the latest version of an edited method. E_WRONG_METHOD_VERSION = -1842151409, // // Summary: // A memory read or write operation failed because the specified memory address // is not currently valid. E_INVALID_MEMORY_ADDRESS = -1842151408, // // Summary: // No source information is available for this instruction. E_INSTRUCTION_NO_SOURCE = -1842151407, // // Summary: // Failed to load localizable resource from vsdebugeng.impl.resources.dll. If this // problem persists, please repair your Visual Studio installation via 'Add or Remove // Programs' in Control Panel. E_VSDEBUGENG_RESOURCE_LOAD_FAILURE = -1842151406, // // Summary: // DkmVariant is of a form that marshalling is not supported. Marshalling is supported // for primitives types, strings, and safe arrays of primitives. E_UNMARSHALLABLE_VARIANT = -1842151405, // // Summary: // An incorrect version of vsdebugeng.dll was loaded into Visual Studio. Please // repair your Visual Studio installation. E_VSDEBUGENG_DEPLOYMENT_ERROR = -1842151404, // // Summary: // The remote debugger was unable to initialize Microsoft Windows Web Services (webservices.dll). // If the problem continues, try reinstalling the Windows Web Services redistributable. // This redistributable can be found under the 'Remote Debugger\Common Resources\Windows // Updates' folder. E_WEBSERVICES_LOAD_FAILURE = -1842151403, // // Summary: // Visual Studio encountered an error while loading a Windows component (Global // Interface Table). If the problem persists, this may be an indication of operating // system corruption, and Windows may need to be reinstalled. E_GLOBAL_INTERFACE_POINTER_FAILURE = -1842151402, // // Summary: // Windows authentication was unable to establish a secure connection to the remote // computer. E_REMOTE_AUTHENTICATION_ERROR = -1842151401, // // Summary: // The Remote Debugger was unable to locate a resource dll (vsdebugeng.impl.resources.dll). // Please ensure that the complete remote debugger folder was copied or installed // on the target computer. E_CANNOT_FIND_REMOTE_RESOURCES = -1842151400, // // Summary: // The hardware does not support monitoring the requested number of bytes. E_INVALID_DATABP_SIZE = -1842151392, // // Summary: // The maximum number of data breakpoints have already been set. E_INVALID_DATABP_ALLREGSUSED = -1842151391, // // Summary: // Breakpoints cannot be set while debugging a minidump. E_DUMPS_DO_NOT_SUPPORT_BREAKPOINTS = -1842151390, // // Summary: // The minidump is from an ARM-based computer and can only be debugged on an ARM // computer. E_DUMP_ARM_ARCHITECTURE = -1842151389, // // Summary: // The minidump is from an unknown processor, and cannot be debugged with this version // of Visual Studio. E_DUMP_UNKNOWN_ARCHITECTURE = -1842151388, // // Summary: // The shell failed to find a checksum for this file. E_NO_CHECKSUM = -1842151387, // // Summary: // On x64, context control must be included in a SetThreadContext E_CONTEXT_CONTROL_REQUIRED = -1842151386, // // Summary: // The size of the buffer does not match the size of the register. E_INVALID_REGISTER_SIZE = -1842151385, // // Summary: // The requested register was not found in the stack frame's unwound register collection. E_REGISTER_NOT_FOUND = -1842151384, // // Summary: // Cannot set a read-only register. E_REGISTER_READONLY = -1842151383, // // Summary: // Cannot set a register in a frame that is not the top of the stack. E_REG_NOT_TOP_STACK = -1842151376, // // Summary: // String could not be read within the specified maximum number of characters. E_STRING_TOO_LONG = -1842151375, // // Summary: // The memory region does not meet the requested protection flags. E_INVALID_MEMORY_PROTECT = -1842151374, // // Summary: // Instruction is invalid or unknown to the disassembler. E_UNKNOWN_CPU_INSTRUCTION = -1842151373, // // Summary: // An invalid runtime was specified for this operation. E_INVALID_RUNTIME = -1842151372, // // Summary: // Variable is optimized away. E_VARIABLE_OPTIMIZED_AWAY = -1842151371, // // Summary: // The text span is not currently loaded in the specified script document. E_TEXT_SPAN_NOT_LOADED = -1842151370, // // Summary: // This location could not be mapped to client side script. E_SCRIPT_SPAN_MAPPING_FAILED = -1842151369, // // Summary: // The file requested must be less than 100 megabytes in size E_DEPLOY_FILE_TOO_LARGE = -1842151368, // // Summary: // The file path requested could not be written to as it is invalid. Ensure the // path does not contain a file where a directory is expected. E_DEPLOY_FILE_PATH_INVALID = -1842151367, // // Summary: // Script debugging is not enabled for WWAHost.exe. E_SCRIPT_DEBUGGING_DISABLED_WWAHOST_ATTACH_FAILED = -1842151360, // // Summary: // The file path requested for deletion does not exist. E_DEPLOY_FILE_NOT_EXIST = -1842151359, // // Summary: // A command is already executing, only one may execute at a time. Please wait for // the executable to exit, or abort the command. E_EXECUTE_COMMAND_IN_PROGRESS = -1842151358, // // Summary: // The specified file path is a relative or unknown path format. File paths must // be fully qualified. E_INVALID_FULL_PATH = -1842151357, // // Summary: // Windows Store app debugging is not possible when the remote debugger is running // as a service. Run the Remote Debugger Configuration Wizard on the target computer, // and uncheck the option to start the remote debugger service. Then start the Visual // Studio Remote Debugging Monitor application. E_CANNOT_DEBUG_APP_PACKAGE_IN_RDBSERVICE = -1842151356, // // Summary: // Applications cannot be launched under the debugger when the remote debugger is // running as a service. Run the Remote Debugger Configuration Wizard on the target // computer, and uncheck the option to start the remote debugger service. Then start // the Visual Studio Remote Debugging Monitor application. E_CANNOT_LAUNCH_IN_RDBSERVICE = -1842151355, // // Summary: // The AD7 AL Causality bridge has already been initialized. E_CAUSALITY_BRIDGE_ALREADY_INITIALIZED = -1842151354, // // Summary: // App Packages may only be shutdown as part of a Visual Studio build operation. E_DEPLOY_APPX_SHUTDOWN_WRONG_TIME = -1842151353, // // Summary: // A Microsoft Windows component is not correctly registered. If the problem persists, // try repairing your Windows installation, or reinstalling Windows. E_WINDOWS_REG_ERROR = -1842151352, // // Summary: // The application never reached a suspended state. E_APP_PACKAGE_NEVER_SUSPENDED = -1842151351, // // Summary: // A different version of this script file has been loaded by the debugged process. // The script file may need to be reloaded. E_SCRIPT_FILE_DIFFERENT_CONTENT = -1842151350, // // Summary: // No stack frame was found. E_NO_FRAME = -1842151349, // // Summary: // Operation is not supported while interop debugging. E_NOT_SUPPORTED_INTEROP = -1842151348, // // Summary: // The selected accelerator does not support the run current tile to cursor operation. E_GPU_BARRIER_BREAKPOINT_NOT_SUPPORTED = -1842151347, // // Summary: // Data breakpoints are not supported on this platform. E_DATABPS_NOTSUPPORTED = -1842151346, // // Summary: // The debugger failed to attach to the process requested in the DkmDebugProcessRequest. E_DEBUG_PROCESS_REQUEST_FAILED = -1842151345, // // Summary: // An invalid NativeOffset or CPUInstructionPart value was used with a DkmClrInstructionAddress // or DkmClrInstructionSymbol E_INVALID_CLR_INSTRUCTION_NATIVE_OFFSET = -1842151339, // // Summary: // Managed heap is not in a state that can be enumerated E_MANAGED_HEAP_NOT_ENUMERABLE = -1842151338, // // Summary: // This operation is unavailable when mixed mode debugging with Script E_OPERATION_UNAVAILABLE_SCRIPT_INTEROP = -1842151337, // // Summary: // This operation is unavailable when debugging native-compiled .NET code. E_OPERATION_UNAVAILABLE_CLR_NC = -1842151336, // // Summary: // Symbol file contains data which is in an unexpected format. E_BAD_SYMBOL_DATA = -1842151335, // // Summary: // Dynamically enabling script debugging in the target process failed. E_ENABLE_SCRIPT_DEBUGGING_FAILED = -1842151334, // // Summary: // Expression evaluation is not available in async call stack frames. E_SCRIPT_ASYNC_FRAME_EE_UNAVAILABLE = -1842151333, // // Summary: // This dump does not contain any thread information or the thread information is // corrupt. Visual Studio does not support debugging of dumps without valid thread // information. E_DUMP_NO_THREADS = -1842151332, // // Summary: // DkmLoadCompleteEventDeferral.Add cannot be called after the load complete event // has been sent. E_LOAD_COMPLETE_ALREADY_SENT = -1842151331, // // Summary: // DkmLoadCompleteEventDeferral was not present in the list during a call to DkmLoadCompleteEventDeferral.Remove. E_LOAD_COMPLETE_DEFERRAL_NOT_FOUND = -1842151330, // // Summary: // The buffer size specified was too large to marshal over the remote boundary. E_MARSHALLING_SIZE_TOO_LARGE = -1842151329, // // Summary: // Emulation of iterator for results view failed. This is typically caused when // the iterator calls into native code. E_CANNOT_EMULATE_RESULTS_VIEW = -1842151328, // // Summary: // Managed heap enumeration is attempted on running target. This is typically caused // by continuing the process while heap enumeration is in progress. E_MANAGED_HEAP_ENUMERATION_TARGET_NOT_STOPPED = -1842151327 } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Workspaces/Core/Portable/Differencing/AbstractSyntaxComparer.cs
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Differencing { internal abstract class AbstractSyntaxComparer : TreeComparer<SyntaxNode> { protected const double ExactMatchDist = 0.0; protected const double EpsilonDist = 0.00001; internal const int IgnoredNode = -1; protected readonly SyntaxNode? _oldRoot; protected readonly SyntaxNode? _newRoot; private readonly IEnumerable<SyntaxNode>? _oldRootChildren; private readonly IEnumerable<SyntaxNode>? _newRootChildren; // This comparer can operate in two modes: // * Top level syntax, which looks at member declarations, but doesn't look inside method bodies etc. // * Statement syntax, which looks into member bodies and descends through all statements and expressions // This flag is used where there needs to be a distinction made between how these are treated protected readonly bool _compareStatementSyntax; internal AbstractSyntaxComparer( SyntaxNode? oldRoot, SyntaxNode? newRoot, IEnumerable<SyntaxNode>? oldRootChildren, IEnumerable<SyntaxNode>? newRootChildren, bool compareStatementSyntax) { _compareStatementSyntax = compareStatementSyntax; _oldRoot = oldRoot; _newRoot = newRoot; _oldRootChildren = oldRootChildren; _newRootChildren = newRootChildren; } protected internal sealed override bool TreesEqual(SyntaxNode oldNode, SyntaxNode newNode) => oldNode.SyntaxTree == newNode.SyntaxTree; protected internal sealed override TextSpan GetSpan(SyntaxNode node) => node.Span; /// <summary> /// Calculates distance of two nodes based on their significant parts. /// Returns false if the nodes don't have any significant parts and should be compared as a whole. /// </summary> protected abstract bool TryComputeWeightedDistance(SyntaxNode oldNode, SyntaxNode newNode, out double distance); protected abstract bool IsLambdaBodyStatementOrExpression(SyntaxNode node); protected internal override bool TryGetParent(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? parent) { if (node == _oldRoot || node == _newRoot) { parent = null; return false; } parent = node.Parent; while (parent != null && !HasLabel(parent)) { parent = parent.Parent; } return parent != null; } protected internal override IEnumerable<SyntaxNode>? GetChildren(SyntaxNode node) { if (node == _oldRoot) { return _oldRootChildren; } if (node == _newRoot) { return _newRootChildren; } return HasChildren(node) ? EnumerateChildren(node) : null; } private IEnumerable<SyntaxNode> EnumerateChildren(SyntaxNode node) { foreach (var child in node.ChildNodes()) { if (IsLambdaBodyStatementOrExpression(child)) { continue; } if (HasLabel(child)) { yield return child; } else if (_compareStatementSyntax) { foreach (var descendant in child.DescendantNodes(DescendIntoChildren)) { if (HasLabel(descendant)) { yield return descendant; } } } } } private bool DescendIntoChildren(SyntaxNode node) => !IsLambdaBodyStatementOrExpression(node) && !HasLabel(node); protected internal sealed override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node) { var rootChildren = (node == _oldRoot) ? _oldRootChildren : (node == _newRoot) ? _newRootChildren : null; return (rootChildren != null) ? EnumerateDescendants(rootChildren) : EnumerateDescendants(node); } private IEnumerable<SyntaxNode> EnumerateDescendants(IEnumerable<SyntaxNode> nodes) { foreach (var node in nodes) { if (HasLabel(node)) { yield return node; } foreach (var descendant in EnumerateDescendants(node)) { if (HasLabel(descendant)) { yield return descendant; } } } } private IEnumerable<SyntaxNode> EnumerateDescendants(SyntaxNode node) { foreach (var descendant in node.DescendantNodesAndTokens( descendIntoChildren: child => ShouldEnumerateChildren(child), descendIntoTrivia: false)) { var descendantNode = descendant.AsNode(); if (descendantNode != null && HasLabel(descendantNode)) { if (!IsLambdaBodyStatementOrExpression(descendantNode)) { yield return descendantNode; } } } bool ShouldEnumerateChildren(SyntaxNode child) { // if we don't want to consider this nodes children, then don't if (!HasChildren(child)) { return false; } // Always descend into the children of the node we were asked about if (child == node) { return true; } // otherwise, as long as we don't descend into lambdas return !IsLambdaBodyStatementOrExpression(child); } } protected bool HasChildren(SyntaxNode node) { // Leaves are labeled statements that don't have a labeled child. // We also return true for non-labeled statements. var label = Classify(node.RawKind, node, out var isLeaf); // ignored should always be reported as leaves for top syntax, but for statements // we want to look at all child nodes, because almost anything could have a lambda if (!_compareStatementSyntax) { Debug.Assert(label != IgnoredNode || isLeaf); } return !isLeaf; } internal bool HasLabel(SyntaxNode node) => Classify(node.RawKind, node, out _) != IgnoredNode; internal abstract int Classify(int kind, SyntaxNode? node, out bool isLeaf); protected internal override int GetLabel(SyntaxNode node) => Classify(node.RawKind, node, out _); } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Differencing { internal abstract class AbstractSyntaxComparer : TreeComparer<SyntaxNode> { protected const double ExactMatchDist = 0.0; protected const double EpsilonDist = 0.00001; internal const int IgnoredNode = -1; protected readonly SyntaxNode? _oldRoot; protected readonly SyntaxNode? _newRoot; private readonly IEnumerable<SyntaxNode>? _oldRootChildren; private readonly IEnumerable<SyntaxNode>? _newRootChildren; // This comparer can operate in two modes: // * Top level syntax, which looks at member declarations, but doesn't look inside method bodies etc. // * Statement syntax, which looks into member bodies and descends through all statements and expressions // This flag is used where there needs to be a distinction made between how these are treated protected readonly bool _compareStatementSyntax; internal AbstractSyntaxComparer( SyntaxNode? oldRoot, SyntaxNode? newRoot, IEnumerable<SyntaxNode>? oldRootChildren, IEnumerable<SyntaxNode>? newRootChildren, bool compareStatementSyntax) { _compareStatementSyntax = compareStatementSyntax; _oldRoot = oldRoot; _newRoot = newRoot; _oldRootChildren = oldRootChildren; _newRootChildren = newRootChildren; } protected internal sealed override bool TreesEqual(SyntaxNode oldNode, SyntaxNode newNode) => oldNode.SyntaxTree == newNode.SyntaxTree; protected internal sealed override TextSpan GetSpan(SyntaxNode node) => node.Span; /// <summary> /// Calculates distance of two nodes based on their significant parts. /// Returns false if the nodes don't have any significant parts and should be compared as a whole. /// </summary> protected abstract bool TryComputeWeightedDistance(SyntaxNode oldNode, SyntaxNode newNode, out double distance); protected abstract bool IsLambdaBodyStatementOrExpression(SyntaxNode node); protected internal override bool TryGetParent(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? parent) { if (node == _oldRoot || node == _newRoot) { parent = null; return false; } parent = node.Parent; while (parent != null && !HasLabel(parent)) { parent = parent.Parent; } return parent != null; } protected internal override IEnumerable<SyntaxNode>? GetChildren(SyntaxNode node) { if (node == _oldRoot) { return _oldRootChildren; } if (node == _newRoot) { return _newRootChildren; } return HasChildren(node) ? EnumerateChildren(node) : null; } private IEnumerable<SyntaxNode> EnumerateChildren(SyntaxNode node) { foreach (var child in node.ChildNodes()) { if (IsLambdaBodyStatementOrExpression(child)) { continue; } if (HasLabel(child)) { yield return child; } else if (_compareStatementSyntax) { foreach (var descendant in child.DescendantNodes(DescendIntoChildren)) { if (HasLabel(descendant)) { yield return descendant; } } } } } private bool DescendIntoChildren(SyntaxNode node) => !IsLambdaBodyStatementOrExpression(node) && !HasLabel(node); protected internal sealed override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node) { var rootChildren = (node == _oldRoot) ? _oldRootChildren : (node == _newRoot) ? _newRootChildren : null; return (rootChildren != null) ? EnumerateDescendants(rootChildren) : EnumerateDescendants(node); } private IEnumerable<SyntaxNode> EnumerateDescendants(IEnumerable<SyntaxNode> nodes) { foreach (var node in nodes) { if (HasLabel(node)) { yield return node; } foreach (var descendant in EnumerateDescendants(node)) { if (HasLabel(descendant)) { yield return descendant; } } } } private IEnumerable<SyntaxNode> EnumerateDescendants(SyntaxNode node) { foreach (var descendant in node.DescendantNodesAndTokens( descendIntoChildren: child => ShouldEnumerateChildren(child), descendIntoTrivia: false)) { var descendantNode = descendant.AsNode(); if (descendantNode != null && HasLabel(descendantNode)) { if (!IsLambdaBodyStatementOrExpression(descendantNode)) { yield return descendantNode; } } } bool ShouldEnumerateChildren(SyntaxNode child) { // if we don't want to consider this nodes children, then don't if (!HasChildren(child)) { return false; } // Always descend into the children of the node we were asked about if (child == node) { return true; } // otherwise, as long as we don't descend into lambdas return !IsLambdaBodyStatementOrExpression(child); } } protected bool HasChildren(SyntaxNode node) { // Leaves are labeled statements that don't have a labeled child. // We also return true for non-labeled statements. var label = Classify(node.RawKind, node, out var isLeaf); // ignored should always be reported as leaves for top syntax, but for statements // we want to look at all child nodes, because almost anything could have a lambda if (!_compareStatementSyntax) { Debug.Assert(label != IgnoredNode || isLeaf); } return !isLeaf; } internal bool HasLabel(SyntaxNode node) => Classify(node.RawKind, node, out _) != IgnoredNode; internal abstract int Classify(int kind, SyntaxNode? node, out bool isLeaf); protected internal override int GetLabel(SyntaxNode node) => Classify(node.RawKind, node, out _); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarAutomationStrings.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor { internal static class NavigationBarAutomationStrings { public const string ProjectDropdownName = "Projects"; public const string ProjectDropdownId = "ProjectsList"; public const string TypeDropdownName = "Objects"; public const string TypeDropdownId = "ScopesList"; public const string MemberDropdownName = "Members"; public const string MemberDropdownId = "FunctionsList"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor { internal static class NavigationBarAutomationStrings { public const string ProjectDropdownName = "Projects"; public const string ProjectDropdownId = "ProjectsList"; public const string TypeDropdownName = "Objects"; public const string TypeDropdownId = "ScopesList"; public const string MemberDropdownName = "Members"; public const string MemberDropdownId = "FunctionsList"; } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/EditorFeatures/Core/Shared/Utilities/NativeMethods.cs
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { internal static class NativeMethods { internal const uint MWMO_INPUTAVAILABLE = 0x0004; internal const uint QS_KEY = 0x0001, QS_MOUSEMOVE = 0x0002, QS_MOUSEBUTTON = 0x0004, QS_POSTMESSAGE = 0x0008, QS_TIMER = 0x0010, QS_PAINT = 0x0020, QS_SENDMESSAGE = 0x0040, QS_HOTKEY = 0x0080, QS_ALLPOSTMESSAGE = 0x0100, QS_MOUSE = QS_MOUSEMOVE | QS_MOUSEBUTTON, QS_INPUT = QS_MOUSE | QS_KEY, QS_ALLEVENTS = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY, QS_ALLINPUT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE, QS_EVENT = 0x2000; [DllImport("user32.dll")] internal static extern uint GetQueueStatus(uint flags); } }
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { internal static class NativeMethods { internal const uint MWMO_INPUTAVAILABLE = 0x0004; internal const uint QS_KEY = 0x0001, QS_MOUSEMOVE = 0x0002, QS_MOUSEBUTTON = 0x0004, QS_POSTMESSAGE = 0x0008, QS_TIMER = 0x0010, QS_PAINT = 0x0020, QS_SENDMESSAGE = 0x0040, QS_HOTKEY = 0x0080, QS_ALLPOSTMESSAGE = 0x0100, QS_MOUSE = QS_MOUSEMOVE | QS_MOUSEBUTTON, QS_INPUT = QS_MOUSE | QS_KEY, QS_ALLEVENTS = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY, QS_ALLINPUT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE, QS_EVENT = 0x2000; [DllImport("user32.dll")] internal static extern uint GetQueueStatus(uint flags); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/Core/Portable/SourceGeneration/GeneratorContexts.cs
// Licensed to the .NET Foundation under one or more 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.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> is called /// </summary> public readonly struct GeneratorExecutionContext { private readonly DiagnosticBag _diagnostics; private readonly ArrayBuilder<GeneratedSourceText> _additionalSources; internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray<AdditionalText> additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxContextReceiver? syntaxReceiver, CancellationToken cancellationToken = default) { Compilation = compilation; ParseOptions = parseOptions; AdditionalFiles = additionalTexts; AnalyzerConfigOptions = optionsProvider; SyntaxReceiver = (syntaxReceiver as SyntaxContextReceiverAdaptor)?.Receiver; SyntaxContextReceiver = (syntaxReceiver is SyntaxContextReceiverAdaptor) ? null : syntaxReceiver; CancellationToken = cancellationToken; _additionalSources = ArrayBuilder<GeneratedSourceText>.GetInstance(); _diagnostics = new DiagnosticBag(); } /// <summary> /// Get the current <see cref="CodeAnalysis.Compilation"/> at the time of execution. /// </summary> /// <remarks> /// This compilation contains only the user supplied code; other generated code is not /// available. As user code can depend on the results of generation, it is possible that /// this compilation will contain errors. /// </remarks> public Compilation Compilation { get; } /// <summary> /// Get the <see cref="CodeAnalysis.ParseOptions"/> that will be used to parse any added sources. /// </summary> public ParseOptions ParseOptions { get; } /// <summary> /// A set of additional non-code text files that can be used by generators. /// </summary> public ImmutableArray<AdditionalText> AdditionalFiles { get; } /// <summary> /// Allows access to options provided by an analyzer config /// </summary> public AnalyzerConfigOptionsProvider AnalyzerConfigOptions { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxReceiver? SyntaxReceiver { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxContextReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxContextReceiver? SyntaxContextReceiver { get; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the generation should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(new GeneratedSourceText(hintName, sourceText)); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => _diagnostics.Add(diagnostic); internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (_additionalSources.ToImmutableAndFree(), _diagnostics.ToReadOnlyAndFree()); internal void Free() { _additionalSources.Free(); _diagnostics.Free(); } internal void CopyToProductionContext(SourceProductionContext ctx) { ctx.Sources.AddRange(_additionalSources); ctx.Diagnostics.AddRange(_diagnostics); } } /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Initialize(GeneratorInitializationContext)"/> is called /// </summary> public struct GeneratorInitializationContext { internal GeneratorInitializationContext(CancellationToken cancellationToken = default) { CancellationToken = cancellationToken; InfoBuilder = new GeneratorInfo.Builder(); } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the initialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } internal GeneratorInfo.Builder InfoBuilder { get; } /// <summary> /// Register a <see cref="SyntaxReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxReceiver"/>. This receiver will have its <see cref="ISyntaxReceiver.OnVisitSyntaxNode(SyntaxNode)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxReceiver"/> is created per-generation, meaning there is no need to manage the lifetime of the /// receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = SyntaxContextReceiverAdaptor.Create(receiverCreator); } /// <summary> /// Register a <see cref="SyntaxContextReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxContextReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxContextReceiver"/>. This receiver will have its <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxContextReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxContextReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxContextReceiver"/> is created prior to every call to <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/>, /// meaning there is no need to manage the lifetime of the receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxContextReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxContextReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxContextReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = receiverCreator; } /// <summary> /// Register a callback that is invoked after initialization. /// </summary> /// <remarks> /// This method allows a generator to opt-in to an extra phase in the generator lifecycle called PostInitialization. After being initialized /// any generators that have opted in will have their provided callback invoked with a <see cref="GeneratorPostInitializationContext"/> instance /// that can be used to alter the compilation that is provided to subsequent generator phases. /// /// For example a generator may choose to add sources during PostInitialization. These will be added to the compilation before execution and /// will be visited by a registered <see cref="ISyntaxReceiver"/> and available for semantic analysis as part of the <see cref="GeneratorExecutionContext.Compilation"/> /// /// Note that any sources added during PostInitialization <i>will</i> be visible to the later phases of other generators operating on the compilation. /// </remarks> /// <param name="callback">An <see cref="Action{T}"/> that accepts a <see cref="GeneratorPostInitializationContext"/> that will be invoked after initialization.</param> public void RegisterForPostInitialization(Action<GeneratorPostInitializationContext> callback) { CheckIsEmpty(InfoBuilder.PostInitCallback); InfoBuilder.PostInitCallback = (context) => callback(new GeneratorPostInitializationContext(context.AdditionalSources, context.CancellationToken)); } private static void CheckIsEmpty<T>(T x, string? typeName = null) where T : class? { if (x is object) { throw new InvalidOperationException(string.Format(CodeAnalysisResources.Single_type_per_generator_0, typeName ?? typeof(T).Name)); } } } /// <summary> /// Context passed to an <see cref="ISyntaxContextReceiver"/> when <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> is called /// </summary> public readonly struct GeneratorSyntaxContext { internal GeneratorSyntaxContext(SyntaxNode node, SemanticModel semanticModel) { Node = node; SemanticModel = semanticModel; } /// <summary> /// The <see cref="SyntaxNode"/> currently being visited /// </summary> public SyntaxNode Node { get; } /// <summary> /// The <see cref="CodeAnalysis.SemanticModel" /> that can be queried to obtain information about <see cref="Node"/>. /// </summary> public SemanticModel SemanticModel { get; } } /// <summary> /// Context passed to a source generator when it has opted-in to PostInitialization via <see cref="GeneratorInitializationContext.RegisterForPostInitialization(Action{GeneratorPostInitializationContext})"/> /// </summary> public readonly struct GeneratorPostInitializationContext { private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { _additionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, 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.Text; using System.Threading; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> is called /// </summary> public readonly struct GeneratorExecutionContext { private readonly DiagnosticBag _diagnostics; private readonly ArrayBuilder<GeneratedSourceText> _additionalSources; internal GeneratorExecutionContext(Compilation compilation, ParseOptions parseOptions, ImmutableArray<AdditionalText> additionalTexts, AnalyzerConfigOptionsProvider optionsProvider, ISyntaxContextReceiver? syntaxReceiver, CancellationToken cancellationToken = default) { Compilation = compilation; ParseOptions = parseOptions; AdditionalFiles = additionalTexts; AnalyzerConfigOptions = optionsProvider; SyntaxReceiver = (syntaxReceiver as SyntaxContextReceiverAdaptor)?.Receiver; SyntaxContextReceiver = (syntaxReceiver is SyntaxContextReceiverAdaptor) ? null : syntaxReceiver; CancellationToken = cancellationToken; _additionalSources = ArrayBuilder<GeneratedSourceText>.GetInstance(); _diagnostics = new DiagnosticBag(); } /// <summary> /// Get the current <see cref="CodeAnalysis.Compilation"/> at the time of execution. /// </summary> /// <remarks> /// This compilation contains only the user supplied code; other generated code is not /// available. As user code can depend on the results of generation, it is possible that /// this compilation will contain errors. /// </remarks> public Compilation Compilation { get; } /// <summary> /// Get the <see cref="CodeAnalysis.ParseOptions"/> that will be used to parse any added sources. /// </summary> public ParseOptions ParseOptions { get; } /// <summary> /// A set of additional non-code text files that can be used by generators. /// </summary> public ImmutableArray<AdditionalText> AdditionalFiles { get; } /// <summary> /// Allows access to options provided by an analyzer config /// </summary> public AnalyzerConfigOptionsProvider AnalyzerConfigOptions { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxReceiver? SyntaxReceiver { get; } /// <summary> /// If the generator registered an <see cref="ISyntaxContextReceiver"/> during initialization, this will be the instance created for this generation pass. /// </summary> public ISyntaxContextReceiver? SyntaxContextReceiver { get; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the generation should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation. /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(new GeneratedSourceText(hintName, sourceText)); /// <summary> /// Adds a <see cref="Diagnostic"/> to the users compilation /// </summary> /// <param name="diagnostic">The diagnostic that should be added to the compilation</param> /// <remarks> /// The severity of the diagnostic may cause the compilation to fail, depending on the <see cref="Compilation"/> settings. /// </remarks> public void ReportDiagnostic(Diagnostic diagnostic) => _diagnostics.Add(diagnostic); internal (ImmutableArray<GeneratedSourceText> sources, ImmutableArray<Diagnostic> diagnostics) ToImmutableAndFree() => (_additionalSources.ToImmutableAndFree(), _diagnostics.ToReadOnlyAndFree()); internal void Free() { _additionalSources.Free(); _diagnostics.Free(); } internal void CopyToProductionContext(SourceProductionContext ctx) { ctx.Sources.AddRange(_additionalSources); ctx.Diagnostics.AddRange(_diagnostics); } } /// <summary> /// Context passed to a source generator when <see cref="ISourceGenerator.Initialize(GeneratorInitializationContext)"/> is called /// </summary> public struct GeneratorInitializationContext { internal GeneratorInitializationContext(CancellationToken cancellationToken = default) { CancellationToken = cancellationToken; InfoBuilder = new GeneratorInfo.Builder(); } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the initialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } internal GeneratorInfo.Builder InfoBuilder { get; } /// <summary> /// Register a <see cref="SyntaxReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxReceiver"/>. This receiver will have its <see cref="ISyntaxReceiver.OnVisitSyntaxNode(SyntaxNode)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxReceiver"/> is created per-generation, meaning there is no need to manage the lifetime of the /// receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = SyntaxContextReceiverAdaptor.Create(receiverCreator); } /// <summary> /// Register a <see cref="SyntaxContextReceiverCreator"/> for this generator, which can be used to create an instance of an <see cref="ISyntaxContextReceiver"/>. /// </summary> /// <remarks> /// This method allows generators to be 'syntax aware'. Before each generation the <paramref name="receiverCreator"/> will be invoked to create /// an instance of <see cref="ISyntaxContextReceiver"/>. This receiver will have its <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> /// invoked for each syntax node in the compilation, allowing the receiver to build up information about the compilation before generation occurs. /// /// During <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/> the generator can obtain the <see cref="ISyntaxContextReceiver"/> instance that was /// created by accessing the <see cref="GeneratorExecutionContext.SyntaxContextReceiver"/> property. Any information that was collected by the receiver can be /// used to generate the final output. /// /// A new instance of <see cref="ISyntaxContextReceiver"/> is created prior to every call to <see cref="ISourceGenerator.Execute(GeneratorExecutionContext)"/>, /// meaning there is no need to manage the lifetime of the receiver or its contents. /// </remarks> /// <param name="receiverCreator">A <see cref="SyntaxContextReceiverCreator"/> that can be invoked to create an instance of <see cref="ISyntaxContextReceiver"/></param> public void RegisterForSyntaxNotifications(SyntaxContextReceiverCreator receiverCreator) { CheckIsEmpty(InfoBuilder.SyntaxContextReceiverCreator, $"{nameof(SyntaxReceiverCreator)} / {nameof(SyntaxContextReceiverCreator)}"); InfoBuilder.SyntaxContextReceiverCreator = receiverCreator; } /// <summary> /// Register a callback that is invoked after initialization. /// </summary> /// <remarks> /// This method allows a generator to opt-in to an extra phase in the generator lifecycle called PostInitialization. After being initialized /// any generators that have opted in will have their provided callback invoked with a <see cref="GeneratorPostInitializationContext"/> instance /// that can be used to alter the compilation that is provided to subsequent generator phases. /// /// For example a generator may choose to add sources during PostInitialization. These will be added to the compilation before execution and /// will be visited by a registered <see cref="ISyntaxReceiver"/> and available for semantic analysis as part of the <see cref="GeneratorExecutionContext.Compilation"/> /// /// Note that any sources added during PostInitialization <i>will</i> be visible to the later phases of other generators operating on the compilation. /// </remarks> /// <param name="callback">An <see cref="Action{T}"/> that accepts a <see cref="GeneratorPostInitializationContext"/> that will be invoked after initialization.</param> public void RegisterForPostInitialization(Action<GeneratorPostInitializationContext> callback) { CheckIsEmpty(InfoBuilder.PostInitCallback); InfoBuilder.PostInitCallback = (context) => callback(new GeneratorPostInitializationContext(context.AdditionalSources, context.CancellationToken)); } private static void CheckIsEmpty<T>(T x, string? typeName = null) where T : class? { if (x is object) { throw new InvalidOperationException(string.Format(CodeAnalysisResources.Single_type_per_generator_0, typeName ?? typeof(T).Name)); } } } /// <summary> /// Context passed to an <see cref="ISyntaxContextReceiver"/> when <see cref="ISyntaxContextReceiver.OnVisitSyntaxNode(GeneratorSyntaxContext)"/> is called /// </summary> public readonly struct GeneratorSyntaxContext { internal GeneratorSyntaxContext(SyntaxNode node, SemanticModel semanticModel) { Node = node; SemanticModel = semanticModel; } /// <summary> /// The <see cref="SyntaxNode"/> currently being visited /// </summary> public SyntaxNode Node { get; } /// <summary> /// The <see cref="CodeAnalysis.SemanticModel" /> that can be queried to obtain information about <see cref="Node"/>. /// </summary> public SemanticModel SemanticModel { get; } } /// <summary> /// Context passed to a source generator when it has opted-in to PostInitialization via <see cref="GeneratorInitializationContext.RegisterForPostInitialization(Action{GeneratorPostInitializationContext})"/> /// </summary> public readonly struct GeneratorPostInitializationContext { private readonly AdditionalSourcesCollection _additionalSources; internal GeneratorPostInitializationContext(AdditionalSourcesCollection additionalSources, CancellationToken cancellationToken) { _additionalSources = additionalSources; CancellationToken = cancellationToken; } /// <summary> /// A <see cref="System.Threading.CancellationToken"/> that can be checked to see if the PostInitialization should be cancelled. /// </summary> public CancellationToken CancellationToken { get; } /// <summary> /// Adds source code in the form of a <see cref="string"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="source">The source code to add to the compilation</param> public void AddSource(string hintName, string source) => AddSource(hintName, SourceText.From(source, Encoding.UTF8)); /// <summary> /// Adds a <see cref="SourceText"/> to the compilation that will be available during subsequent phases /// </summary> /// <param name="hintName">An identifier that can be used to reference this source text, must be unique within this generator</param> /// <param name="sourceText">The <see cref="SourceText"/> to add to the compilation</param> public void AddSource(string hintName, SourceText sourceText) => _additionalSources.Add(hintName, sourceText); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/Core/Portable/SolutionCrawler/Extensibility/IPerLanguageIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more 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.SolutionCrawler { internal interface IPerLanguageIncrementalAnalyzerProvider { IIncrementalAnalyzer CreatePerLanguageIncrementalAnalyzer(Workspace workspace, IIncrementalAnalyzerProvider provider); } }
// Licensed to the .NET Foundation under one or more 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.SolutionCrawler { internal interface IPerLanguageIncrementalAnalyzerProvider { IIncrementalAnalyzer CreatePerLanguageIncrementalAnalyzer(Workspace workspace, IIncrementalAnalyzerProvider provider); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Workspaces/Core/Portable/Serialization/SolutionReplicationContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Serialization { internal readonly struct SolutionReplicationContext : IDisposable { private readonly ArrayBuilder<IDisposable> _resources; private SolutionReplicationContext(ArrayBuilder<IDisposable> resources) => _resources = resources; public static SolutionReplicationContext Create() => new(ArrayBuilder<IDisposable>.GetInstance()); public void AddResource(IDisposable resource) => _resources.Add(resource); public void Dispose() { // TODO: https://github.com/dotnet/roslyn/issues/49973 // Currently we don't dispose resources, only keep them alive. // Shouldn't we dispose them? // _resources.All(resource => resource.Dispose()); _resources.Free(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Serialization { internal readonly struct SolutionReplicationContext : IDisposable { private readonly ArrayBuilder<IDisposable> _resources; private SolutionReplicationContext(ArrayBuilder<IDisposable> resources) => _resources = resources; public static SolutionReplicationContext Create() => new(ArrayBuilder<IDisposable>.GetInstance()); public void AddResource(IDisposable resource) => _resources.Add(resource); public void Dispose() { // TODO: https://github.com/dotnet/roslyn/issues/49973 // Currently we don't dispose resources, only keep them alive. // Shouldn't we dispose them? // _resources.All(resource => resource.Dispose()); _resources.Free(); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/InProcComponent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Windows; using System.Windows.Threading; using EnvDTE; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { /// <summary> /// Base class for all components that run inside of the Visual Studio process. /// <list type="bullet"> /// <item>Every in-proc component should provide a public, static, parameterless "Create" method. /// This will be called to construct the component in the VS process.</item> /// <item>Public methods on in-proc components should be instance methods to ensure that they are /// marshalled properly and execute in the VS process. Static methods will execute in the process /// in which they are called.</item> /// </list> /// </summary> internal abstract class InProcComponent : MarshalByRefObject { private static JoinableTaskFactory? _joinableTaskFactory; protected InProcComponent() { } private static Dispatcher CurrentApplicationDispatcher => Application.Current.Dispatcher; protected static JoinableTaskFactory JoinableTaskFactory { get { if (_joinableTaskFactory is null) { Interlocked.CompareExchange(ref _joinableTaskFactory, ThreadHelper.JoinableTaskFactory.WithPriority(CurrentApplicationDispatcher, DispatcherPriority.Background), null); } return _joinableTaskFactory; } } protected static void InvokeOnUIThread(Action<CancellationToken> action) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); var operation = JoinableTaskFactory.RunAsync(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); action(cancellationTokenSource.Token); }); operation.Task.Wait(cancellationTokenSource.Token); } protected static T InvokeOnUIThread<T>(Func<CancellationToken, T> action) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); var operation = JoinableTaskFactory.RunAsync(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); return action(cancellationTokenSource.Token); }); operation.Task.Wait(cancellationTokenSource.Token); return operation.Task.Result; } protected static TInterface GetGlobalService<TService, TInterface>() where TService : class where TInterface : class => InvokeOnUIThread(cancellationToken => (TInterface)ServiceProvider.GlobalProvider.GetService(typeof(TService))); protected static TService GetComponentModelService<TService>() where TService : class => InvokeOnUIThread(cancellationToken => GetComponentModel().GetService<TService>()); protected static DTE GetDTE() => GetGlobalService<SDTE, DTE>(); protected static IComponentModel GetComponentModel() => GetGlobalService<SComponentModel, IComponentModel>(); protected static bool IsCommandAvailable(string commandName) => GetDTE().Commands.Item(commandName).IsAvailable; protected static void ExecuteCommand(string commandName, string args = "") { var task = Task.Run(() => GetDTE().ExecuteCommand(commandName, args)); task.Wait(Helper.HangMitigatingTimeout); } /// <summary> /// Waiting for the application to 'idle' means that it is done pumping messages (including WM_PAINT). /// </summary> protected static void WaitForApplicationIdle(TimeSpan timeout) #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs => CurrentApplicationDispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle).Wait(timeout); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs protected static void WaitForSystemIdle() #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs => CurrentApplicationDispatcher.Invoke(() => { }, DispatcherPriority.SystemIdle); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs // Ensure InProcComponents live forever public override object? InitializeLifetimeService() => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Windows; using System.Windows.Threading; using EnvDTE; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { /// <summary> /// Base class for all components that run inside of the Visual Studio process. /// <list type="bullet"> /// <item>Every in-proc component should provide a public, static, parameterless "Create" method. /// This will be called to construct the component in the VS process.</item> /// <item>Public methods on in-proc components should be instance methods to ensure that they are /// marshalled properly and execute in the VS process. Static methods will execute in the process /// in which they are called.</item> /// </list> /// </summary> internal abstract class InProcComponent : MarshalByRefObject { private static JoinableTaskFactory? _joinableTaskFactory; protected InProcComponent() { } private static Dispatcher CurrentApplicationDispatcher => Application.Current.Dispatcher; protected static JoinableTaskFactory JoinableTaskFactory { get { if (_joinableTaskFactory is null) { Interlocked.CompareExchange(ref _joinableTaskFactory, ThreadHelper.JoinableTaskFactory.WithPriority(CurrentApplicationDispatcher, DispatcherPriority.Background), null); } return _joinableTaskFactory; } } protected static void InvokeOnUIThread(Action<CancellationToken> action) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); var operation = JoinableTaskFactory.RunAsync(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); action(cancellationTokenSource.Token); }); operation.Task.Wait(cancellationTokenSource.Token); } protected static T InvokeOnUIThread<T>(Func<CancellationToken, T> action) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); var operation = JoinableTaskFactory.RunAsync(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); return action(cancellationTokenSource.Token); }); operation.Task.Wait(cancellationTokenSource.Token); return operation.Task.Result; } protected static TInterface GetGlobalService<TService, TInterface>() where TService : class where TInterface : class => InvokeOnUIThread(cancellationToken => (TInterface)ServiceProvider.GlobalProvider.GetService(typeof(TService))); protected static TService GetComponentModelService<TService>() where TService : class => InvokeOnUIThread(cancellationToken => GetComponentModel().GetService<TService>()); protected static DTE GetDTE() => GetGlobalService<SDTE, DTE>(); protected static IComponentModel GetComponentModel() => GetGlobalService<SComponentModel, IComponentModel>(); protected static bool IsCommandAvailable(string commandName) => GetDTE().Commands.Item(commandName).IsAvailable; protected static void ExecuteCommand(string commandName, string args = "") { var task = Task.Run(() => GetDTE().ExecuteCommand(commandName, args)); task.Wait(Helper.HangMitigatingTimeout); } /// <summary> /// Waiting for the application to 'idle' means that it is done pumping messages (including WM_PAINT). /// </summary> protected static void WaitForApplicationIdle(TimeSpan timeout) #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs => CurrentApplicationDispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle).Wait(timeout); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs protected static void WaitForSystemIdle() #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs => CurrentApplicationDispatcher.Invoke(() => { }, DispatcherPriority.SystemIdle); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs // Ensure InProcComponents live forever public override object? InitializeLifetimeService() => null; } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/EditorFeatures/Core/Implementation/InlineRename/AbstractEditorInlineRenameService.FailureInlineRenameInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractEditorInlineRenameService { private class FailureInlineRenameInfo : IInlineRenameInfo { public FailureInlineRenameInfo(string localizedErrorMessage) => this.LocalizedErrorMessage = localizedErrorMessage; public bool CanRename => false; public bool HasOverloads => false; public bool ForceRenameOverloads => false; public string LocalizedErrorMessage { get; } public TextSpan TriggerSpan => default; public string DisplayName => null; public string FullDisplayName => null; public Glyph Glyph => Glyph.None; public ImmutableArray<DocumentSpan> DefinitionLocations => default; public string GetFinalSymbolName(string replacementText) => null; public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) => default; public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) => null; public Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) => Task.FromResult<IInlineRenameLocationSet>(null); public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => false; public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractEditorInlineRenameService { private class FailureInlineRenameInfo : IInlineRenameInfo { public FailureInlineRenameInfo(string localizedErrorMessage) => this.LocalizedErrorMessage = localizedErrorMessage; public bool CanRename => false; public bool HasOverloads => false; public bool ForceRenameOverloads => false; public string LocalizedErrorMessage { get; } public TextSpan TriggerSpan => default; public string DisplayName => null; public string FullDisplayName => null; public Glyph Glyph => Glyph.None; public ImmutableArray<DocumentSpan> DefinitionLocations => default; public string GetFinalSymbolName(string replacementText) => null; public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) => default; public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) => null; public Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) => Task.FromResult<IInlineRenameLocationSet>(null); public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => false; public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) => false; } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Features/Core/Portable/RQName/Nodes/RQVoidType.cs
// Licensed to the .NET Foundation under one or more 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.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQVoidType : RQType { public static readonly RQVoidType Singleton = new(); private RQVoidType() { } public override SimpleTreeNode ToSimpleTree() => new SimpleLeafNode(RQNameStrings.Void); } }
// Licensed to the .NET Foundation under one or more 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.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQVoidType : RQType { public static readonly RQVoidType Singleton = new(); private RQVoidType() { } public override SimpleTreeNode ToSimpleTree() => new SimpleLeafNode(RQNameStrings.Void); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/CSharpFormatEngine.cs
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class CSharpFormatEngine : AbstractFormatEngine { public CSharpFormatEngine( SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken token1, SyntaxToken token2) : base(TreeData.Create(node), options, formattingRules, token1, token2) { } internal override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override AbstractTriviaDataFactory CreateTriviaFactory() => new TriviaDataFactory(this.TreeData, this.Options); protected override AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream) => new FormattingResult(this.TreeData, tokenStream, this.SpanToFormat); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class CSharpFormatEngine : AbstractFormatEngine { public CSharpFormatEngine( SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken token1, SyntaxToken token2) : base(TreeData.Create(node), options, formattingRules, token1, token2) { } internal override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override AbstractTriviaDataFactory CreateTriviaFactory() => new TriviaDataFactory(this.TreeData, this.Options); protected override AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream) => new FormattingResult(this.TreeData, tokenStream, this.SpanToFormat); } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/CSharp/Portable/Symbols/UnboundGenericType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class TypeSymbolExtensions { public static NamedTypeSymbol AsUnboundGenericType(this NamedTypeSymbol type) { if (!type.IsGenericType) { // This exception is part of the public contract of NamedTypeSymbol.ConstructUnboundGenericType throw new InvalidOperationException(); } var original = type.OriginalDefinition; int n = original.Arity; NamedTypeSymbol originalContainingType = original.ContainingType; var constructedFrom = ((object)originalContainingType == null) ? original : original.AsMember(originalContainingType.IsGenericType ? originalContainingType.AsUnboundGenericType() : originalContainingType); if (n == 0) { return constructedFrom; } var typeArguments = UnboundArgumentErrorTypeSymbol.CreateTypeArguments( constructedFrom.TypeParameters, n, new CSDiagnosticInfo(ErrorCode.ERR_UnexpectedUnboundGenericName)); return constructedFrom.Construct(typeArguments, unbound: true); } } internal sealed class UnboundArgumentErrorTypeSymbol : ErrorTypeSymbol { public static ImmutableArray<TypeWithAnnotations> CreateTypeArguments(ImmutableArray<TypeParameterSymbol> typeParameters, int n, DiagnosticInfo errorInfo) { var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(); for (int i = 0; i < n; i++) { string name = (i < typeParameters.Length) ? typeParameters[i].Name : string.Empty; result.Add(TypeWithAnnotations.Create(new UnboundArgumentErrorTypeSymbol(name, errorInfo))); } return result.ToImmutableAndFree(); } public static readonly ErrorTypeSymbol Instance = new UnboundArgumentErrorTypeSymbol(string.Empty, new CSDiagnosticInfo(ErrorCode.ERR_UnexpectedUnboundGenericName)); private readonly string _name; private readonly DiagnosticInfo _errorInfo; private UnboundArgumentErrorTypeSymbol(string name, DiagnosticInfo errorInfo, TupleExtraData? tupleData = null) : base(tupleData) { _name = name; _errorInfo = errorInfo; } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { return new UnboundArgumentErrorTypeSymbol(_name, _errorInfo, newData); } public override string Name { get { return _name; } } internal override bool MangleName { get { Debug.Assert(Arity == 0); return false; } } internal override DiagnosticInfo ErrorInfo { get { return _errorInfo; } } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if ((object)t2 == (object)this) { return true; } UnboundArgumentErrorTypeSymbol? other = t2 as UnboundArgumentErrorTypeSymbol; return (object?)other != null && string.Equals(other._name, _name, StringComparison.Ordinal) && object.Equals(other._errorInfo, _errorInfo); } public override int GetHashCode() { return _errorInfo == null ? _name.GetHashCode() : Hash.Combine(_name, _errorInfo.Code); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static partial class TypeSymbolExtensions { public static NamedTypeSymbol AsUnboundGenericType(this NamedTypeSymbol type) { if (!type.IsGenericType) { // This exception is part of the public contract of NamedTypeSymbol.ConstructUnboundGenericType throw new InvalidOperationException(); } var original = type.OriginalDefinition; int n = original.Arity; NamedTypeSymbol originalContainingType = original.ContainingType; var constructedFrom = ((object)originalContainingType == null) ? original : original.AsMember(originalContainingType.IsGenericType ? originalContainingType.AsUnboundGenericType() : originalContainingType); if (n == 0) { return constructedFrom; } var typeArguments = UnboundArgumentErrorTypeSymbol.CreateTypeArguments( constructedFrom.TypeParameters, n, new CSDiagnosticInfo(ErrorCode.ERR_UnexpectedUnboundGenericName)); return constructedFrom.Construct(typeArguments, unbound: true); } } internal sealed class UnboundArgumentErrorTypeSymbol : ErrorTypeSymbol { public static ImmutableArray<TypeWithAnnotations> CreateTypeArguments(ImmutableArray<TypeParameterSymbol> typeParameters, int n, DiagnosticInfo errorInfo) { var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(); for (int i = 0; i < n; i++) { string name = (i < typeParameters.Length) ? typeParameters[i].Name : string.Empty; result.Add(TypeWithAnnotations.Create(new UnboundArgumentErrorTypeSymbol(name, errorInfo))); } return result.ToImmutableAndFree(); } public static readonly ErrorTypeSymbol Instance = new UnboundArgumentErrorTypeSymbol(string.Empty, new CSDiagnosticInfo(ErrorCode.ERR_UnexpectedUnboundGenericName)); private readonly string _name; private readonly DiagnosticInfo _errorInfo; private UnboundArgumentErrorTypeSymbol(string name, DiagnosticInfo errorInfo, TupleExtraData? tupleData = null) : base(tupleData) { _name = name; _errorInfo = errorInfo; } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { return new UnboundArgumentErrorTypeSymbol(_name, _errorInfo, newData); } public override string Name { get { return _name; } } internal override bool MangleName { get { Debug.Assert(Arity == 0); return false; } } internal override DiagnosticInfo ErrorInfo { get { return _errorInfo; } } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if ((object)t2 == (object)this) { return true; } UnboundArgumentErrorTypeSymbol? other = t2 as UnboundArgumentErrorTypeSymbol; return (object?)other != null && string.Equals(other._name, _name, StringComparison.Ordinal) && object.Equals(other._errorInfo, _errorInfo); } public override int GetHashCode() { return _errorInfo == null ? _name.GetHashCode() : Hash.Combine(_name, _errorInfo.Code); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/CSharp/Portable/Compilation/DeconstructionInfo.cs
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.CSharp { // Deconstructions are represented internally as a tree of conversions, but // since they are not conversions from the language perspective we use a wrapper to // abstract the public API from the implementation. /// <summary> /// The representation of a deconstruction as a tree of Deconstruct methods and conversions. /// Methods only appear in non-terminal nodes. All terminal nodes have a Conversion. /// /// Here's an example: /// A deconstruction like <c>(int x1, (long x2, long x3)) = deconstructable1</c> with /// <c>Deconstructable1.Deconstruct(out int y1, out Deconstructable2 y2)</c> and /// <c>Deconstructable2.Deconstruct(out int z1, out int z2)</c> is represented as 5 DeconstructionInfo nodes. /// /// The top-level node has a <see cref="Method"/> (Deconstructable1.Deconstruct), no <see cref="Conversion"/>, but has two <see cref="Nested"/> nodes. /// Its first nested node has no <see cref="Method"/>, but has a <see cref="Conversion"/> (Identity). /// Its second nested node has a <see cref="Method"/> (Deconstructable2.Deconstruct), no <see cref="Conversion"/>, and two <see cref="Nested"/> nodes. /// Those last two nested nodes have no <see cref="Method"/>, but each have a <see cref="Conversion"/> (ImplicitNumeric, from int to long). /// </summary> public struct DeconstructionInfo { private readonly Conversion _conversion; /// <summary> /// The Deconstruct method (if any) for this non-terminal position in the deconstruction tree. /// </summary> public IMethodSymbol? Method { get { return _conversion.Kind == ConversionKind.Deconstruction ? _conversion.MethodSymbol : null; } } /// <summary> /// The conversion for a terminal position in the deconstruction tree. /// </summary> public Conversion? Conversion { get { return _conversion.Kind == ConversionKind.Deconstruction ? null : (Conversion?)_conversion; } } /// <summary> /// The children for this deconstruction node. /// </summary> public ImmutableArray<DeconstructionInfo> Nested { get { var underlyingConversions = _conversion.UnderlyingConversions; return underlyingConversions.IsDefault ? ImmutableArray<DeconstructionInfo>.Empty : underlyingConversions.SelectAsArray(c => new DeconstructionInfo(c)); } } internal DeconstructionInfo(Conversion conversion) { _conversion = conversion; } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.CSharp { // Deconstructions are represented internally as a tree of conversions, but // since they are not conversions from the language perspective we use a wrapper to // abstract the public API from the implementation. /// <summary> /// The representation of a deconstruction as a tree of Deconstruct methods and conversions. /// Methods only appear in non-terminal nodes. All terminal nodes have a Conversion. /// /// Here's an example: /// A deconstruction like <c>(int x1, (long x2, long x3)) = deconstructable1</c> with /// <c>Deconstructable1.Deconstruct(out int y1, out Deconstructable2 y2)</c> and /// <c>Deconstructable2.Deconstruct(out int z1, out int z2)</c> is represented as 5 DeconstructionInfo nodes. /// /// The top-level node has a <see cref="Method"/> (Deconstructable1.Deconstruct), no <see cref="Conversion"/>, but has two <see cref="Nested"/> nodes. /// Its first nested node has no <see cref="Method"/>, but has a <see cref="Conversion"/> (Identity). /// Its second nested node has a <see cref="Method"/> (Deconstructable2.Deconstruct), no <see cref="Conversion"/>, and two <see cref="Nested"/> nodes. /// Those last two nested nodes have no <see cref="Method"/>, but each have a <see cref="Conversion"/> (ImplicitNumeric, from int to long). /// </summary> public struct DeconstructionInfo { private readonly Conversion _conversion; /// <summary> /// The Deconstruct method (if any) for this non-terminal position in the deconstruction tree. /// </summary> public IMethodSymbol? Method { get { return _conversion.Kind == ConversionKind.Deconstruction ? _conversion.MethodSymbol : null; } } /// <summary> /// The conversion for a terminal position in the deconstruction tree. /// </summary> public Conversion? Conversion { get { return _conversion.Kind == ConversionKind.Deconstruction ? null : (Conversion?)_conversion; } } /// <summary> /// The children for this deconstruction node. /// </summary> public ImmutableArray<DeconstructionInfo> Nested { get { var underlyingConversions = _conversion.UnderlyingConversions; return underlyingConversions.IsDefault ? ImmutableArray<DeconstructionInfo>.Empty : underlyingConversions.SelectAsArray(c => new DeconstructionInfo(c)); } } internal DeconstructionInfo(Conversion conversion) { _conversion = conversion; } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Tools/ExternalAccess/OmniSharp/ImplementType/OmniSharpImplementTypeOptions.cs
// Licensed to the .NET Foundation under one or more 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.ImplementType; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ImplementType { internal static class OmniSharpImplementTypeOptions { public static OmniSharpImplementTypeInsertionBehavior GetInsertionBehavior(OptionSet options, string language) => (OmniSharpImplementTypeInsertionBehavior)options.GetOption(ImplementTypeOptions.InsertionBehavior, language); public static OptionSet SetInsertionBehavior(OptionSet options, string language, OmniSharpImplementTypeInsertionBehavior value) => options.WithChangedOption(ImplementTypeOptions.InsertionBehavior, language, (ImplementTypeInsertionBehavior)value); public static OmniSharpImplementTypePropertyGenerationBehavior GetPropertyGenerationBehavior(OptionSet options, string language) => (OmniSharpImplementTypePropertyGenerationBehavior)options.GetOption(ImplementTypeOptions.PropertyGenerationBehavior, language); public static OptionSet SetPropertyGenerationBehavior(OptionSet options, string language, OmniSharpImplementTypePropertyGenerationBehavior value) => options.WithChangedOption(ImplementTypeOptions.PropertyGenerationBehavior, language, (ImplementTypePropertyGenerationBehavior)value); } internal enum OmniSharpImplementTypeInsertionBehavior { WithOtherMembersOfTheSameKind = ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, AtTheEnd = ImplementTypeInsertionBehavior.AtTheEnd, } internal enum OmniSharpImplementTypePropertyGenerationBehavior { PreferThrowingProperties = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, PreferAutoProperties = ImplementTypePropertyGenerationBehavior.PreferAutoProperties, } }
// Licensed to the .NET Foundation under one or more 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.ImplementType; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.ImplementType { internal static class OmniSharpImplementTypeOptions { public static OmniSharpImplementTypeInsertionBehavior GetInsertionBehavior(OptionSet options, string language) => (OmniSharpImplementTypeInsertionBehavior)options.GetOption(ImplementTypeOptions.InsertionBehavior, language); public static OptionSet SetInsertionBehavior(OptionSet options, string language, OmniSharpImplementTypeInsertionBehavior value) => options.WithChangedOption(ImplementTypeOptions.InsertionBehavior, language, (ImplementTypeInsertionBehavior)value); public static OmniSharpImplementTypePropertyGenerationBehavior GetPropertyGenerationBehavior(OptionSet options, string language) => (OmniSharpImplementTypePropertyGenerationBehavior)options.GetOption(ImplementTypeOptions.PropertyGenerationBehavior, language); public static OptionSet SetPropertyGenerationBehavior(OptionSet options, string language, OmniSharpImplementTypePropertyGenerationBehavior value) => options.WithChangedOption(ImplementTypeOptions.PropertyGenerationBehavior, language, (ImplementTypePropertyGenerationBehavior)value); } internal enum OmniSharpImplementTypeInsertionBehavior { WithOtherMembersOfTheSameKind = ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, AtTheEnd = ImplementTypeInsertionBehavior.AtTheEnd, } internal enum OmniSharpImplementTypePropertyGenerationBehavior { PreferThrowingProperties = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, PreferAutoProperties = ImplementTypePropertyGenerationBehavior.PreferAutoProperties, } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Scripting/Core/ScriptOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; /// <summary> /// Options for creating and running scripts. /// </summary> public sealed class ScriptOptions { public static ScriptOptions Default { get; } = new ScriptOptions( filePath: string.Empty, references: GetDefaultMetadataReferences(), namespaces: ImmutableArray<string>.Empty, metadataResolver: ScriptMetadataResolver.Default, sourceResolver: SourceFileResolver.Default, emitDebugInformation: false, fileEncoding: null, OptimizationLevel.Debug, checkOverflow: false, allowUnsafe: true, warningLevel: 4, parseOptions: null); private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences() { if (GacFileResolver.IsAvailable) { return ImmutableArray<MetadataReference>.Empty; } // These references are resolved lazily. Keep in sync with list in core csi.rsp. var files = new[] { "System.Collections", "System.Collections.Concurrent", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.Process", "System.Diagnostics.StackTrace", "System.Globalization", "System.IO", "System.IO.FileSystem", "System.IO.FileSystem.Primitives", "System.Reflection", "System.Reflection.Extensions", "System.Reflection.Primitives", "System.Runtime", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Text.Encoding", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.ValueTuple", }; return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference)); } /// <summary> /// An array of <see cref="MetadataReference"/>s to be added to the script. /// </summary> /// <remarks> /// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>). /// Unresolved references are resolved when the script is about to be executed /// (<see cref="Script.RunAsync(object, CancellationToken)"/>. /// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>. /// </remarks> public ImmutableArray<MetadataReference> MetadataReferences { get; private set; } /// <summary> /// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives. /// </summary> public MetadataReferenceResolver MetadataResolver { get; private set; } /// <summary> /// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive. /// </summary> public SourceReferenceResolver SourceResolver { get; private set; } /// <summary> /// The namespaces, static classes and aliases imported by the script. /// </summary> public ImmutableArray<string> Imports { get; private set; } /// <summary> /// Specifies whether debugging symbols should be emitted. /// </summary> public bool EmitDebugInformation { get; private set; } = false; /// <summary> /// Specifies the encoding to be used when debugging scripts loaded from a file, or saved to a file for debugging purposes. /// If it's null, the compiler will attempt to detect the necessary encoding for debugging /// </summary> public Encoding FileEncoding { get; private set; } /// <summary> /// The path to the script source if it originated from a file, empty otherwise. /// </summary> public string FilePath { get; private set; } /// <summary> /// Specifies whether or not optimizations should be performed on the output IL. /// </summary> public OptimizationLevel OptimizationLevel { get; private set; } /// <summary> /// Whether bounds checking on integer arithmetic is enforced by default or not. /// </summary> public bool CheckOverflow { get; private set; } /// <summary> /// Allow unsafe regions (i.e. unsafe modifiers on members and unsafe blocks). /// </summary> public bool AllowUnsafe { get; private set; } /// <summary> /// Global warning level (from 0 to 4). /// </summary> public int WarningLevel { get; private set; } internal ParseOptions ParseOptions { get; private set; } internal ScriptOptions( string filePath, ImmutableArray<MetadataReference> references, ImmutableArray<string> namespaces, MetadataReferenceResolver metadataResolver, SourceReferenceResolver sourceResolver, bool emitDebugInformation, Encoding fileEncoding, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, int warningLevel, ParseOptions parseOptions) { Debug.Assert(filePath != null); Debug.Assert(!references.IsDefault); Debug.Assert(!namespaces.IsDefault); Debug.Assert(metadataResolver != null); Debug.Assert(sourceResolver != null); FilePath = filePath; MetadataReferences = references; Imports = namespaces; MetadataResolver = metadataResolver; SourceResolver = sourceResolver; EmitDebugInformation = emitDebugInformation; FileEncoding = fileEncoding; OptimizationLevel = optimizationLevel; CheckOverflow = checkOverflow; AllowUnsafe = allowUnsafe; WarningLevel = warningLevel; ParseOptions = parseOptions; } private ScriptOptions(ScriptOptions other) : this(filePath: other.FilePath, references: other.MetadataReferences, namespaces: other.Imports, metadataResolver: other.MetadataResolver, sourceResolver: other.SourceResolver, emitDebugInformation: other.EmitDebugInformation, fileEncoding: other.FileEncoding, optimizationLevel: other.OptimizationLevel, checkOverflow: other.CheckOverflow, allowUnsafe: other.AllowUnsafe, warningLevel: other.WarningLevel, parseOptions: other.ParseOptions) { } // a reference to an assembly should by default be equivalent to #r, which applies recursive global alias: private static readonly MetadataReferenceProperties s_assemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithRecursiveAliases(true); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed. /// </summary> public ScriptOptions WithFilePath(string filePath) => (FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" }; private static MetadataReference CreateUnresolvedReference(string reference) => new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) => MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) => WithReferences(ToImmutableArrayChecked(references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params MetadataReference[] references) => WithReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) => WithReferences(ConcatChecked(MetadataReferences, references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params MetadataReference[] references) => AddReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(IEnumerable<Assembly> references) => WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(params Assembly[] references) => WithReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(IEnumerable<Assembly> references) => AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); private static MetadataReference CreateReferenceFromAssembly(Assembly assembly) { return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties); } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(params Assembly[] references) => AddReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<string> references) => WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params string[] references) => WithReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<string> references) => AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params string[] references) => AddReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>. /// </summary> public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) => MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>. /// </summary> public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) => SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> private ScriptOptions WithImports(ImmutableArray<string> imports) => Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(IEnumerable<string> imports) => WithImports(ToImmutableArrayChecked(imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(params string[] imports) => WithImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(IEnumerable<string> imports) => WithImports(ConcatChecked(Imports, imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(params string[] imports) => AddImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with debugging information enabled. /// </summary> public ScriptOptions WithEmitDebugInformation(bool emitDebugInformation) => emitDebugInformation == EmitDebugInformation ? this : new ScriptOptions(this) { EmitDebugInformation = emitDebugInformation }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="FileEncoding"/>. /// </summary> public ScriptOptions WithFileEncoding(Encoding encoding) => encoding == FileEncoding ? this : new ScriptOptions(this) { FileEncoding = encoding }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>. /// </summary> /// <returns></returns> public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) => optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this) { OptimizationLevel = optimizationLevel }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with unsafe code regions allowed. /// </summary> public ScriptOptions WithAllowUnsafe(bool allowUnsafe) => allowUnsafe == AllowUnsafe ? this : new ScriptOptions(this) { AllowUnsafe = allowUnsafe }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with bounds checking on integer arithmetic enforced. /// </summary> public ScriptOptions WithCheckOverflow(bool checkOverflow) => checkOverflow == CheckOverflow ? this : new ScriptOptions(this) { CheckOverflow = checkOverflow }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with the specific <see cref="WarningLevel"/>. /// </summary> public ScriptOptions WithWarningLevel(int warningLevel) => warningLevel == WarningLevel ? this : new ScriptOptions(this) { WarningLevel = warningLevel }; internal ScriptOptions WithParseOptions(ParseOptions parseOptions) => parseOptions == ParseOptions ? this : new ScriptOptions(this) { ParseOptions = parseOptions }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; /// <summary> /// Options for creating and running scripts. /// </summary> public sealed class ScriptOptions { public static ScriptOptions Default { get; } = new ScriptOptions( filePath: string.Empty, references: GetDefaultMetadataReferences(), namespaces: ImmutableArray<string>.Empty, metadataResolver: ScriptMetadataResolver.Default, sourceResolver: SourceFileResolver.Default, emitDebugInformation: false, fileEncoding: null, OptimizationLevel.Debug, checkOverflow: false, allowUnsafe: true, warningLevel: 4, parseOptions: null); private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences() { if (GacFileResolver.IsAvailable) { return ImmutableArray<MetadataReference>.Empty; } // These references are resolved lazily. Keep in sync with list in core csi.rsp. var files = new[] { "System.Collections", "System.Collections.Concurrent", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.Process", "System.Diagnostics.StackTrace", "System.Globalization", "System.IO", "System.IO.FileSystem", "System.IO.FileSystem.Primitives", "System.Reflection", "System.Reflection.Extensions", "System.Reflection.Primitives", "System.Runtime", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Text.Encoding", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.ValueTuple", }; return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference)); } /// <summary> /// An array of <see cref="MetadataReference"/>s to be added to the script. /// </summary> /// <remarks> /// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>). /// Unresolved references are resolved when the script is about to be executed /// (<see cref="Script.RunAsync(object, CancellationToken)"/>. /// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>. /// </remarks> public ImmutableArray<MetadataReference> MetadataReferences { get; private set; } /// <summary> /// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives. /// </summary> public MetadataReferenceResolver MetadataResolver { get; private set; } /// <summary> /// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive. /// </summary> public SourceReferenceResolver SourceResolver { get; private set; } /// <summary> /// The namespaces, static classes and aliases imported by the script. /// </summary> public ImmutableArray<string> Imports { get; private set; } /// <summary> /// Specifies whether debugging symbols should be emitted. /// </summary> public bool EmitDebugInformation { get; private set; } = false; /// <summary> /// Specifies the encoding to be used when debugging scripts loaded from a file, or saved to a file for debugging purposes. /// If it's null, the compiler will attempt to detect the necessary encoding for debugging /// </summary> public Encoding FileEncoding { get; private set; } /// <summary> /// The path to the script source if it originated from a file, empty otherwise. /// </summary> public string FilePath { get; private set; } /// <summary> /// Specifies whether or not optimizations should be performed on the output IL. /// </summary> public OptimizationLevel OptimizationLevel { get; private set; } /// <summary> /// Whether bounds checking on integer arithmetic is enforced by default or not. /// </summary> public bool CheckOverflow { get; private set; } /// <summary> /// Allow unsafe regions (i.e. unsafe modifiers on members and unsafe blocks). /// </summary> public bool AllowUnsafe { get; private set; } /// <summary> /// Global warning level (from 0 to 4). /// </summary> public int WarningLevel { get; private set; } internal ParseOptions ParseOptions { get; private set; } internal ScriptOptions( string filePath, ImmutableArray<MetadataReference> references, ImmutableArray<string> namespaces, MetadataReferenceResolver metadataResolver, SourceReferenceResolver sourceResolver, bool emitDebugInformation, Encoding fileEncoding, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, int warningLevel, ParseOptions parseOptions) { Debug.Assert(filePath != null); Debug.Assert(!references.IsDefault); Debug.Assert(!namespaces.IsDefault); Debug.Assert(metadataResolver != null); Debug.Assert(sourceResolver != null); FilePath = filePath; MetadataReferences = references; Imports = namespaces; MetadataResolver = metadataResolver; SourceResolver = sourceResolver; EmitDebugInformation = emitDebugInformation; FileEncoding = fileEncoding; OptimizationLevel = optimizationLevel; CheckOverflow = checkOverflow; AllowUnsafe = allowUnsafe; WarningLevel = warningLevel; ParseOptions = parseOptions; } private ScriptOptions(ScriptOptions other) : this(filePath: other.FilePath, references: other.MetadataReferences, namespaces: other.Imports, metadataResolver: other.MetadataResolver, sourceResolver: other.SourceResolver, emitDebugInformation: other.EmitDebugInformation, fileEncoding: other.FileEncoding, optimizationLevel: other.OptimizationLevel, checkOverflow: other.CheckOverflow, allowUnsafe: other.AllowUnsafe, warningLevel: other.WarningLevel, parseOptions: other.ParseOptions) { } // a reference to an assembly should by default be equivalent to #r, which applies recursive global alias: private static readonly MetadataReferenceProperties s_assemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithRecursiveAliases(true); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed. /// </summary> public ScriptOptions WithFilePath(string filePath) => (FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" }; private static MetadataReference CreateUnresolvedReference(string reference) => new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) => MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) => WithReferences(ToImmutableArrayChecked(references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params MetadataReference[] references) => WithReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) => WithReferences(ConcatChecked(MetadataReferences, references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params MetadataReference[] references) => AddReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(IEnumerable<Assembly> references) => WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(params Assembly[] references) => WithReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(IEnumerable<Assembly> references) => AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); private static MetadataReference CreateReferenceFromAssembly(Assembly assembly) { return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties); } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(params Assembly[] references) => AddReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<string> references) => WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params string[] references) => WithReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<string> references) => AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params string[] references) => AddReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>. /// </summary> public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) => MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>. /// </summary> public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) => SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> private ScriptOptions WithImports(ImmutableArray<string> imports) => Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(IEnumerable<string> imports) => WithImports(ToImmutableArrayChecked(imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(params string[] imports) => WithImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(IEnumerable<string> imports) => WithImports(ConcatChecked(Imports, imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(params string[] imports) => AddImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with debugging information enabled. /// </summary> public ScriptOptions WithEmitDebugInformation(bool emitDebugInformation) => emitDebugInformation == EmitDebugInformation ? this : new ScriptOptions(this) { EmitDebugInformation = emitDebugInformation }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="FileEncoding"/>. /// </summary> public ScriptOptions WithFileEncoding(Encoding encoding) => encoding == FileEncoding ? this : new ScriptOptions(this) { FileEncoding = encoding }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>. /// </summary> /// <returns></returns> public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) => optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this) { OptimizationLevel = optimizationLevel }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with unsafe code regions allowed. /// </summary> public ScriptOptions WithAllowUnsafe(bool allowUnsafe) => allowUnsafe == AllowUnsafe ? this : new ScriptOptions(this) { AllowUnsafe = allowUnsafe }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with bounds checking on integer arithmetic enforced. /// </summary> public ScriptOptions WithCheckOverflow(bool checkOverflow) => checkOverflow == CheckOverflow ? this : new ScriptOptions(this) { CheckOverflow = checkOverflow }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with the specific <see cref="WarningLevel"/>. /// </summary> public ScriptOptions WithWarningLevel(int warningLevel) => warningLevel == WarningLevel ? this : new ScriptOptions(this) { WarningLevel = warningLevel }; internal ScriptOptions WithParseOptions(ParseOptions parseOptions) => parseOptions == ParseOptions ? this : new ScriptOptions(this) { ParseOptions = parseOptions }; } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/CSharp/Test/Semantic/Semantics/BetterCandidates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Linq; using System.Diagnostics; using System.Collections; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests for improved overload candidate selection. /// See also https://github.com/dotnet/csharplang/issues/98. /// </summary> public class BetterCandidates : CompilingTestBase { private CSharpCompilation CreateCompilationWithoutBetterCandidates(string source, CSharpCompilationOptions options = null, MetadataReference[] references = null) { return CreateCompilation(source, options: options, references: references, parseOptions: TestOptions.WithoutImprovedOverloadCandidates); } private CSharpCompilation CreateCompilationWithBetterCandidates(string source, CSharpCompilationOptions options = null, MetadataReference[] references = null) { Debug.Assert(TestOptions.Regular.LanguageVersion >= MessageID.IDS_FeatureImprovedOverloadCandidates.RequiredVersion()); return CreateCompilation(source, options: options, references: references, parseOptions: TestOptions.Regular); } //When a method group contains both instance and static members, we discard the instance members if invoked with a static receiver. [Fact] public void TestStaticReceiver01() { var source = @"class Program { public static void Main() { Program.M(null); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // Program.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver01() { var source = @"class Program { public static void Main() { Program p = new Program(); p.M(null); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,11): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // p.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 11) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver02() { var source = @"class Program { public static void Main() { Program p = new Program(); p.Main2(); } void Main2() { this.M(null); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (10,14): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // this.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(10, 14) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver02b() { var source = @"class Program { public static void Main() { D d = new D(); d.Main2(); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class D : Program { public void Main2() { base.M(null); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (15,14): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // base.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(15, 14) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver03() { var source = @"class Program { public static void Main() { new MyCollection { null }; } } class A {} class B {} class MyCollection : System.Collections.IEnumerable { public static void Add(A a) { System.Console.WriteLine(1); } public void Add(B b) { System.Console.WriteLine(2); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new System.NotImplementedException(); } } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,28): error CS0121: The call is ambiguous between the following methods or properties: 'MyCollection.Add(A)' and 'MyCollection.Add(B)' // new MyCollection { null }; Diagnostic(ErrorCode.ERR_AmbigCall, "null").WithArguments("MyCollection.Add(A)", "MyCollection.Add(B)").WithLocation(5, 28) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver04() { var source = @"class Program { public static void Main() { var c = new MyCollection(); foreach (var q in c) { } } } class A {} class B {} class MyCollection : System.Collections.IEnumerable { public static System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { System.Console.Write(1); return new MyEnumerator(); } } class MyEnumerator : System.Collections.IEnumerator { object System.Collections.IEnumerator.Current => throw null; bool System.Collections.IEnumerator.MoveNext() { System.Console.WriteLine(2); return false; } void System.Collections.IEnumerator.Reset() => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,27): warning CS0279: 'MyCollection' does not implement the 'collection' pattern. 'MyCollection.GetEnumerator()' is not a public instance or extension method. // foreach (var q in c) { } Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "c").WithArguments("MyCollection", "collection", "MyCollection.GetEnumerator()").WithLocation(6, 27) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "12"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver05() { var source = @"class Program { public static void Main() { var c = new MyCollection(); foreach (var q in c) { } } } class A {} class B {} class MyCollection { public MyEnumerator GetEnumerator() { return new MyEnumerator(); } } class MyEnumerator { public object Current => throw null; public bool MoveNext() { System.Console.WriteLine(2); return false; } public static bool MoveNext() => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (26,24): error CS0111: Type 'MyEnumerator' already defines a member called 'MoveNext' with the same parameter types // public static bool MoveNext() => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "MoveNext").WithArguments("MoveNext", "MyEnumerator").WithLocation(26, 24), // (6,27): error CS0202: foreach requires that the return type 'MyEnumerator' of 'MyCollection.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property // foreach (var q in c) { } Diagnostic(ErrorCode.ERR_BadGetEnumerator, "c").WithArguments("MyEnumerator", "MyCollection.GetEnumerator()").WithLocation(6, 27) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (26,24): error CS0111: Type 'MyEnumerator' already defines a member called 'MoveNext' with the same parameter types // public static bool MoveNext() => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "MoveNext").WithArguments("MoveNext", "MyEnumerator").WithLocation(26, 24) ); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver06() { var source = @"class Program { public static void Main() { var o = new MyDeconstructable(); (var a, var b) = o; System.Console.WriteLine(a); } } class MyDeconstructable { public void Deconstruct(out int a, out int b) => (a, b) = (1, 2); public static void Deconstruct(out long a, out long b) => (a, b) = (3, 4); } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,26): error CS0121: The call is ambiguous between the following methods or properties: 'MyDeconstructable.Deconstruct(out int, out int)' and 'MyDeconstructable.Deconstruct(out long, out long)' // (var a, var b) = o; Diagnostic(ErrorCode.ERR_AmbigCall, "o").WithArguments("MyDeconstructable.Deconstruct(out int, out int)", "MyDeconstructable.Deconstruct(out long, out long)").WithLocation(6, 26), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'a'. // (var a, var b) = o; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "a").WithArguments("a").WithLocation(6, 14), // (6,21): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'b'. // (var a, var b) = o; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "b").WithArguments("b").WithLocation(6, 21) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver07() { var source = @"class Program { public static void Main() { M(new MyTask<int>(3)).GetAwaiter().GetResult(); } static async System.Threading.Tasks.Task M(MyTask<int> x) { var z = await x; System.Console.WriteLine(z); } } public class MyTask<TResult> { MyTaskAwaiter<TResult> awaiter; public MyTask(TResult value) { this.awaiter = new MyTaskAwaiter<TResult>(value); } public static MyTaskAwaiter<TResult> GetAwaiter() => null; } public class MyTaskAwaiter<TResult> : System.Runtime.CompilerServices.INotifyCompletion { TResult value; public MyTaskAwaiter(TResult value) { this.value = value; } public bool IsCompleted { get => true; } public TResult GetResult() => value; public void OnCompleted(System.Action continuation) => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,17): error CS1986: 'await' requires that the type MyTask<int> have a suitable GetAwaiter method // var z = await x; Diagnostic(ErrorCode.ERR_BadAwaitArg, "await x").WithArguments("MyTask<int>").WithLocation(9, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,17): error CS1986: 'await' requires that the type MyTask<int> have a suitable GetAwaiter method // var z = await x; Diagnostic(ErrorCode.ERR_BadAwaitArg, "await x").WithArguments("MyTask<int>").WithLocation(9, 17) ); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver08() { var source = @"class Program { public static void Main() { M(new MyTask<int>(3)).GetAwaiter().GetResult(); } static async System.Threading.Tasks.Task M(MyTask<int> x) { var z = await x; System.Console.WriteLine(z); } } public class MyTask<TResult> { MyTaskAwaiter<TResult> awaiter; public MyTask(TResult value) { this.awaiter = new MyTaskAwaiter<TResult>(value); } public MyTaskAwaiter<TResult> GetAwaiter() => awaiter; } public struct MyTaskAwaiter<TResult> : System.Runtime.CompilerServices.INotifyCompletion { TResult value; public MyTaskAwaiter(TResult value) { this.value = value; } public bool IsCompleted { get => true; } public static TResult GetResult() => throw null; public void OnCompleted(System.Action continuation) => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,17): error CS0176: Member 'MyTaskAwaiter<int>.GetResult()' cannot be accessed with an instance reference; qualify it with a type name instead // var z = await x; Diagnostic(ErrorCode.ERR_ObjectProhibited, "await x").WithArguments("MyTaskAwaiter<int>.GetResult()").WithLocation(9, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,17): error CS0176: Member 'MyTaskAwaiter<int>.GetResult()' cannot be accessed with an instance reference; qualify it with a type name instead // var z = await x; Diagnostic(ErrorCode.ERR_ObjectProhibited, "await x").WithArguments("MyTaskAwaiter<int>.GetResult()").WithLocation(9, 17) ); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver09() { var source = @"using System; class Program { static void Main() { var q = from x in new Q() select x; } } class Q { public static object Select(Func<A, A> y) { Console.WriteLine(1); return null; } public object Select(Func<B, B> y) { Console.WriteLine(2); return null; } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,35): error CS1940: Multiple implementations of the query pattern were found for source type 'Q'. Ambiguous call to 'Select'. // var q = from x in new Q() select x; Diagnostic(ErrorCode.ERR_QueryMultipleProviders, "select x").WithArguments("Q", "Select").WithLocation(6, 35) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains no receiver in a static context, we include only static members. // Type 1: in a static method [Fact] public void TestStaticContext01() { var source = @"class Program { public static void Main() { M(null); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains no receiver in a static context, we include only static members. // Type 2: in a field initializer [Fact] public void TestStaticContext02() { var source = @"class Program { public static void Main() { new Program(); } public static int M(A a) { System.Console.WriteLine(1); return 1; } public int M(B b) { System.Console.WriteLine(2); return 2; } int X = M(null); } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,13): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // int X = M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(9, 13) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains no receiver in a static context, we include only static members. // Type 4: in a constructor-initializer [Fact] public void TestStaticContext04() { var source = @"class Program { public static void Main() { new Program(); } public Program() : this(M(null)) {} public Program(int x) {} public static int M(A a) { System.Console.WriteLine(1); return 1; } public int M(B b) { System.Console.WriteLine(2); return 2; } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (7,29): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // public Program() : this(M(null)) {} Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(7, 29) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains no receiver in a static context, we include only static members. // Type 5: in an attribute argument [Fact] public void TestStaticContext05() { var source = @"public class Program { public static int M(A a) { System.Console.WriteLine(1); return 1; } public int M(B b) { System.Console.WriteLine(2); return 2; } [My(M(null))] public int x; } public class A {} public class B {} public class MyAttribute : System.Attribute { public MyAttribute(int value) {} } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // [My(M(null))] Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 9) ); CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(M(null))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "M(null)").WithLocation(6, 9) ); } //When a method group contains no receiver in a static context, we include only static members. // In a default parameter value [Fact] public void TestStaticContext06() { var source = @"public class Program { public static int M(A a) { System.Console.WriteLine(1); return 1; } public int M(B b) { System.Console.WriteLine(2); return 2; } public void Q(int x = M(null)) { } } public class A {} public class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (5,27): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // public void Q(int x = M(null)) Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 27) ); CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (5,27): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // public void Q(int x = M(null)) Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 27) ); } //When a method group contains no receiver, we include both static and instance members in an other-than-static context. i.e. discard nothing. [Fact] public void TestInstanceContext01() { var source = @"public class Program { public void M() { M(null); } public static int M(A a) => 1; public int M(B b) => 2; } public class A {} public class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 9) ); CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 9) ); } //When a method group receiver is ambiguously an instance or type due to a color-color situation, we include both instance and static candidates. [Fact] public void TestAmbiguousContext01() { var source = @"public class Color { public void M() { Color Color = null; Color.M(null); } public static int M(A a) => 1; public int M(B b) => 2; } public class A {} public class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,15): error CS0121: The call is ambiguous between the following methods or properties: 'Color.M(A)' and 'Color.M(B)' // Color.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Color.M(A)", "Color.M(B)").WithLocation(6, 15) ); CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,15): error CS0121: The call is ambiguous between the following methods or properties: 'Color.M(A)' and 'Color.M(B)' // Color.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Color.M(A)", "Color.M(B)").WithLocation(6, 15) ); } //When a method group contains some generic methods whose type parameters do not satisfy their constraints, these members are removed from the candidate set. [Fact] public void TestConstraintFailed01() { var source = @"public class Program { static void Main() { M(new A(), 0); } static void M<T>(T t1, int i) where T: B { System.Console.WriteLine(1); } static void M<T>(T t1, short s) { System.Console.WriteLine(2); } } public class A {} public class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0311: The type 'A' cannot be used as type parameter 'T' in the generic type or method 'Program.M<T>(T, int)'. There is no implicit reference conversion from 'A' to 'B'. // M(new A(), 0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("Program.M<T>(T, int)", "B", "T", "A").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains some generic methods whose type parameters do not satisfy their constraints, these members are removed from the candidate set. // Test that this permits overload resolution to use type parameter constraints "as a tie-breaker" to guide overload resolution. [Fact] public void TestConstraintFailed02() { var source = @"public class Program { static void Main() { M(new A(), null); M(new B(), null); } static void M<T>(T t1, B b) where T: struct { System.Console.Write(""struct ""); } static void M<T>(T t1, X s) where T : class { System.Console.Write(""class ""); } } public struct A {} public class B {} public class X {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, B)' and 'Program.M<T>(T, X)' // M(new A(), null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, B)", "Program.M<T>(T, X)").WithLocation(5, 9), // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, B)' and 'Program.M<T>(T, X)' // M(new B(), null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, B)", "Program.M<T>(T, X)").WithLocation(6, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "struct class "); } //For a method group conversion, candidate methods whose return type doesn't match up with the delegate's return type are removed from the set. [Fact] public void TestReturnTypeMismatch01() { var source = @"public class Program { static void Main() { M(Program.Q); } static void M(D1 d) { System.Console.WriteLine(1); } static void M(D2 d) { System.Console.WriteLine(2); } static void Q(A a) { } static void Q(B b) { } } delegate int D1(A a); delegate void D2(B b); class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(D1)' and 'Program.M(D2)' // M(Q); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(D1)", "Program.M(D2)").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } //For a method group conversion, candidate methods whose return ref kind doesn't match up with the delegate's return ref kind are removed from the set. [Fact] public void TestReturnRefMismatch01() { var source = @"public class Program { static int tmp; static void Main() { M(Q); } static void M(D1 d) { System.Console.WriteLine(1); } static void M(D2 d) { System.Console.WriteLine(2); } static ref int Q() { return ref tmp; } } delegate int D1(); delegate ref int D2(); "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(D1)' and 'Program.M(D2)' // M(Q); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(D1)", "Program.M(D2)").WithLocation(6, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } //For a method group conversion, candidate methods whose return ref kind doesn't match up with the delegate's return ref kind are removed from the set. [Fact] public void TestReturnRefMismatch02() { var source = @"public class Program { static int tmp = 2; static void Main() { M(Q); } static void M(D1 d) { System.Console.WriteLine(1); } static void M(D2 d) { System.Console.WriteLine(2); } static int Q() { return tmp; } } delegate int D1(); delegate ref int D2(); "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(D1)' and 'Program.M(D2)' // M(Q); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(D1)", "Program.M(D2)").WithLocation(6, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //For a method group conversion, candidate methods whose return type doesn't match up with the delegate's return type are removed from the set. [Fact] public void TestReturnTypeMismatch02() { var source = @"public class Program { static void Main() { M(new Z().Q); } static void M(D1 d) { System.Console.WriteLine(1); } static void M(D2 d) { System.Console.WriteLine(2); } } delegate int D1(A a); delegate void D2(B b); public class A {} public class B {} public class Z {} public static class X { public static void Q(this Z z, A a) {} public static void Q(this Z z, B b) {} } namespace System.Runtime.CompilerServices { public class ExtensionAttribute : System.Attribute {} } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(D1)' and 'Program.M(D2)' // M(new Z().Q); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(D1)", "Program.M(D2)").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } // Test suggested by @VSadov // 1) one candidate is generic, but candidate fails constraints, while another overload requires a conversion. Used to be an error, second should be picked now. [Fact] public void TestConstraintFailed03() { var source = @"public class Program { static void Main() { M(new A(), 0); } static void M<T>(T t1, int i) where T: B { System.Console.WriteLine(1); } static void M(C c, short s) { System.Console.WriteLine(2); } } public class A {} public class B {} public class C { public static implicit operator C(A a) => null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0311: The type 'A' cannot be used as type parameter 'T' in the generic type or method 'Program.M<T>(T, int)'. There is no implicit reference conversion from 'A' to 'B'. // M(new A(), 0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("Program.M<T>(T, int)", "B", "T", "A").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } // Test suggested by @VSadov // 2) one candidate is generic without constraints, but we pass a ref-struct to it, which cannot be a generic type arg, another candidate requires a conversion and now works. [Fact] public void TestConstraintFailed04() { var source = @"public class Program { static void Main() { M(new A(), 0); } static void M<T>(T t1, int i) { System.Console.WriteLine(1); } static void M(C c, short s) { System.Console.WriteLine(2); } } public ref struct A {} public class C { public static implicit operator C(A a) => null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0306: The type 'A' may not be used as a type argument // M(new A(), 0); Diagnostic(ErrorCode.ERR_BadTypeArgument, "M").WithArguments("A").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } // Test suggested by @VSadov // 3) one candidate is generic without constraints, but we pass a pointer to it, which cannot be a generic type arg, another candidate requires a conversion and now works. [Fact] public void TestConstraintFailed05() { var source = @"public class Program { static unsafe void Main() { int *p = null; M(p, 0); } static void M<T>(T t1, int i) { System.Console.WriteLine(1); } static void M(C c, short s) { System.Console.WriteLine(2); } } public class C { public static unsafe implicit operator C(int* p) => null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,9): error CS0306: The type 'int*' may not be used as a type argument // M(p, 0); Diagnostic(ErrorCode.ERR_BadTypeArgument, "M").WithArguments("int*").WithLocation(6, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2", verify: Verification.Skipped); } [ClrOnlyFact] public void IndexedPropertyTest01() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class C Public Property P(a As A) As Object Get Return Nothing End Get Set(value As Object) End Set End Property Public Shared Property P(b As B) As Object Get Return Nothing End Get Set(value As Object) End Set End Property End Class Public Class A End Class Public Class B End Class "; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Passes); var source2 = @"class D : C { static void Main() { } void M() { object o; o = P[null]; P[null] = o; o = this.P[null]; base.P[null] = o; o = D.P[null]; // C# does not support static indexed properties D.P[null] = o; // C# does not support static indexed properties } }"; CreateCompilationWithoutBetterCandidates(source2, references: new[] { reference1 }, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)).VerifyDiagnostics( // (13,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.P[A]' // o = D.P[null]; Diagnostic(ErrorCode.ERR_ObjectRequired, "D.P[null]").WithArguments("C.P[A]").WithLocation(13, 13), // (14,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.P[A]' // D.P[null] = o; Diagnostic(ErrorCode.ERR_ObjectRequired, "D.P[null]").WithArguments("C.P[A]").WithLocation(14, 9) ); CreateCompilationWithBetterCandidates(source2, references: new[] { reference1 }, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)).VerifyDiagnostics( // (13,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.P[A]' // o = D.P[null]; Diagnostic(ErrorCode.ERR_ObjectRequired, "D.P[null]").WithArguments("C.P[A]").WithLocation(13, 13), // (14,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.P[A]' // D.P[null] = o; Diagnostic(ErrorCode.ERR_ObjectRequired, "D.P[null]").WithArguments("C.P[A]").WithLocation(14, 9) ); } [Fact] public void TestAmbiguous01() { // test semantic model in the face of ambiguities even when there are static/instance violations var source = @"class Program { public static void Main() { Program p = null; Program.M(null); // two static candidates p.M(null); // two instance candidates M(null); // two static candidates } void Q() { Program Program = null; M(null); // four candidates Program.M(null); // four candidates } public static void M(A a) => throw null; public void M(B b) => throw null; public static void M(C c) => throw null; public void M(D d) => throw null; } class A {} class B {} class C {} class D {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // Program.M(null); // two static candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 17), // (7,11): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // p.M(null); // two instance candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(7, 11), // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // two static candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(8, 9), // (13,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // four candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(13, 9), // (14,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // Program.M(null); // four candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(14, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(C)' // Program.M(null); // two static candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(C)").WithLocation(6, 17), // (7,11): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(B)' and 'Program.M(D)' // p.M(null); // two instance candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(B)", "Program.M(D)").WithLocation(7, 11), // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(C)' // M(null); // two static candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(C)").WithLocation(8, 9), // (13,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // four candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(13, 9), // (14,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // Program.M(null); // four candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(14, 17) ); var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var invocations = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal(5, invocations.Length); var symbolInfo = model.GetSymbolInfo(invocations[0].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); symbolInfo = model.GetSymbolInfo(invocations[1].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); symbolInfo = model.GetSymbolInfo(invocations[2].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); symbolInfo = model.GetSymbolInfo(invocations[3].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); symbolInfo = model.GetSymbolInfo(invocations[4].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); } [Fact] public void TestAmbiguous02() { // test semantic model in the face of ambiguities even when there are constraint violations var source = @"class Program { public static void Main() { M(1, null); } public static void M<T>(T t, A a) where T : Constraint => throw null; public static void M<T>(T t, B b) => throw null; public static void M<T>(T t, C c) where T : Constraint => throw null; public static void M<T>(T t, D d) => throw null; } class A {} class B {} class C {} class D {} class Constraint {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, A)' and 'Program.M<T>(T, B)' // M(1, null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, A)", "Program.M<T>(T, B)").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, B)' and 'Program.M<T>(T, D)' // M(1, null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, B)", "Program.M<T>(T, D)").WithLocation(5, 9) ); var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var invocations = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal(1, invocations.Length); var symbolInfo = model.GetSymbolInfo(invocations[0].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M<System.Int32>(System.Int32 t, A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M<System.Int32>(System.Int32 t, B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M<System.Int32>(System.Int32 t, C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M<System.Int32>(System.Int32 t, D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); } [Fact] public void TestAmbiguous03() { // test semantic model in the face of ambiguities even when there are constraint violations var source = @"class Program { public static void Main() { 1.M(null); } } public class A {} public class B {} public class C {} public class D {} public class Constraint {} public static class Extensions { public static void M<T>(this T t, A a) where T : Constraint => throw null; public static void M<T>(this T t, B b) => throw null; public static void M<T>(this T t, C c) where T : Constraint => throw null; public static void M<T>(this T t, D d) => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,11): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions.M<T>(T, A)' and 'Extensions.M<T>(T, B)' // 1.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Extensions.M<T>(T, A)", "Extensions.M<T>(T, B)").WithLocation(5, 11) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,11): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions.M<T>(T, B)' and 'Extensions.M<T>(T, D)' // 1.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Extensions.M<T>(T, B)", "Extensions.M<T>(T, D)").WithLocation(5, 11) ); var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var invocations = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal(1, invocations.Length); var symbolInfo = model.GetSymbolInfo(invocations[0].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void System.Int32.M<System.Int32>(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void System.Int32.M<System.Int32>(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void System.Int32.M<System.Int32>(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void System.Int32.M<System.Int32>(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); } [Fact] public void TestAmbiguous04() { // test semantic model in the face of ambiguities even when there are return type mismatches var source = @"class Program { public static void Main() { Invoked(Argument); } public static void Invoked(Delegate d) { } public delegate A Delegate(IZ c); static B Argument(IQ x) => null; static D Argument(IW x) => null; static C Argument(IX x) => null; static D Argument(IY x) => null; } class A {} class B: A {} class C: A {} class D {} interface IQ {} interface IW {} interface IX {} interface IY {} interface IZ: IQ, IW, IX, IY {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Argument(IQ)' and 'Program.Argument(IW)' // Invoked(Argument); Diagnostic(ErrorCode.ERR_AmbigCall, "Argument").WithArguments("Program.Argument(IQ)", "Program.Argument(IW)").WithLocation(5, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Argument(IQ)' and 'Program.Argument(IX)' // Invoked(Argument); Diagnostic(ErrorCode.ERR_AmbigCall, "Argument").WithArguments("Program.Argument(IQ)", "Program.Argument(IX)").WithLocation(5, 17) ); var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var invocations = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal(1, invocations.Length); var symbolInfo = model.GetSymbolInfo(invocations[0].ArgumentList.Arguments[0].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("B Program.Argument(IQ x)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("D Program.Argument(IW x)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("C Program.Argument(IX x)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("D Program.Argument(IY x)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using System.Linq; using System.Diagnostics; using System.Collections; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests for improved overload candidate selection. /// See also https://github.com/dotnet/csharplang/issues/98. /// </summary> public class BetterCandidates : CompilingTestBase { private CSharpCompilation CreateCompilationWithoutBetterCandidates(string source, CSharpCompilationOptions options = null, MetadataReference[] references = null) { return CreateCompilation(source, options: options, references: references, parseOptions: TestOptions.WithoutImprovedOverloadCandidates); } private CSharpCompilation CreateCompilationWithBetterCandidates(string source, CSharpCompilationOptions options = null, MetadataReference[] references = null) { Debug.Assert(TestOptions.Regular.LanguageVersion >= MessageID.IDS_FeatureImprovedOverloadCandidates.RequiredVersion()); return CreateCompilation(source, options: options, references: references, parseOptions: TestOptions.Regular); } //When a method group contains both instance and static members, we discard the instance members if invoked with a static receiver. [Fact] public void TestStaticReceiver01() { var source = @"class Program { public static void Main() { Program.M(null); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // Program.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver01() { var source = @"class Program { public static void Main() { Program p = new Program(); p.M(null); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,11): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // p.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 11) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver02() { var source = @"class Program { public static void Main() { Program p = new Program(); p.Main2(); } void Main2() { this.M(null); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (10,14): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // this.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(10, 14) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver02b() { var source = @"class Program { public static void Main() { D d = new D(); d.Main2(); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class D : Program { public void Main2() { base.M(null); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (15,14): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // base.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(15, 14) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver03() { var source = @"class Program { public static void Main() { new MyCollection { null }; } } class A {} class B {} class MyCollection : System.Collections.IEnumerable { public static void Add(A a) { System.Console.WriteLine(1); } public void Add(B b) { System.Console.WriteLine(2); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new System.NotImplementedException(); } } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,28): error CS0121: The call is ambiguous between the following methods or properties: 'MyCollection.Add(A)' and 'MyCollection.Add(B)' // new MyCollection { null }; Diagnostic(ErrorCode.ERR_AmbigCall, "null").WithArguments("MyCollection.Add(A)", "MyCollection.Add(B)").WithLocation(5, 28) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver04() { var source = @"class Program { public static void Main() { var c = new MyCollection(); foreach (var q in c) { } } } class A {} class B {} class MyCollection : System.Collections.IEnumerable { public static System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { System.Console.Write(1); return new MyEnumerator(); } } class MyEnumerator : System.Collections.IEnumerator { object System.Collections.IEnumerator.Current => throw null; bool System.Collections.IEnumerator.MoveNext() { System.Console.WriteLine(2); return false; } void System.Collections.IEnumerator.Reset() => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,27): warning CS0279: 'MyCollection' does not implement the 'collection' pattern. 'MyCollection.GetEnumerator()' is not a public instance or extension method. // foreach (var q in c) { } Diagnostic(ErrorCode.WRN_PatternNotPublicOrNotInstance, "c").WithArguments("MyCollection", "collection", "MyCollection.GetEnumerator()").WithLocation(6, 27) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "12"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver05() { var source = @"class Program { public static void Main() { var c = new MyCollection(); foreach (var q in c) { } } } class A {} class B {} class MyCollection { public MyEnumerator GetEnumerator() { return new MyEnumerator(); } } class MyEnumerator { public object Current => throw null; public bool MoveNext() { System.Console.WriteLine(2); return false; } public static bool MoveNext() => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (26,24): error CS0111: Type 'MyEnumerator' already defines a member called 'MoveNext' with the same parameter types // public static bool MoveNext() => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "MoveNext").WithArguments("MoveNext", "MyEnumerator").WithLocation(26, 24), // (6,27): error CS0202: foreach requires that the return type 'MyEnumerator' of 'MyCollection.GetEnumerator()' must have a suitable public 'MoveNext' method and public 'Current' property // foreach (var q in c) { } Diagnostic(ErrorCode.ERR_BadGetEnumerator, "c").WithArguments("MyEnumerator", "MyCollection.GetEnumerator()").WithLocation(6, 27) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (26,24): error CS0111: Type 'MyEnumerator' already defines a member called 'MoveNext' with the same parameter types // public static bool MoveNext() => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "MoveNext").WithArguments("MoveNext", "MyEnumerator").WithLocation(26, 24) ); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver06() { var source = @"class Program { public static void Main() { var o = new MyDeconstructable(); (var a, var b) = o; System.Console.WriteLine(a); } } class MyDeconstructable { public void Deconstruct(out int a, out int b) => (a, b) = (1, 2); public static void Deconstruct(out long a, out long b) => (a, b) = (3, 4); } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,26): error CS0121: The call is ambiguous between the following methods or properties: 'MyDeconstructable.Deconstruct(out int, out int)' and 'MyDeconstructable.Deconstruct(out long, out long)' // (var a, var b) = o; Diagnostic(ErrorCode.ERR_AmbigCall, "o").WithArguments("MyDeconstructable.Deconstruct(out int, out int)", "MyDeconstructable.Deconstruct(out long, out long)").WithLocation(6, 26), // (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'a'. // (var a, var b) = o; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "a").WithArguments("a").WithLocation(6, 14), // (6,21): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'b'. // (var a, var b) = o; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "b").WithArguments("b").WithLocation(6, 21) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver07() { var source = @"class Program { public static void Main() { M(new MyTask<int>(3)).GetAwaiter().GetResult(); } static async System.Threading.Tasks.Task M(MyTask<int> x) { var z = await x; System.Console.WriteLine(z); } } public class MyTask<TResult> { MyTaskAwaiter<TResult> awaiter; public MyTask(TResult value) { this.awaiter = new MyTaskAwaiter<TResult>(value); } public static MyTaskAwaiter<TResult> GetAwaiter() => null; } public class MyTaskAwaiter<TResult> : System.Runtime.CompilerServices.INotifyCompletion { TResult value; public MyTaskAwaiter(TResult value) { this.value = value; } public bool IsCompleted { get => true; } public TResult GetResult() => value; public void OnCompleted(System.Action continuation) => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,17): error CS1986: 'await' requires that the type MyTask<int> have a suitable GetAwaiter method // var z = await x; Diagnostic(ErrorCode.ERR_BadAwaitArg, "await x").WithArguments("MyTask<int>").WithLocation(9, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,17): error CS1986: 'await' requires that the type MyTask<int> have a suitable GetAwaiter method // var z = await x; Diagnostic(ErrorCode.ERR_BadAwaitArg, "await x").WithArguments("MyTask<int>").WithLocation(9, 17) ); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver08() { var source = @"class Program { public static void Main() { M(new MyTask<int>(3)).GetAwaiter().GetResult(); } static async System.Threading.Tasks.Task M(MyTask<int> x) { var z = await x; System.Console.WriteLine(z); } } public class MyTask<TResult> { MyTaskAwaiter<TResult> awaiter; public MyTask(TResult value) { this.awaiter = new MyTaskAwaiter<TResult>(value); } public MyTaskAwaiter<TResult> GetAwaiter() => awaiter; } public struct MyTaskAwaiter<TResult> : System.Runtime.CompilerServices.INotifyCompletion { TResult value; public MyTaskAwaiter(TResult value) { this.value = value; } public bool IsCompleted { get => true; } public static TResult GetResult() => throw null; public void OnCompleted(System.Action continuation) => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,17): error CS0176: Member 'MyTaskAwaiter<int>.GetResult()' cannot be accessed with an instance reference; qualify it with a type name instead // var z = await x; Diagnostic(ErrorCode.ERR_ObjectProhibited, "await x").WithArguments("MyTaskAwaiter<int>.GetResult()").WithLocation(9, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,17): error CS0176: Member 'MyTaskAwaiter<int>.GetResult()' cannot be accessed with an instance reference; qualify it with a type name instead // var z = await x; Diagnostic(ErrorCode.ERR_ObjectProhibited, "await x").WithArguments("MyTaskAwaiter<int>.GetResult()").WithLocation(9, 17) ); } //When a method group contains both instance and static members, we discard the static members if invoked with an instance receiver. [Fact] public void TestInstanceReceiver09() { var source = @"using System; class Program { static void Main() { var q = from x in new Q() select x; } } class Q { public static object Select(Func<A, A> y) { Console.WriteLine(1); return null; } public object Select(Func<B, B> y) { Console.WriteLine(2); return null; } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,35): error CS1940: Multiple implementations of the query pattern were found for source type 'Q'. Ambiguous call to 'Select'. // var q = from x in new Q() select x; Diagnostic(ErrorCode.ERR_QueryMultipleProviders, "select x").WithArguments("Q", "Select").WithLocation(6, 35) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains no receiver in a static context, we include only static members. // Type 1: in a static method [Fact] public void TestStaticContext01() { var source = @"class Program { public static void Main() { M(null); } public static void M(A a) { System.Console.WriteLine(1); } public void M(B b) { System.Console.WriteLine(2); } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains no receiver in a static context, we include only static members. // Type 2: in a field initializer [Fact] public void TestStaticContext02() { var source = @"class Program { public static void Main() { new Program(); } public static int M(A a) { System.Console.WriteLine(1); return 1; } public int M(B b) { System.Console.WriteLine(2); return 2; } int X = M(null); } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (9,13): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // int X = M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(9, 13) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains no receiver in a static context, we include only static members. // Type 4: in a constructor-initializer [Fact] public void TestStaticContext04() { var source = @"class Program { public static void Main() { new Program(); } public Program() : this(M(null)) {} public Program(int x) {} public static int M(A a) { System.Console.WriteLine(1); return 1; } public int M(B b) { System.Console.WriteLine(2); return 2; } } class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (7,29): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // public Program() : this(M(null)) {} Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(7, 29) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //When a method group contains no receiver in a static context, we include only static members. // Type 5: in an attribute argument [Fact] public void TestStaticContext05() { var source = @"public class Program { public static int M(A a) { System.Console.WriteLine(1); return 1; } public int M(B b) { System.Console.WriteLine(2); return 2; } [My(M(null))] public int x; } public class A {} public class B {} public class MyAttribute : System.Attribute { public MyAttribute(int value) {} } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // [My(M(null))] Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 9) ); CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,9): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [My(M(null))] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "M(null)").WithLocation(6, 9) ); } //When a method group contains no receiver in a static context, we include only static members. // In a default parameter value [Fact] public void TestStaticContext06() { var source = @"public class Program { public static int M(A a) { System.Console.WriteLine(1); return 1; } public int M(B b) { System.Console.WriteLine(2); return 2; } public void Q(int x = M(null)) { } } public class A {} public class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (5,27): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // public void Q(int x = M(null)) Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 27) ); CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (5,27): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // public void Q(int x = M(null)) Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 27) ); } //When a method group contains no receiver, we include both static and instance members in an other-than-static context. i.e. discard nothing. [Fact] public void TestInstanceContext01() { var source = @"public class Program { public void M() { M(null); } public static int M(A a) => 1; public int M(B b) => 2; } public class A {} public class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 9) ); CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(5, 9) ); } //When a method group receiver is ambiguously an instance or type due to a color-color situation, we include both instance and static candidates. [Fact] public void TestAmbiguousContext01() { var source = @"public class Color { public void M() { Color Color = null; Color.M(null); } public static int M(A a) => 1; public int M(B b) => 2; } public class A {} public class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,15): error CS0121: The call is ambiguous between the following methods or properties: 'Color.M(A)' and 'Color.M(B)' // Color.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Color.M(A)", "Color.M(B)").WithLocation(6, 15) ); CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,15): error CS0121: The call is ambiguous between the following methods or properties: 'Color.M(A)' and 'Color.M(B)' // Color.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Color.M(A)", "Color.M(B)").WithLocation(6, 15) ); } //When a method group contains some generic methods whose type parameters do not satisfy their constraints, these members are removed from the candidate set. [Fact] public void TestConstraintFailed01() { var source = @"public class Program { static void Main() { M(new A(), 0); } static void M<T>(T t1, int i) where T: B { System.Console.WriteLine(1); } static void M<T>(T t1, short s) { System.Console.WriteLine(2); } } public class A {} public class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0311: The type 'A' cannot be used as type parameter 'T' in the generic type or method 'Program.M<T>(T, int)'. There is no implicit reference conversion from 'A' to 'B'. // M(new A(), 0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("Program.M<T>(T, int)", "B", "T", "A").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } //When a method group contains some generic methods whose type parameters do not satisfy their constraints, these members are removed from the candidate set. // Test that this permits overload resolution to use type parameter constraints "as a tie-breaker" to guide overload resolution. [Fact] public void TestConstraintFailed02() { var source = @"public class Program { static void Main() { M(new A(), null); M(new B(), null); } static void M<T>(T t1, B b) where T: struct { System.Console.Write(""struct ""); } static void M<T>(T t1, X s) where T : class { System.Console.Write(""class ""); } } public struct A {} public class B {} public class X {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, B)' and 'Program.M<T>(T, X)' // M(new A(), null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, B)", "Program.M<T>(T, X)").WithLocation(5, 9), // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, B)' and 'Program.M<T>(T, X)' // M(new B(), null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, B)", "Program.M<T>(T, X)").WithLocation(6, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "struct class "); } //For a method group conversion, candidate methods whose return type doesn't match up with the delegate's return type are removed from the set. [Fact] public void TestReturnTypeMismatch01() { var source = @"public class Program { static void Main() { M(Program.Q); } static void M(D1 d) { System.Console.WriteLine(1); } static void M(D2 d) { System.Console.WriteLine(2); } static void Q(A a) { } static void Q(B b) { } } delegate int D1(A a); delegate void D2(B b); class A {} class B {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(D1)' and 'Program.M(D2)' // M(Q); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(D1)", "Program.M(D2)").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } //For a method group conversion, candidate methods whose return ref kind doesn't match up with the delegate's return ref kind are removed from the set. [Fact] public void TestReturnRefMismatch01() { var source = @"public class Program { static int tmp; static void Main() { M(Q); } static void M(D1 d) { System.Console.WriteLine(1); } static void M(D2 d) { System.Console.WriteLine(2); } static ref int Q() { return ref tmp; } } delegate int D1(); delegate ref int D2(); "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(D1)' and 'Program.M(D2)' // M(Q); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(D1)", "Program.M(D2)").WithLocation(6, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } //For a method group conversion, candidate methods whose return ref kind doesn't match up with the delegate's return ref kind are removed from the set. [Fact] public void TestReturnRefMismatch02() { var source = @"public class Program { static int tmp = 2; static void Main() { M(Q); } static void M(D1 d) { System.Console.WriteLine(1); } static void M(D2 d) { System.Console.WriteLine(2); } static int Q() { return tmp; } } delegate int D1(); delegate ref int D2(); "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(D1)' and 'Program.M(D2)' // M(Q); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(D1)", "Program.M(D2)").WithLocation(6, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "1"); } //For a method group conversion, candidate methods whose return type doesn't match up with the delegate's return type are removed from the set. [Fact] public void TestReturnTypeMismatch02() { var source = @"public class Program { static void Main() { M(new Z().Q); } static void M(D1 d) { System.Console.WriteLine(1); } static void M(D2 d) { System.Console.WriteLine(2); } } delegate int D1(A a); delegate void D2(B b); public class A {} public class B {} public class Z {} public static class X { public static void Q(this Z z, A a) {} public static void Q(this Z z, B b) {} } namespace System.Runtime.CompilerServices { public class ExtensionAttribute : System.Attribute {} } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(D1)' and 'Program.M(D2)' // M(new Z().Q); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(D1)", "Program.M(D2)").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } // Test suggested by @VSadov // 1) one candidate is generic, but candidate fails constraints, while another overload requires a conversion. Used to be an error, second should be picked now. [Fact] public void TestConstraintFailed03() { var source = @"public class Program { static void Main() { M(new A(), 0); } static void M<T>(T t1, int i) where T: B { System.Console.WriteLine(1); } static void M(C c, short s) { System.Console.WriteLine(2); } } public class A {} public class B {} public class C { public static implicit operator C(A a) => null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0311: The type 'A' cannot be used as type parameter 'T' in the generic type or method 'Program.M<T>(T, int)'. There is no implicit reference conversion from 'A' to 'B'. // M(new A(), 0); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("Program.M<T>(T, int)", "B", "T", "A").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } // Test suggested by @VSadov // 2) one candidate is generic without constraints, but we pass a ref-struct to it, which cannot be a generic type arg, another candidate requires a conversion and now works. [Fact] public void TestConstraintFailed04() { var source = @"public class Program { static void Main() { M(new A(), 0); } static void M<T>(T t1, int i) { System.Console.WriteLine(1); } static void M(C c, short s) { System.Console.WriteLine(2); } } public ref struct A {} public class C { public static implicit operator C(A a) => null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0306: The type 'A' may not be used as a type argument // M(new A(), 0); Diagnostic(ErrorCode.ERR_BadTypeArgument, "M").WithArguments("A").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2"); } // Test suggested by @VSadov // 3) one candidate is generic without constraints, but we pass a pointer to it, which cannot be a generic type arg, another candidate requires a conversion and now works. [Fact] public void TestConstraintFailed05() { var source = @"public class Program { static unsafe void Main() { int *p = null; M(p, 0); } static void M<T>(T t1, int i) { System.Console.WriteLine(1); } static void M(C c, short s) { System.Console.WriteLine(2); } } public class C { public static unsafe implicit operator C(int* p) => null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,9): error CS0306: The type 'int*' may not be used as a type argument // M(p, 0); Diagnostic(ErrorCode.ERR_BadTypeArgument, "M").WithArguments("int*").WithLocation(6, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)).VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "2", verify: Verification.Skipped); } [ClrOnlyFact] public void IndexedPropertyTest01() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class C Public Property P(a As A) As Object Get Return Nothing End Get Set(value As Object) End Set End Property Public Shared Property P(b As B) As Object Get Return Nothing End Get Set(value As Object) End Set End Property End Class Public Class A End Class Public Class B End Class "; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Passes); var source2 = @"class D : C { static void Main() { } void M() { object o; o = P[null]; P[null] = o; o = this.P[null]; base.P[null] = o; o = D.P[null]; // C# does not support static indexed properties D.P[null] = o; // C# does not support static indexed properties } }"; CreateCompilationWithoutBetterCandidates(source2, references: new[] { reference1 }, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)).VerifyDiagnostics( // (13,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.P[A]' // o = D.P[null]; Diagnostic(ErrorCode.ERR_ObjectRequired, "D.P[null]").WithArguments("C.P[A]").WithLocation(13, 13), // (14,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.P[A]' // D.P[null] = o; Diagnostic(ErrorCode.ERR_ObjectRequired, "D.P[null]").WithArguments("C.P[A]").WithLocation(14, 9) ); CreateCompilationWithBetterCandidates(source2, references: new[] { reference1 }, options: TestOptions.ReleaseExe.WithAllowUnsafe(true)).VerifyDiagnostics( // (13,13): error CS0120: An object reference is required for the non-static field, method, or property 'C.P[A]' // o = D.P[null]; Diagnostic(ErrorCode.ERR_ObjectRequired, "D.P[null]").WithArguments("C.P[A]").WithLocation(13, 13), // (14,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.P[A]' // D.P[null] = o; Diagnostic(ErrorCode.ERR_ObjectRequired, "D.P[null]").WithArguments("C.P[A]").WithLocation(14, 9) ); } [Fact] public void TestAmbiguous01() { // test semantic model in the face of ambiguities even when there are static/instance violations var source = @"class Program { public static void Main() { Program p = null; Program.M(null); // two static candidates p.M(null); // two instance candidates M(null); // two static candidates } void Q() { Program Program = null; M(null); // four candidates Program.M(null); // four candidates } public static void M(A a) => throw null; public void M(B b) => throw null; public static void M(C c) => throw null; public void M(D d) => throw null; } class A {} class B {} class C {} class D {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // Program.M(null); // two static candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(6, 17), // (7,11): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // p.M(null); // two instance candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(7, 11), // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // two static candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(8, 9), // (13,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // four candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(13, 9), // (14,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // Program.M(null); // four candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(14, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (6,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(C)' // Program.M(null); // two static candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(C)").WithLocation(6, 17), // (7,11): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(B)' and 'Program.M(D)' // p.M(null); // two instance candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(B)", "Program.M(D)").WithLocation(7, 11), // (8,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(C)' // M(null); // two static candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(C)").WithLocation(8, 9), // (13,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // M(null); // four candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(13, 9), // (14,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(A)' and 'Program.M(B)' // Program.M(null); // four candidates Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(A)", "Program.M(B)").WithLocation(14, 17) ); var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var invocations = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal(5, invocations.Length); var symbolInfo = model.GetSymbolInfo(invocations[0].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); symbolInfo = model.GetSymbolInfo(invocations[1].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); symbolInfo = model.GetSymbolInfo(invocations[2].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); symbolInfo = model.GetSymbolInfo(invocations[3].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); symbolInfo = model.GetSymbolInfo(invocations[4].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); } [Fact] public void TestAmbiguous02() { // test semantic model in the face of ambiguities even when there are constraint violations var source = @"class Program { public static void Main() { M(1, null); } public static void M<T>(T t, A a) where T : Constraint => throw null; public static void M<T>(T t, B b) => throw null; public static void M<T>(T t, C c) where T : Constraint => throw null; public static void M<T>(T t, D d) => throw null; } class A {} class B {} class C {} class D {} class Constraint {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, A)' and 'Program.M<T>(T, B)' // M(1, null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, A)", "Program.M<T>(T, B)").WithLocation(5, 9) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M<T>(T, B)' and 'Program.M<T>(T, D)' // M(1, null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M<T>(T, B)", "Program.M<T>(T, D)").WithLocation(5, 9) ); var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var invocations = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal(1, invocations.Length); var symbolInfo = model.GetSymbolInfo(invocations[0].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void Program.M<System.Int32>(System.Int32 t, A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void Program.M<System.Int32>(System.Int32 t, B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void Program.M<System.Int32>(System.Int32 t, C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void Program.M<System.Int32>(System.Int32 t, D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); } [Fact] public void TestAmbiguous03() { // test semantic model in the face of ambiguities even when there are constraint violations var source = @"class Program { public static void Main() { 1.M(null); } } public class A {} public class B {} public class C {} public class D {} public class Constraint {} public static class Extensions { public static void M<T>(this T t, A a) where T : Constraint => throw null; public static void M<T>(this T t, B b) => throw null; public static void M<T>(this T t, C c) where T : Constraint => throw null; public static void M<T>(this T t, D d) => throw null; } "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,11): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions.M<T>(T, A)' and 'Extensions.M<T>(T, B)' // 1.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Extensions.M<T>(T, A)", "Extensions.M<T>(T, B)").WithLocation(5, 11) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,11): error CS0121: The call is ambiguous between the following methods or properties: 'Extensions.M<T>(T, B)' and 'Extensions.M<T>(T, D)' // 1.M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Extensions.M<T>(T, B)", "Extensions.M<T>(T, D)").WithLocation(5, 11) ); var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var invocations = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal(1, invocations.Length); var symbolInfo = model.GetSymbolInfo(invocations[0].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("void System.Int32.M<System.Int32>(A a)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("void System.Int32.M<System.Int32>(B b)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("void System.Int32.M<System.Int32>(C c)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("void System.Int32.M<System.Int32>(D d)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); } [Fact] public void TestAmbiguous04() { // test semantic model in the face of ambiguities even when there are return type mismatches var source = @"class Program { public static void Main() { Invoked(Argument); } public static void Invoked(Delegate d) { } public delegate A Delegate(IZ c); static B Argument(IQ x) => null; static D Argument(IW x) => null; static C Argument(IX x) => null; static D Argument(IY x) => null; } class A {} class B: A {} class C: A {} class D {} interface IQ {} interface IW {} interface IX {} interface IY {} interface IZ: IQ, IW, IX, IY {} "; CreateCompilationWithoutBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Argument(IQ)' and 'Program.Argument(IW)' // Invoked(Argument); Diagnostic(ErrorCode.ERR_AmbigCall, "Argument").WithArguments("Program.Argument(IQ)", "Program.Argument(IW)").WithLocation(5, 17) ); var compilation = CreateCompilationWithBetterCandidates(source, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (5,17): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Argument(IQ)' and 'Program.Argument(IX)' // Invoked(Argument); Diagnostic(ErrorCode.ERR_AmbigCall, "Argument").WithArguments("Program.Argument(IQ)", "Program.Argument(IX)").WithLocation(5, 17) ); var model = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var invocations = compilation.SyntaxTrees[0].GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal(1, invocations.Length); var symbolInfo = model.GetSymbolInfo(invocations[0].ArgumentList.Arguments[0].Expression); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(4, symbolInfo.CandidateSymbols.Length); Assert.Equal("B Program.Argument(IQ x)", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal("D Program.Argument(IW x)", symbolInfo.CandidateSymbols[1].ToTestDisplayString()); Assert.Equal("C Program.Argument(IX x)", symbolInfo.CandidateSymbols[2].ToTestDisplayString()); Assert.Equal("D Program.Argument(IY x)", symbolInfo.CandidateSymbols[3].ToTestDisplayString()); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/Core/CodeAnalysisTest/Collections/SegmentedArrayTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class SegmentedArrayTests { public static IEnumerable<object[]> TestLengths { get { yield return new object[] { 1 }; yield return new object[] { 10 }; yield return new object[] { 100 }; yield return new object[] { SegmentedArray<IntPtr>.TestAccessor.SegmentSize / 2 }; yield return new object[] { SegmentedArray<IntPtr>.TestAccessor.SegmentSize }; yield return new object[] { SegmentedArray<IntPtr>.TestAccessor.SegmentSize * 2 }; yield return new object[] { 100000 }; } } private static void ResetToSequence(SegmentedArray<IntPtr> array) { for (var i = 0; i < array.Length; i++) { array[i] = (IntPtr)i; } } [Fact] public void TestDefaultInstance() { var data = default(SegmentedArray<IntPtr>); Assert.Null(data.GetTestAccessor().Items); Assert.True(data.IsFixedSize); Assert.True(data.IsReadOnly); Assert.False(data.IsSynchronized); Assert.Equal(0, data.Length); Assert.Null(data.SyncRoot); Assert.Throws<NullReferenceException>(() => data[0]); Assert.Throws<NullReferenceException>(() => ((IReadOnlyList<IntPtr>)data)[0]); Assert.Throws<NullReferenceException>(() => ((IList<IntPtr>)data)[0]); Assert.Throws<NullReferenceException>(() => ((IList<IntPtr>)data)[0] = IntPtr.Zero); Assert.Throws<NullReferenceException>(() => ((IList)data)[0]); Assert.Throws<NullReferenceException>(() => ((IList)data)[0] = IntPtr.Zero); Assert.Equal(0, ((ICollection)data).Count); Assert.Equal(0, ((ICollection<IntPtr>)data).Count); Assert.Equal(0, ((IReadOnlyCollection<IntPtr>)data).Count); Assert.Throws<NullReferenceException>(() => data.Clone()); Assert.Throws<NullReferenceException>(() => data.CopyTo(Array.Empty<IntPtr>(), 0)); Assert.Throws<NullReferenceException>(() => ((ICollection<IntPtr>)data).CopyTo(Array.Empty<IntPtr>(), 0)); var enumerator1 = data.GetEnumerator(); Assert.Throws<NullReferenceException>(() => enumerator1.MoveNext()); var enumerator2 = ((IEnumerable)data).GetEnumerator(); Assert.Throws<NullReferenceException>(() => enumerator1.MoveNext()); var enumerator3 = ((IEnumerable<IntPtr>)data).GetEnumerator(); Assert.Throws<NullReferenceException>(() => enumerator1.MoveNext()); Assert.Throws<NotSupportedException>(() => ((IList)data).Add(IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((ICollection<IntPtr>)data).Add(IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((ICollection<IntPtr>)data).Clear()); Assert.Throws<NotSupportedException>(() => ((IList)data).Insert(0, IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((IList<IntPtr>)data).Insert(0, IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((IList)data).Remove(IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((ICollection<IntPtr>)data).Remove(IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((IList)data).RemoveAt(0)); Assert.Throws<NotSupportedException>(() => ((IList<IntPtr>)data).RemoveAt(0)); Assert.Throws<NullReferenceException>(() => ((IList)data).Clear()); Assert.Throws<NullReferenceException>(() => ((IList)data).Contains(IntPtr.Zero)); Assert.Throws<NullReferenceException>(() => ((ICollection<IntPtr>)data).Contains(IntPtr.Zero)); Assert.Throws<NullReferenceException>(() => ((IList)data).IndexOf(IntPtr.Zero)); Assert.Throws<NullReferenceException>(() => ((IList<IntPtr>)data).IndexOf(IntPtr.Zero)); } [Fact] public void TestConstructor1() { Assert.Throws<ArgumentOutOfRangeException>("length", () => new SegmentedArray<byte>(-1)); Assert.Empty(new SegmentedArray<byte>(0)); Assert.Same(Array.Empty<byte[]>(), new SegmentedArray<byte>(0).GetTestAccessor().Items); } [Theory] [MemberData(nameof(TestLengths))] public void TestConstructor2(int length) { var data = new SegmentedArray<IntPtr>(length); Assert.Equal(length, data.Length); var items = data.GetTestAccessor().Items; Assert.Equal(length, items.Sum(item => item.Length)); for (var i = 0; i < items.Length - 1; i++) { Assert.Equal(SegmentedArray<IntPtr>.TestAccessor.SegmentSize, items[i].Length); Assert.True(items[i].Length <= SegmentedArray<IntPtr>.TestAccessor.SegmentSize); } } [Theory] [MemberData(nameof(TestLengths))] public void TestBasicProperties(int length) { var data = new SegmentedArray<IntPtr>(length); Assert.True(data.IsFixedSize); Assert.True(data.IsReadOnly); Assert.False(data.IsSynchronized); Assert.Equal(length, data.Length); Assert.Same(data.GetTestAccessor().Items, data.SyncRoot); Assert.Equal(length, ((ICollection)data).Count); Assert.Equal(length, ((ICollection<IntPtr>)data).Count); Assert.Equal(length, ((IReadOnlyCollection<IntPtr>)data).Count); } [Theory] [MemberData(nameof(TestLengths))] public void TestIndexer(int length) { var data = new SegmentedArray<IntPtr>(length); ResetToSequence(data); for (var i = 0; i < length; i++) { data[i] = (IntPtr)i; } for (var i = 0; i < length; i++) { Assert.Equal((IntPtr)i, data[i]); } for (var i = 0; i < length; i++) { ref var value = ref data[i]; Assert.Equal((IntPtr)i, data[i]); value = IntPtr.Add(value, 1); Assert.Equal((IntPtr)(i + 1), value); Assert.Equal((IntPtr)(i + 1), data[i]); } ResetToSequence(data); for (var i = 0; i < length; i++) { Assert.Equal((IntPtr)i, ((IReadOnlyList<IntPtr>)data)[i]); data[i] = IntPtr.Add(data[i], 1); Assert.Equal((IntPtr)(i + 1), ((IReadOnlyList<IntPtr>)data)[i]); } ResetToSequence(data); for (var i = 0; i < length; i++) { Assert.Equal((IntPtr)i, ((IList<IntPtr>)data)[i]); ((IList<IntPtr>)data)[i] = IntPtr.Add(data[i], 1); Assert.Equal((IntPtr)(i + 1), ((IList<IntPtr>)data)[i]); } ResetToSequence(data); for (var i = 0; i < length; i++) { Assert.Equal((IntPtr)i, ((IList)data)[i]); ((IList)data)[i] = IntPtr.Add(data[i], 1); Assert.Equal((IntPtr)(i + 1), ((IList)data)[i]); } } /// <summary> /// Verify that indexing and iteration match for an array with many segments. /// </summary> [Fact] public void TestIterateLargeArray() { var data = new SegmentedArray<Guid>(1000000); Assert.True(data.GetTestAccessor().Items.Length > 10); for (var i = 0; i < data.Length; i++) { data[i] = Guid.NewGuid(); Assert.NotEqual(Guid.Empty, data[i]); } var index = 0; foreach (var guid in data) { Assert.Equal(guid, data[index++]); } Assert.Equal(data.Length, index); } [Fact] public void CopyOverlappingEndOfSegment() { var array = new int[2 * SegmentedArray<int>.TestAccessor.SegmentSize]; var segmented = new SegmentedArray<int>(2 * SegmentedArray<int>.TestAccessor.SegmentSize); initialize(array, segmented); Assert.Equal(array, segmented); var sourceStart = SegmentedArray<int>.TestAccessor.SegmentSize - 128; var destinationStart = SegmentedArray<int>.TestAccessor.SegmentSize - 60; var length = 256; Array.Copy(array, sourceStart, array, destinationStart, length); SegmentedArray.Copy(segmented, sourceStart, segmented, destinationStart, length); Assert.Equal(array, segmented); initialize(array, segmented); sourceStart = SegmentedArray<int>.TestAccessor.SegmentSize - 60; destinationStart = SegmentedArray<int>.TestAccessor.SegmentSize - 128; length = 256; Array.Copy(array, sourceStart, array, destinationStart, length); SegmentedArray.Copy(segmented, sourceStart, segmented, destinationStart, length); Assert.Equal(array, segmented); static void initialize(int[] array, SegmentedArray<int> segmented) { for (int i = 0; i < array.Length; i++) { array[i] = i; segmented[i] = i; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class SegmentedArrayTests { public static IEnumerable<object[]> TestLengths { get { yield return new object[] { 1 }; yield return new object[] { 10 }; yield return new object[] { 100 }; yield return new object[] { SegmentedArray<IntPtr>.TestAccessor.SegmentSize / 2 }; yield return new object[] { SegmentedArray<IntPtr>.TestAccessor.SegmentSize }; yield return new object[] { SegmentedArray<IntPtr>.TestAccessor.SegmentSize * 2 }; yield return new object[] { 100000 }; } } private static void ResetToSequence(SegmentedArray<IntPtr> array) { for (var i = 0; i < array.Length; i++) { array[i] = (IntPtr)i; } } [Fact] public void TestDefaultInstance() { var data = default(SegmentedArray<IntPtr>); Assert.Null(data.GetTestAccessor().Items); Assert.True(data.IsFixedSize); Assert.True(data.IsReadOnly); Assert.False(data.IsSynchronized); Assert.Equal(0, data.Length); Assert.Null(data.SyncRoot); Assert.Throws<NullReferenceException>(() => data[0]); Assert.Throws<NullReferenceException>(() => ((IReadOnlyList<IntPtr>)data)[0]); Assert.Throws<NullReferenceException>(() => ((IList<IntPtr>)data)[0]); Assert.Throws<NullReferenceException>(() => ((IList<IntPtr>)data)[0] = IntPtr.Zero); Assert.Throws<NullReferenceException>(() => ((IList)data)[0]); Assert.Throws<NullReferenceException>(() => ((IList)data)[0] = IntPtr.Zero); Assert.Equal(0, ((ICollection)data).Count); Assert.Equal(0, ((ICollection<IntPtr>)data).Count); Assert.Equal(0, ((IReadOnlyCollection<IntPtr>)data).Count); Assert.Throws<NullReferenceException>(() => data.Clone()); Assert.Throws<NullReferenceException>(() => data.CopyTo(Array.Empty<IntPtr>(), 0)); Assert.Throws<NullReferenceException>(() => ((ICollection<IntPtr>)data).CopyTo(Array.Empty<IntPtr>(), 0)); var enumerator1 = data.GetEnumerator(); Assert.Throws<NullReferenceException>(() => enumerator1.MoveNext()); var enumerator2 = ((IEnumerable)data).GetEnumerator(); Assert.Throws<NullReferenceException>(() => enumerator1.MoveNext()); var enumerator3 = ((IEnumerable<IntPtr>)data).GetEnumerator(); Assert.Throws<NullReferenceException>(() => enumerator1.MoveNext()); Assert.Throws<NotSupportedException>(() => ((IList)data).Add(IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((ICollection<IntPtr>)data).Add(IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((ICollection<IntPtr>)data).Clear()); Assert.Throws<NotSupportedException>(() => ((IList)data).Insert(0, IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((IList<IntPtr>)data).Insert(0, IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((IList)data).Remove(IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((ICollection<IntPtr>)data).Remove(IntPtr.Zero)); Assert.Throws<NotSupportedException>(() => ((IList)data).RemoveAt(0)); Assert.Throws<NotSupportedException>(() => ((IList<IntPtr>)data).RemoveAt(0)); Assert.Throws<NullReferenceException>(() => ((IList)data).Clear()); Assert.Throws<NullReferenceException>(() => ((IList)data).Contains(IntPtr.Zero)); Assert.Throws<NullReferenceException>(() => ((ICollection<IntPtr>)data).Contains(IntPtr.Zero)); Assert.Throws<NullReferenceException>(() => ((IList)data).IndexOf(IntPtr.Zero)); Assert.Throws<NullReferenceException>(() => ((IList<IntPtr>)data).IndexOf(IntPtr.Zero)); } [Fact] public void TestConstructor1() { Assert.Throws<ArgumentOutOfRangeException>("length", () => new SegmentedArray<byte>(-1)); Assert.Empty(new SegmentedArray<byte>(0)); Assert.Same(Array.Empty<byte[]>(), new SegmentedArray<byte>(0).GetTestAccessor().Items); } [Theory] [MemberData(nameof(TestLengths))] public void TestConstructor2(int length) { var data = new SegmentedArray<IntPtr>(length); Assert.Equal(length, data.Length); var items = data.GetTestAccessor().Items; Assert.Equal(length, items.Sum(item => item.Length)); for (var i = 0; i < items.Length - 1; i++) { Assert.Equal(SegmentedArray<IntPtr>.TestAccessor.SegmentSize, items[i].Length); Assert.True(items[i].Length <= SegmentedArray<IntPtr>.TestAccessor.SegmentSize); } } [Theory] [MemberData(nameof(TestLengths))] public void TestBasicProperties(int length) { var data = new SegmentedArray<IntPtr>(length); Assert.True(data.IsFixedSize); Assert.True(data.IsReadOnly); Assert.False(data.IsSynchronized); Assert.Equal(length, data.Length); Assert.Same(data.GetTestAccessor().Items, data.SyncRoot); Assert.Equal(length, ((ICollection)data).Count); Assert.Equal(length, ((ICollection<IntPtr>)data).Count); Assert.Equal(length, ((IReadOnlyCollection<IntPtr>)data).Count); } [Theory] [MemberData(nameof(TestLengths))] public void TestIndexer(int length) { var data = new SegmentedArray<IntPtr>(length); ResetToSequence(data); for (var i = 0; i < length; i++) { data[i] = (IntPtr)i; } for (var i = 0; i < length; i++) { Assert.Equal((IntPtr)i, data[i]); } for (var i = 0; i < length; i++) { ref var value = ref data[i]; Assert.Equal((IntPtr)i, data[i]); value = IntPtr.Add(value, 1); Assert.Equal((IntPtr)(i + 1), value); Assert.Equal((IntPtr)(i + 1), data[i]); } ResetToSequence(data); for (var i = 0; i < length; i++) { Assert.Equal((IntPtr)i, ((IReadOnlyList<IntPtr>)data)[i]); data[i] = IntPtr.Add(data[i], 1); Assert.Equal((IntPtr)(i + 1), ((IReadOnlyList<IntPtr>)data)[i]); } ResetToSequence(data); for (var i = 0; i < length; i++) { Assert.Equal((IntPtr)i, ((IList<IntPtr>)data)[i]); ((IList<IntPtr>)data)[i] = IntPtr.Add(data[i], 1); Assert.Equal((IntPtr)(i + 1), ((IList<IntPtr>)data)[i]); } ResetToSequence(data); for (var i = 0; i < length; i++) { Assert.Equal((IntPtr)i, ((IList)data)[i]); ((IList)data)[i] = IntPtr.Add(data[i], 1); Assert.Equal((IntPtr)(i + 1), ((IList)data)[i]); } } /// <summary> /// Verify that indexing and iteration match for an array with many segments. /// </summary> [Fact] public void TestIterateLargeArray() { var data = new SegmentedArray<Guid>(1000000); Assert.True(data.GetTestAccessor().Items.Length > 10); for (var i = 0; i < data.Length; i++) { data[i] = Guid.NewGuid(); Assert.NotEqual(Guid.Empty, data[i]); } var index = 0; foreach (var guid in data) { Assert.Equal(guid, data[index++]); } Assert.Equal(data.Length, index); } [Fact] public void CopyOverlappingEndOfSegment() { var array = new int[2 * SegmentedArray<int>.TestAccessor.SegmentSize]; var segmented = new SegmentedArray<int>(2 * SegmentedArray<int>.TestAccessor.SegmentSize); initialize(array, segmented); Assert.Equal(array, segmented); var sourceStart = SegmentedArray<int>.TestAccessor.SegmentSize - 128; var destinationStart = SegmentedArray<int>.TestAccessor.SegmentSize - 60; var length = 256; Array.Copy(array, sourceStart, array, destinationStart, length); SegmentedArray.Copy(segmented, sourceStart, segmented, destinationStart, length); Assert.Equal(array, segmented); initialize(array, segmented); sourceStart = SegmentedArray<int>.TestAccessor.SegmentSize - 60; destinationStart = SegmentedArray<int>.TestAccessor.SegmentSize - 128; length = 256; Array.Copy(array, sourceStart, array, destinationStart, length); SegmentedArray.Copy(segmented, sourceStart, segmented, destinationStart, length); Assert.Equal(array, segmented); static void initialize(int[] array, SegmentedArray<int> segmented) { for (int i = 0; i < array.Length; i++) { array[i] = i; segmented[i] = i; } } } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/CSharp/Test/Emit/CodeGen/ObjectAndCollectionInitializerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class ObjectAndCollectionInitializerTests : EmitMetadataTestBase { #region "Object Initializer Tests" [Fact] public void ObjectInitializerTest_ClassType() { var source = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { x = 1, y = 2 }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 41 (0x29) .maxstack 3 IL_0000: newobj ""MemberInitializerTest..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld ""int MemberInitializerTest.x"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void MemberInitializerTest.y.set"" IL_0013: dup IL_0014: ldfld ""int MemberInitializerTest.x"" IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: callvirt ""int MemberInitializerTest.y.get"" IL_0023: call ""void System.Console.WriteLine(int)"" IL_0028: ret }"); } [Fact] public void ObjectInitializerTest_StructType() { var source = @" public struct MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { x = 1, y = 2 }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 50 (0x32) .maxstack 2 .locals init (MemberInitializerTest V_0, //i MemberInitializerTest V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""MemberInitializerTest"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int MemberInitializerTest.x"" IL_0010: ldloca.s V_1 IL_0012: ldc.i4.2 IL_0013: call ""void MemberInitializerTest.y.set"" IL_0018: ldloc.1 IL_0019: stloc.0 IL_001a: ldloc.0 IL_001b: ldfld ""int MemberInitializerTest.x"" IL_0020: call ""void System.Console.WriteLine(int)"" IL_0025: ldloca.s V_0 IL_0027: call ""readonly int MemberInitializerTest.y.get"" IL_002c: call ""void System.Console.WriteLine(int)"" IL_0031: ret }"); } [Fact] public void ObjectInitializerTest_TypeParameterType() { var source = @" public class Base { public Base() {} public int x; public int y { get; set; } public static void Main() { MemberInitializerTest<Base>.Goo(); } } public class MemberInitializerTest<T> where T: Base, new() { public static void Goo() { var i = new T() { x = 1, y = 2 }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest<T>.Goo", @" { // Code size 61 (0x3d) .maxstack 3 IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: dup IL_0006: box ""T"" IL_000b: ldc.i4.1 IL_000c: stfld ""int Base.x"" IL_0011: dup IL_0012: box ""T"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void Base.y.set"" IL_001d: dup IL_001e: box ""T"" IL_0023: ldfld ""int Base.x"" IL_0028: call ""void System.Console.WriteLine(int)"" IL_002d: box ""T"" IL_0032: callvirt ""int Base.y.get"" IL_0037: call ""void System.Console.WriteLine(int)"" IL_003c: ret }"); } [Fact] public void ObjectInitializerTest_TypeParameterType_InterfaceConstraint() { var source = @" using System; class MemberInitializerTest { static int Main() { Console.WriteLine(Goo<S>()); return 0; } static byte Goo<T>() where T : I, new() { var b = new T { X = 1 }; return b.X; } } interface I { byte X { get; set; } } struct S : I { public byte X { get; set; } } "; string expectedOutput = "1"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Goo<T>", @" { // Code size 36 (0x24) .maxstack 2 .locals init (T V_0, //b T V_1) IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: ldc.i4.1 IL_0009: constrained. ""T"" IL_000f: callvirt ""void I.X.set"" IL_0014: ldloc.1 IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: constrained. ""T"" IL_001e: callvirt ""byte I.X.get"" IL_0023: ret }"); } [Fact] public void ObjectInitializerTest_NullableType() { var source = @" using System; class MemberInitializerTest { static int Main() { Console.WriteLine(Goo<S>().Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0; } static Decimal? Goo<T>() where T : I, new() { var b = new T { X = 1.1M }; return b.X; } } interface I { Decimal? X { get; set; } } struct S : I { public Decimal? X { get; set; } }"; string expectedOutput = "1.1"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Goo<T>", @" { // Code size 51 (0x33) .maxstack 6 .locals init (T V_0, //b T V_1) IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: ldc.i4.s 11 IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: ldc.i4.1 IL_000e: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0013: newobj ""decimal?..ctor(decimal)"" IL_0018: constrained. ""T"" IL_001e: callvirt ""void I.X.set"" IL_0023: ldloc.1 IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: constrained. ""T"" IL_002d: callvirt ""decimal? I.X.get"" IL_0032: ret }"); } [Fact] public void ObjectInitializerTest_AssignWriteOnlyProperty() { var source = @" public class MemberInitializerTest { public int x; public int Prop { set { x = value; } } public static void Main() { var i = new MemberInitializerTest() { Prop = 1 }; System.Console.WriteLine(i.x); } } "; string expectedOutput = "1"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 23 (0x17) .maxstack 3 IL_0000: newobj ""MemberInitializerTest..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void MemberInitializerTest.Prop.set"" IL_000c: ldfld ""int MemberInitializerTest.x"" IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: ret }"); } [Fact] public void ObjectInitializerTest_AssignMembersOfReadOnlyField() { var source = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public readonly MemberInitializerTest m = new MemberInitializerTest(); public static void Main() { var i = new Test() { m = { x = 1, y = 2 } }; System.Console.WriteLine(i.m.x); System.Console.WriteLine(i.m.y); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 61 (0x3d) .maxstack 3 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldfld ""MemberInitializerTest Test.m"" IL_000b: ldc.i4.1 IL_000c: stfld ""int MemberInitializerTest.x"" IL_0011: dup IL_0012: ldfld ""MemberInitializerTest Test.m"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void MemberInitializerTest.y.set"" IL_001d: dup IL_001e: ldfld ""MemberInitializerTest Test.m"" IL_0023: ldfld ""int MemberInitializerTest.x"" IL_0028: call ""void System.Console.WriteLine(int)"" IL_002d: ldfld ""MemberInitializerTest Test.m"" IL_0032: callvirt ""int MemberInitializerTest.y.get"" IL_0037: call ""void System.Console.WriteLine(int)"" IL_003c: ret }"); } [Fact] public void ObjectInitializerTest_AssignFieldWithSameNameAsLocal() { var source = @" public class MemberInitializerTest { public int x; public static void Main() { int x = 1; MemberInitializerTest m = new MemberInitializerTest() { x = x + 1 }; System.Console.WriteLine(x); System.Console.WriteLine(m.x); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 33 (0x21) .maxstack 4 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""MemberInitializerTest..ctor()"" IL_0007: dup IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld ""int MemberInitializerTest.x"" IL_0010: ldloc.0 IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: ldfld ""int MemberInitializerTest.x"" IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ret }"); } [Fact] public void ObjectInitializerTest_AssignmentOrderingIsPreserved() { var source = @" public class MemberInitializerTest { public int x, y, z; public static void Main() { Goo(); } public static void Goo(MemberInitializerTest nullArg = null) { MemberInitializerTest m = new MemberInitializerTest() { x = -1, y = -1, z = -1 }; try { m = new MemberInitializerTest { x = Bar(1), y = nullArg.y, z = Bar(3) }; } catch(System.NullReferenceException) { } System.Console.WriteLine(m.x); System.Console.WriteLine(m.y); System.Console.WriteLine(m.z); } public static int Bar(int i) { System.Console.WriteLine(i); return i; } } "; string expectedOutput = @"1 -1 -1 -1"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Goo", @" { // Code size 108 (0x6c) .maxstack 3 .locals init (MemberInitializerTest V_0) //m IL_0000: newobj ""MemberInitializerTest..ctor()"" IL_0005: dup IL_0006: ldc.i4.m1 IL_0007: stfld ""int MemberInitializerTest.x"" IL_000c: dup IL_000d: ldc.i4.m1 IL_000e: stfld ""int MemberInitializerTest.y"" IL_0013: dup IL_0014: ldc.i4.m1 IL_0015: stfld ""int MemberInitializerTest.z"" IL_001a: stloc.0 .try { IL_001b: newobj ""MemberInitializerTest..ctor()"" IL_0020: dup IL_0021: ldc.i4.1 IL_0022: call ""int MemberInitializerTest.Bar(int)"" IL_0027: stfld ""int MemberInitializerTest.x"" IL_002c: dup IL_002d: ldarg.0 IL_002e: ldfld ""int MemberInitializerTest.y"" IL_0033: stfld ""int MemberInitializerTest.y"" IL_0038: dup IL_0039: ldc.i4.3 IL_003a: call ""int MemberInitializerTest.Bar(int)"" IL_003f: stfld ""int MemberInitializerTest.z"" IL_0044: stloc.0 IL_0045: leave.s IL_004a } catch System.NullReferenceException { IL_0047: pop IL_0048: leave.s IL_004a } IL_004a: ldloc.0 IL_004b: ldfld ""int MemberInitializerTest.x"" IL_0050: call ""void System.Console.WriteLine(int)"" IL_0055: ldloc.0 IL_0056: ldfld ""int MemberInitializerTest.y"" IL_005b: call ""void System.Console.WriteLine(int)"" IL_0060: ldloc.0 IL_0061: ldfld ""int MemberInitializerTest.z"" IL_0066: call ""void System.Console.WriteLine(int)"" IL_006b: ret }"); } [Fact] public void ObjectInitializerTest_NestedObjectInitializerExpression() { var source = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public int x; public int y { get; set; } public MemberInitializerTest z; public static void Main() { var i = new Test() { x = 1, y = 2, z = new MemberInitializerTest() { x = 3, y = 4 } }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); System.Console.WriteLine(i.z.x); System.Console.WriteLine(i.z.y); } } "; string expectedOutput = @"1 2 3 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 98 (0x62) .maxstack 5 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld ""int Test.x"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void Test.y.set"" IL_0013: dup IL_0014: newobj ""MemberInitializerTest..ctor()"" IL_0019: dup IL_001a: ldc.i4.3 IL_001b: stfld ""int MemberInitializerTest.x"" IL_0020: dup IL_0021: ldc.i4.4 IL_0022: callvirt ""void MemberInitializerTest.y.set"" IL_0027: stfld ""MemberInitializerTest Test.z"" IL_002c: dup IL_002d: ldfld ""int Test.x"" IL_0032: call ""void System.Console.WriteLine(int)"" IL_0037: dup IL_0038: callvirt ""int Test.y.get"" IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: dup IL_0043: ldfld ""MemberInitializerTest Test.z"" IL_0048: ldfld ""int MemberInitializerTest.x"" IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: ldfld ""MemberInitializerTest Test.z"" IL_0057: callvirt ""int MemberInitializerTest.y.get"" IL_005c: call ""void System.Console.WriteLine(int)"" IL_0061: ret }"); } [Fact()] public void ObjectInitializerTest_NestedObjectInitializer_InitializerValue() { var source = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public int x; public int y { get; set; } public readonly MemberInitializerTest z = new MemberInitializerTest(); public static void Main() { var i = new Test() { x = 1, y = 2, z = { x = 3, y = 4 } }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); System.Console.WriteLine(i.z.x); System.Console.WriteLine(i.z.y); } } "; string expectedOutput = @"1 2 3 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 97 (0x61) .maxstack 3 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld ""int Test.x"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void Test.y.set"" IL_0013: dup IL_0014: ldfld ""MemberInitializerTest Test.z"" IL_0019: ldc.i4.3 IL_001a: stfld ""int MemberInitializerTest.x"" IL_001f: dup IL_0020: ldfld ""MemberInitializerTest Test.z"" IL_0025: ldc.i4.4 IL_0026: callvirt ""void MemberInitializerTest.y.set"" IL_002b: dup IL_002c: ldfld ""int Test.x"" IL_0031: call ""void System.Console.WriteLine(int)"" IL_0036: dup IL_0037: callvirt ""int Test.y.get"" IL_003c: call ""void System.Console.WriteLine(int)"" IL_0041: dup IL_0042: ldfld ""MemberInitializerTest Test.z"" IL_0047: ldfld ""int MemberInitializerTest.x"" IL_004c: call ""void System.Console.WriteLine(int)"" IL_0051: ldfld ""MemberInitializerTest Test.z"" IL_0056: callvirt ""int MemberInitializerTest.y.get"" IL_005b: call ""void System.Console.WriteLine(int)"" IL_0060: ret }"); } [Fact] public void ObjectInitializerTest_NestedCollectionInitializerExpression() { var source = @" using System; using System.Collections.Generic; public class MemberInitializerTest { public List<int> x = new List<int>(); public List<int> y { get { return x; } set { x = value; } } } public class Test { public List<int> x = new List<int>(); public List<int> y { get { return x; } set { x = value; } } public MemberInitializerTest z; public static void Main() { var i = new Test() { x = { 1 }, y = { 2 }, z = new MemberInitializerTest() { x = { 3 }, y = { 4 } } }; DisplayCollection(i.x); DisplayCollection(i.y); DisplayCollection(i.z.x); DisplayCollection(i.z.y); } public static void DisplayCollection<T>(IEnumerable<T> collection) { foreach (var i in collection) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 1 2 3 4 3 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 118 (0x76) .maxstack 5 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldfld ""System.Collections.Generic.List<int> Test.x"" IL_000b: ldc.i4.1 IL_000c: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0011: dup IL_0012: callvirt ""System.Collections.Generic.List<int> Test.y.get"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_001d: dup IL_001e: newobj ""MemberInitializerTest..ctor()"" IL_0023: dup IL_0024: ldfld ""System.Collections.Generic.List<int> MemberInitializerTest.x"" IL_0029: ldc.i4.3 IL_002a: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_002f: dup IL_0030: callvirt ""System.Collections.Generic.List<int> MemberInitializerTest.y.get"" IL_0035: ldc.i4.4 IL_0036: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_003b: stfld ""MemberInitializerTest Test.z"" IL_0040: dup IL_0041: ldfld ""System.Collections.Generic.List<int> Test.x"" IL_0046: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_004b: dup IL_004c: callvirt ""System.Collections.Generic.List<int> Test.y.get"" IL_0051: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0056: dup IL_0057: ldfld ""MemberInitializerTest Test.z"" IL_005c: ldfld ""System.Collections.Generic.List<int> MemberInitializerTest.x"" IL_0061: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0066: ldfld ""MemberInitializerTest Test.z"" IL_006b: callvirt ""System.Collections.Generic.List<int> MemberInitializerTest.y.get"" IL_0070: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0075: ret }"); } [Fact] public void ObjectInitializerTest_NestedCollectionInitializer_InitializerValue() { var source = @" using System; using System.Collections.Generic; public class MemberInitializerTest { public List<int> x = new List<int>(); public List<int> y { get { return x; } set { x = value; } } } public class Test { public List<int> x = new List<int>(); public List<int> y { get { return x; } set { x = value; } } public MemberInitializerTest z = new MemberInitializerTest(); public static void Main() { var i = new Test() { x = { 1 }, y = { 2 }, z = { x = { 3 }, y = { 4 } } }; DisplayCollection(i.x); DisplayCollection(i.y); DisplayCollection(i.z.x); DisplayCollection(i.z.y); } public static void DisplayCollection<T>(IEnumerable<T> collection) { foreach (var i in collection) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 1 2 3 4 3 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 117 (0x75) .maxstack 3 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldfld ""System.Collections.Generic.List<int> Test.x"" IL_000b: ldc.i4.1 IL_000c: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0011: dup IL_0012: callvirt ""System.Collections.Generic.List<int> Test.y.get"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_001d: dup IL_001e: ldfld ""MemberInitializerTest Test.z"" IL_0023: ldfld ""System.Collections.Generic.List<int> MemberInitializerTest.x"" IL_0028: ldc.i4.3 IL_0029: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_002e: dup IL_002f: ldfld ""MemberInitializerTest Test.z"" IL_0034: callvirt ""System.Collections.Generic.List<int> MemberInitializerTest.y.get"" IL_0039: ldc.i4.4 IL_003a: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_003f: dup IL_0040: ldfld ""System.Collections.Generic.List<int> Test.x"" IL_0045: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_004a: dup IL_004b: callvirt ""System.Collections.Generic.List<int> Test.y.get"" IL_0050: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0055: dup IL_0056: ldfld ""MemberInitializerTest Test.z"" IL_005b: ldfld ""System.Collections.Generic.List<int> MemberInitializerTest.x"" IL_0060: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0065: ldfld ""MemberInitializerTest Test.z"" IL_006a: callvirt ""System.Collections.Generic.List<int> MemberInitializerTest.y.get"" IL_006f: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0074: ret }"); } [WorkItem(2021, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/2021")] [Fact()] public void ObjectInitializerFieldlikeEvent() { var source = @" public delegate void D(); public struct MemberInitializerTest { public event D z; public static void Main() { var i = new MemberInitializerTest() { z = null }; } }"; var compVerifier = CompileAndVerify(source, expectedOutput: ""); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 17 (0x11) .maxstack 2 .locals init (MemberInitializerTest V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""MemberInitializerTest"" IL_0008: ldloca.s V_0 IL_000a: ldnull IL_000b: stfld ""D MemberInitializerTest.z"" IL_0010: ret }"); } [Fact] public void ObjectInitializerTest_UseVariableBeingAssignedInObjectInitializer() { var source = @" public class Test { public int x, y; public static void Main() { Test m = new Test() { x = Goo(out m), y = m.x }; System.Console.WriteLine(m.x); // Print 1 System.Console.WriteLine(m.y); // Print 0 } public static int Goo(out Test m) { m = new Test() { x = 0 }; return 1; } } "; string expectedOutput = @"1 0"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (Test V_0) //m IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldloca.s V_0 IL_0008: call ""int Test.Goo(out Test)"" IL_000d: stfld ""int Test.x"" IL_0012: dup IL_0013: ldloc.0 IL_0014: ldfld ""int Test.x"" IL_0019: stfld ""int Test.y"" IL_001e: stloc.0 IL_001f: ldloc.0 IL_0020: ldfld ""int Test.x"" IL_0025: call ""void System.Console.WriteLine(int)"" IL_002a: ldloc.0 IL_002b: ldfld ""int Test.y"" IL_0030: call ""void System.Console.WriteLine(int)"" IL_0035: ret }"); } [Fact] public void DictionaryInitializerTest001() { var source = @" using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int>() {[""aaa""] = 3}; System.Console.WriteLine(x[""aaa""]); } } "; string expectedOutput = @"3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.Main", @" { // Code size 33 (0x21) .maxstack 4 IL_0000: newobj ""System.Collections.Generic.Dictionary<string, int>..ctor()"" IL_0005: dup IL_0006: ldstr ""aaa"" IL_000b: ldc.i4.3 IL_000c: callvirt ""void System.Collections.Generic.Dictionary<string, int>.this[string].set"" IL_0011: ldstr ""aaa"" IL_0016: callvirt ""int System.Collections.Generic.Dictionary<string, int>.this[string].get"" IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001() { var source = @" using System; class A { A this[int x] { get { Console.WriteLine(x); return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[x: x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 1 1 1 - - 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 86 (0x56) .maxstack 3 .locals init (int V_0, //x A V_1, int V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""A..ctor()"" IL_0007: stloc.1 IL_0008: ldloc.0 IL_0009: dup IL_000a: ldc.i4.1 IL_000b: add IL_000c: stloc.0 IL_000d: stloc.2 IL_000e: ldloc.1 IL_000f: ldloc.2 IL_0010: callvirt ""A A.this[int].get"" IL_0015: ldc.i4.1 IL_0016: stfld ""int A.X"" IL_001b: ldloc.1 IL_001c: ldloc.2 IL_001d: callvirt ""A A.this[int].get"" IL_0022: ldc.i4.1 IL_0023: stfld ""int A.Y"" IL_0028: ldloc.1 IL_0029: ldloc.2 IL_002a: callvirt ""A A.this[int].get"" IL_002f: ldc.i4.1 IL_0030: stfld ""int A.Z"" IL_0035: ldc.i4.s 45 IL_0037: call ""void System.Console.WriteLine(char)"" IL_003c: newobj ""A..ctor()"" IL_0041: pop IL_0042: ldloc.0 IL_0043: dup IL_0044: ldc.i4.1 IL_0045: add IL_0046: stloc.0 IL_0047: pop IL_0048: ldc.i4.s 45 IL_004a: call ""void System.Console.WriteLine(char)"" IL_004f: ldloc.0 IL_0050: call ""void System.Console.WriteLine(int)"" IL_0055: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001param() { var source = @" using System; class A { A this[params int[] x] { get { Console.WriteLine(x[0]); x[0] = 12345; return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 1 1 1 - - 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 113 (0x71) .maxstack 5 .locals init (int V_0, //x A V_1, int V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""A..ctor()"" IL_0007: stloc.1 IL_0008: ldloc.0 IL_0009: dup IL_000a: ldc.i4.1 IL_000b: add IL_000c: stloc.0 IL_000d: stloc.2 IL_000e: ldloc.1 IL_000f: ldc.i4.1 IL_0010: newarr ""int"" IL_0015: dup IL_0016: ldc.i4.0 IL_0017: ldloc.2 IL_0018: stelem.i4 IL_0019: callvirt ""A A.this[params int[]].get"" IL_001e: ldc.i4.1 IL_001f: stfld ""int A.X"" IL_0024: ldloc.1 IL_0025: ldc.i4.1 IL_0026: newarr ""int"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldloc.2 IL_002e: stelem.i4 IL_002f: callvirt ""A A.this[params int[]].get"" IL_0034: ldc.i4.1 IL_0035: stfld ""int A.Y"" IL_003a: ldloc.1 IL_003b: ldc.i4.1 IL_003c: newarr ""int"" IL_0041: dup IL_0042: ldc.i4.0 IL_0043: ldloc.2 IL_0044: stelem.i4 IL_0045: callvirt ""A A.this[params int[]].get"" IL_004a: ldc.i4.1 IL_004b: stfld ""int A.Z"" IL_0050: ldc.i4.s 45 IL_0052: call ""void System.Console.WriteLine(char)"" IL_0057: newobj ""A..ctor()"" IL_005c: pop IL_005d: ldloc.0 IL_005e: dup IL_005f: ldc.i4.1 IL_0060: add IL_0061: stloc.0 IL_0062: pop IL_0063: ldc.i4.s 45 IL_0065: call ""void System.Console.WriteLine(char)"" IL_006a: ldloc.0 IL_006b: call ""void System.Console.WriteLine(int)"" IL_0070: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001named() { var source = @" using System; class A { A this[int x, int y] { get { Console.WriteLine(x); Console.WriteLine(y); return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[y: x++, x: x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[y: x++, x: x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 2 1 2 1 2 1 - - 5"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects001namedAsync() { var source = @" using System; using System.Threading.Tasks; class A { A this[int x, int y] { get { Console.WriteLine(x); Console.WriteLine(y); return new A(); } } int X, Y, Z; static void Main() { Test().Wait(); } private static async Task<int> Test() { int x = 1; new A {[y: await F(x++), x: await F(x++)] = { X = 1, Y = await F(1), Z = 1 } }; Console.WriteLine('-'); new A {[y: x++, x: x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); return 42; } private static async Task<int> F(int x) { await Task.Yield(); return x; } } "; string expectedOutput = @" 2 1 2 1 2 1 - - 5"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects001dyn() { var source = @" using System; class A { dynamic this[int x] { get { Console.WriteLine(x); return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 1 1 1 - - 3"; var compVerifier = CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects001namedDynamic() { var source = @" using System; class A { dynamic this[int x, int y] { get { Console.WriteLine(x); Console.WriteLine(y); return new A(); } } dynamic this[string x, string y] { get { throw null; } } int X, Y, Z; static void Main() { dynamic x = 1; new A {[y: x++, x: x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[y: x++, x: x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 2 1 2 1 2 1 - - 5"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects001a() { var source = @" using System; struct A { public A[] arr; int X, Y, Z; public A(int x) { X = 0; Y = 0; Z = 0; arr = new A[x]; } static void Main() { int x = 1; var v = new A(3) {arr = {[x++] = { X = 1, Y = x, Z = 3 },[x++] = { X = 1, Y = x, Z = 3 }} }; System.Console.WriteLine(v.arr[0].Y); System.Console.WriteLine(v.arr[1].Y); System.Console.WriteLine(v.arr[2].Y); } } "; string expectedOutput = @" 0 2 3"; var compVerifier = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 194 (0xc2) .maxstack 4 .locals init (int V_0, //x int V_1, int V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.3 IL_0003: newobj ""A..ctor(int)"" IL_0008: ldloc.0 IL_0009: dup IL_000a: ldc.i4.1 IL_000b: add IL_000c: stloc.0 IL_000d: stloc.1 IL_000e: dup IL_000f: ldfld ""A[] A.arr"" IL_0014: ldloc.1 IL_0015: ldelema ""A"" IL_001a: ldc.i4.1 IL_001b: stfld ""int A.X"" IL_0020: dup IL_0021: ldfld ""A[] A.arr"" IL_0026: ldloc.1 IL_0027: ldelema ""A"" IL_002c: ldloc.0 IL_002d: stfld ""int A.Y"" IL_0032: dup IL_0033: ldfld ""A[] A.arr"" IL_0038: ldloc.1 IL_0039: ldelema ""A"" IL_003e: ldc.i4.3 IL_003f: stfld ""int A.Z"" IL_0044: ldloc.0 IL_0045: dup IL_0046: ldc.i4.1 IL_0047: add IL_0048: stloc.0 IL_0049: stloc.2 IL_004a: dup IL_004b: ldfld ""A[] A.arr"" IL_0050: ldloc.2 IL_0051: ldelema ""A"" IL_0056: ldc.i4.1 IL_0057: stfld ""int A.X"" IL_005c: dup IL_005d: ldfld ""A[] A.arr"" IL_0062: ldloc.2 IL_0063: ldelema ""A"" IL_0068: ldloc.0 IL_0069: stfld ""int A.Y"" IL_006e: dup IL_006f: ldfld ""A[] A.arr"" IL_0074: ldloc.2 IL_0075: ldelema ""A"" IL_007a: ldc.i4.3 IL_007b: stfld ""int A.Z"" IL_0080: dup IL_0081: ldfld ""A[] A.arr"" IL_0086: ldc.i4.0 IL_0087: ldelema ""A"" IL_008c: ldfld ""int A.Y"" IL_0091: call ""void System.Console.WriteLine(int)"" IL_0096: dup IL_0097: ldfld ""A[] A.arr"" IL_009c: ldc.i4.1 IL_009d: ldelema ""A"" IL_00a2: ldfld ""int A.Y"" IL_00a7: call ""void System.Console.WriteLine(int)"" IL_00ac: ldfld ""A[] A.arr"" IL_00b1: ldc.i4.2 IL_00b2: ldelema ""A"" IL_00b7: ldfld ""int A.Y"" IL_00bc: call ""void System.Console.WriteLine(int)"" IL_00c1: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001a1() { var source = @" using System; struct A { private A[] _arr; public A[] arr { get { System.Console.WriteLine(""get""); return _arr; } } int X, Y, Z; public A(int x) { X = 0; Y = 0; Z = 0; _arr = new A[x]; } static void Main() { int x = 1; var v = new A(3) {arr = {[x++] = { X = 1, Y = x, Z = 3 },[x++] = { X = 1, Y = x, Z = 3 }} }; System.Console.WriteLine(""=======""); System.Console.WriteLine(v.arr[0].Y); System.Console.WriteLine(v.arr[1].Y); System.Console.WriteLine(v.arr[2].Y); } } "; string expectedOutput = @" get get get get get get ======= get 0 get 2 get 3"; var compVerifier = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 222 (0xde) .maxstack 3 .locals init (int V_0, //x A V_1, //v A V_2, int V_3, int V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.3 IL_0005: call ""A..ctor(int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: add IL_000e: stloc.0 IL_000f: stloc.3 IL_0010: ldloca.s V_2 IL_0012: call ""A[] A.arr.get"" IL_0017: ldloc.3 IL_0018: ldelema ""A"" IL_001d: ldc.i4.1 IL_001e: stfld ""int A.X"" IL_0023: ldloca.s V_2 IL_0025: call ""A[] A.arr.get"" IL_002a: ldloc.3 IL_002b: ldelema ""A"" IL_0030: ldloc.0 IL_0031: stfld ""int A.Y"" IL_0036: ldloca.s V_2 IL_0038: call ""A[] A.arr.get"" IL_003d: ldloc.3 IL_003e: ldelema ""A"" IL_0043: ldc.i4.3 IL_0044: stfld ""int A.Z"" IL_0049: ldloc.0 IL_004a: dup IL_004b: ldc.i4.1 IL_004c: add IL_004d: stloc.0 IL_004e: stloc.s V_4 IL_0050: ldloca.s V_2 IL_0052: call ""A[] A.arr.get"" IL_0057: ldloc.s V_4 IL_0059: ldelema ""A"" IL_005e: ldc.i4.1 IL_005f: stfld ""int A.X"" IL_0064: ldloca.s V_2 IL_0066: call ""A[] A.arr.get"" IL_006b: ldloc.s V_4 IL_006d: ldelema ""A"" IL_0072: ldloc.0 IL_0073: stfld ""int A.Y"" IL_0078: ldloca.s V_2 IL_007a: call ""A[] A.arr.get"" IL_007f: ldloc.s V_4 IL_0081: ldelema ""A"" IL_0086: ldc.i4.3 IL_0087: stfld ""int A.Z"" IL_008c: ldloc.2 IL_008d: stloc.1 IL_008e: ldstr ""======="" IL_0093: call ""void System.Console.WriteLine(string)"" IL_0098: ldloca.s V_1 IL_009a: call ""A[] A.arr.get"" IL_009f: ldc.i4.0 IL_00a0: ldelema ""A"" IL_00a5: ldfld ""int A.Y"" IL_00aa: call ""void System.Console.WriteLine(int)"" IL_00af: ldloca.s V_1 IL_00b1: call ""A[] A.arr.get"" IL_00b6: ldc.i4.1 IL_00b7: ldelema ""A"" IL_00bc: ldfld ""int A.Y"" IL_00c1: call ""void System.Console.WriteLine(int)"" IL_00c6: ldloca.s V_1 IL_00c8: call ""A[] A.arr.get"" IL_00cd: ldc.i4.2 IL_00ce: ldelema ""A"" IL_00d3: ldfld ""int A.Y"" IL_00d8: call ""void System.Console.WriteLine(int)"" IL_00dd: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001async() { var source = @" using System; using System.Threading.Tasks; struct A { private A[] _arr; public A[] arr { get { System.Console.WriteLine(""get""); return _arr; } } int X, Y, Z; public A(int x) { X = 0; Y = 0; Z = 0; _arr = new A[x]; } static void Main() { Test().Wait(); } private static async Task<int> Test() { int x = 1; var v = new A(3) { arr = {[x++] = { X = 1, Y = await F(x), Z = 3 },[await F(x++)] = { X = 1, Y = x, Z = await F(3) } } }; System.Console.WriteLine(""=======""); System.Console.WriteLine(v.arr[0].Y); System.Console.WriteLine(v.arr[1].Y); System.Console.WriteLine(v.arr[2].Y); return 42; } private static async Task<int> F(int x) { await Task.Yield(); return x; } } "; string expectedOutput = @" get get get get get get ======= get 0 get 2 get 3"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects002() { var source = @" using System; class A { A this[int x, int y] { get { Console.Write(x); Console.WriteLine(y); return new A(); } } A this[int x, int y, int z] { get { Console.Write(x); Console.Write(y); Console.WriteLine(z); return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[x++, 5] = { X = 1, Y = 1, Z = 1 } , [x++, 7, x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine(x); } } "; string expectedOutput = @" 15 15 15 273 273 273 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 118 (0x76) .maxstack 5 .locals init (int V_0, //x int V_1, int V_2, int V_3) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""A..ctor()"" IL_0007: ldloc.0 IL_0008: dup IL_0009: ldc.i4.1 IL_000a: add IL_000b: stloc.0 IL_000c: stloc.1 IL_000d: dup IL_000e: ldloc.1 IL_000f: ldc.i4.5 IL_0010: callvirt ""A A.this[int, int].get"" IL_0015: ldc.i4.1 IL_0016: stfld ""int A.X"" IL_001b: dup IL_001c: ldloc.1 IL_001d: ldc.i4.5 IL_001e: callvirt ""A A.this[int, int].get"" IL_0023: ldc.i4.1 IL_0024: stfld ""int A.Y"" IL_0029: dup IL_002a: ldloc.1 IL_002b: ldc.i4.5 IL_002c: callvirt ""A A.this[int, int].get"" IL_0031: ldc.i4.1 IL_0032: stfld ""int A.Z"" IL_0037: ldloc.0 IL_0038: dup IL_0039: ldc.i4.1 IL_003a: add IL_003b: stloc.0 IL_003c: stloc.2 IL_003d: ldloc.0 IL_003e: dup IL_003f: ldc.i4.1 IL_0040: add IL_0041: stloc.0 IL_0042: stloc.3 IL_0043: dup IL_0044: ldloc.2 IL_0045: ldc.i4.7 IL_0046: ldloc.3 IL_0047: callvirt ""A A.this[int, int, int].get"" IL_004c: ldc.i4.1 IL_004d: stfld ""int A.X"" IL_0052: dup IL_0053: ldloc.2 IL_0054: ldc.i4.7 IL_0055: ldloc.3 IL_0056: callvirt ""A A.this[int, int, int].get"" IL_005b: ldc.i4.1 IL_005c: stfld ""int A.Y"" IL_0061: ldloc.2 IL_0062: ldc.i4.7 IL_0063: ldloc.3 IL_0064: callvirt ""A A.this[int, int, int].get"" IL_0069: ldc.i4.1 IL_006a: stfld ""int A.Z"" IL_006f: ldloc.0 IL_0070: call ""void System.Console.WriteLine(int)"" IL_0075: ret } "); } [Fact] public void DictionaryInitializerTest002() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { var l = new cls1() { [""aaa""] = { 1, 2 }, [""bbb""] = { 42 } }; System.Console.Write(l[""bbb""][0]); System.Console.Write(l[""aaa""][1]); } class cls1 { private Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>(); public dynamic this[string value] { get { List<int> member; if (dict.TryGetValue(value, out member)) { return member; } return dict[value] = new List<int>(); } } } } "; string expectedOutput = @"422"; var compVerifier = CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTest003() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { var l = new Cls1() { [""aaa""] = { [""x""] = 1, [""y""] = 2 }, [""bbb""] = { [""z""] = 42 } }; System.Console.Write(l[""bbb""][""z""]); System.Console.Write(l[""aaa""][""y""]); } class Cls1 { private Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>(); public Dictionary<string, int> this[string arg] { get { Dictionary<string, int> member; if (dict.TryGetValue(arg, out member)) { return member; } return dict[arg] = new Dictionary<string, int>(); } } } } "; string expectedOutput = @"422"; var compVerifier = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTest004() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { var l = new Cls1() { [""aaa""] = { [""x""] = 1, [""y""] = 2 }, [""bbb""] = { [""z""] = 42 } }; System.Console.Write(l[""bbb""][""z""]); System.Console.Write(l[""aaa""][""y""]); } class Cls1 { private Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>(); public dynamic this[string arg] { get { Dictionary<string, int> member; if (dict.TryGetValue(arg, out member)) { return member; } return dict[arg] = new Dictionary<string, int>(); } } } } "; string expectedOutput = @"422"; var compVerifier = CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: expectedOutput); } [Fact, WorkItem(1073330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073330")] public void NestedIndexerInitializerArray() { var source = @" class C { int[] a = new int[2]; static void Main() { var a = new C { a = { [0] = 1, [1] = 2 } }; System.Console.Write(""{0} {1}"", a.a[0], a.a[1]); } } "; CompileAndVerify(source, expectedOutput: "1 2").VerifyIL("C.Main", @" { // Code size 61 (0x3d) .maxstack 4 .locals init (C V_0) //a IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldfld ""int[] C.a"" IL_000b: ldc.i4.0 IL_000c: ldc.i4.1 IL_000d: stelem.i4 IL_000e: dup IL_000f: ldfld ""int[] C.a"" IL_0014: ldc.i4.1 IL_0015: ldc.i4.2 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ldstr ""{0} {1}"" IL_001d: ldloc.0 IL_001e: ldfld ""int[] C.a"" IL_0023: ldc.i4.0 IL_0024: ldelem.i4 IL_0025: box ""int"" IL_002a: ldloc.0 IL_002b: ldfld ""int[] C.a"" IL_0030: ldc.i4.1 IL_0031: ldelem.i4 IL_0032: box ""int"" IL_0037: call ""void System.Console.Write(string, object, object)"" IL_003c: ret }"); } [Fact, WorkItem(1073330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073330")] public void NestedIndexerInitializerMDArray() { var source = @" class C { int[,] a = new int[2,2]; static void Main() { var a = new C { a = { [0, 0] = 1, [0, 1] = 2, [1, 0] = 3, [1, 1] = 4} }; System.Console.Write(""{0} {1} {2} {3}"", a.a[0, 0], a.a[0, 1], a.a[1, 0], a.a[1, 1]); } } "; CompileAndVerify(source, expectedOutput: "1 2 3 4").VerifyIL("C.Main", @" { // Code size 163 (0xa3) .maxstack 7 .locals init (C V_0) //a IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldfld ""int[,] C.a"" IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: ldc.i4.1 IL_000e: call ""int[*,*].Set"" IL_0013: dup IL_0014: ldfld ""int[,] C.a"" IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldc.i4.2 IL_001c: call ""int[*,*].Set"" IL_0021: dup IL_0022: ldfld ""int[,] C.a"" IL_0027: ldc.i4.1 IL_0028: ldc.i4.0 IL_0029: ldc.i4.3 IL_002a: call ""int[*,*].Set"" IL_002f: dup IL_0030: ldfld ""int[,] C.a"" IL_0035: ldc.i4.1 IL_0036: ldc.i4.1 IL_0037: ldc.i4.4 IL_0038: call ""int[*,*].Set"" IL_003d: stloc.0 IL_003e: ldstr ""{0} {1} {2} {3}"" IL_0043: ldc.i4.4 IL_0044: newarr ""object"" IL_0049: dup IL_004a: ldc.i4.0 IL_004b: ldloc.0 IL_004c: ldfld ""int[,] C.a"" IL_0051: ldc.i4.0 IL_0052: ldc.i4.0 IL_0053: call ""int[*,*].Get"" IL_0058: box ""int"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.1 IL_0060: ldloc.0 IL_0061: ldfld ""int[,] C.a"" IL_0066: ldc.i4.0 IL_0067: ldc.i4.1 IL_0068: call ""int[*,*].Get"" IL_006d: box ""int"" IL_0072: stelem.ref IL_0073: dup IL_0074: ldc.i4.2 IL_0075: ldloc.0 IL_0076: ldfld ""int[,] C.a"" IL_007b: ldc.i4.1 IL_007c: ldc.i4.0 IL_007d: call ""int[*,*].Get"" IL_0082: box ""int"" IL_0087: stelem.ref IL_0088: dup IL_0089: ldc.i4.3 IL_008a: ldloc.0 IL_008b: ldfld ""int[,] C.a"" IL_0090: ldc.i4.1 IL_0091: ldc.i4.1 IL_0092: call ""int[*,*].Get"" IL_0097: box ""int"" IL_009c: stelem.ref IL_009d: call ""void System.Console.Write(string, params object[])"" IL_00a2: ret }"); } [Fact, WorkItem(1073330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073330")] public void NestedIndexerInitializerJaggedArrayNestedInitializer() { var source = @" class C { int[][] a = new int[1][] { new int[2] }; static void Main() { var a = new C { a = { [0] = { [0] = 1, [1] = 2 } } }; System.Console.Write(""{0} {1}"", a.a[0][0], a.a[0][1]); } } "; CompileAndVerify(source, expectedOutput: "1 2").VerifyIL("C.Main", @" { // Code size 69 (0x45) .maxstack 4 .locals init (C V_0) //a IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldfld ""int[][] C.a"" IL_000b: ldc.i4.0 IL_000c: ldelem.ref IL_000d: ldc.i4.0 IL_000e: ldc.i4.1 IL_000f: stelem.i4 IL_0010: dup IL_0011: ldfld ""int[][] C.a"" IL_0016: ldc.i4.0 IL_0017: ldelem.ref IL_0018: ldc.i4.1 IL_0019: ldc.i4.2 IL_001a: stelem.i4 IL_001b: stloc.0 IL_001c: ldstr ""{0} {1}"" IL_0021: ldloc.0 IL_0022: ldfld ""int[][] C.a"" IL_0027: ldc.i4.0 IL_0028: ldelem.ref IL_0029: ldc.i4.0 IL_002a: ldelem.i4 IL_002b: box ""int"" IL_0030: ldloc.0 IL_0031: ldfld ""int[][] C.a"" IL_0036: ldc.i4.0 IL_0037: ldelem.ref IL_0038: ldc.i4.1 IL_0039: ldelem.i4 IL_003a: box ""int"" IL_003f: call ""void System.Console.Write(string, object, object)"" IL_0044: ret }"); } [Fact, WorkItem(1073330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073330")] public void NestedIndexerInitializerArrayNestedObjectInitializer() { var source = @" class C { C[] a; int b; C() { } C(bool unused) { this.a = new C[2] { new C(), new C() }; } static void Main() { var a = new C(true) { a = { [0] = { b = 1 }, [1] = { b = 2 } } }; System.Console.Write(""{0} {1}"", a.a[0].b, a.a[1].b); } } "; CompileAndVerify(source, expectedOutput: "1 2").VerifyIL("C.Main", @" { // Code size 82 (0x52) .maxstack 4 .locals init (C V_0) //a IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(bool)"" IL_0006: dup IL_0007: ldfld ""C[] C.a"" IL_000c: ldc.i4.0 IL_000d: ldelem.ref IL_000e: ldc.i4.1 IL_000f: stfld ""int C.b"" IL_0014: dup IL_0015: ldfld ""C[] C.a"" IL_001a: ldc.i4.1 IL_001b: ldelem.ref IL_001c: ldc.i4.2 IL_001d: stfld ""int C.b"" IL_0022: stloc.0 IL_0023: ldstr ""{0} {1}"" IL_0028: ldloc.0 IL_0029: ldfld ""C[] C.a"" IL_002e: ldc.i4.0 IL_002f: ldelem.ref IL_0030: ldfld ""int C.b"" IL_0035: box ""int"" IL_003a: ldloc.0 IL_003b: ldfld ""C[] C.a"" IL_0040: ldc.i4.1 IL_0041: ldelem.ref IL_0042: ldfld ""int C.b"" IL_0047: box ""int"" IL_004c: call ""void System.Console.Write(string, object, object)"" IL_0051: ret }"); } #endregion #region "Collection Initializer Tests" [Fact] public void CollectionInitializerTest_GenericList() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<int> list = new List<int>() { 1, 2, 3, 4, 5 }; DisplayCollection(list); return 0; } public static void DisplayCollection<T>(IEnumerable<T> collection) { foreach (var i in collection) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 3 4 5"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 47 (0x2f) .maxstack 3 IL_0000: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0013: dup IL_0014: ldc.i4.3 IL_0015: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_001a: dup IL_001b: ldc.i4.4 IL_001c: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0021: dup IL_0022: ldc.i4.5 IL_0023: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0028: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_002d: ldc.i4.0 IL_002e: ret }"); } [Fact] public void CollectionInitializerTest_GenericList_WithComplexElementInitializer() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<long> list = new List<long>() { 1, 2, { 4L }, { 9 }, 3L }; DisplayCollection(list); return 0; } public static void DisplayCollection<T>(IEnumerable<T> collection) { foreach (var i in collection) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 4 9 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 53 (0x35) .maxstack 3 IL_0000: newobj ""System.Collections.Generic.List<long>..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: conv.i8 IL_0008: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_000d: dup IL_000e: ldc.i4.2 IL_000f: conv.i8 IL_0010: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_0015: dup IL_0016: ldc.i4.4 IL_0017: conv.i8 IL_0018: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_001d: dup IL_001e: ldc.i4.s 9 IL_0020: conv.i8 IL_0021: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_0026: dup IL_0027: ldc.i4.3 IL_0028: conv.i8 IL_0029: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_002e: call ""void Test.DisplayCollection<long>(System.Collections.Generic.IEnumerable<long>)"" IL_0033: ldc.i4.0 IL_0034: ret }"); } [Fact] public void CollectionInitializerTest_TypeParameter() { var source = @" using System; using System.Collections; using System.Collections.Generic; class A:IEnumerable { public static List<int> list = new List<int>(); public void Add(int i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } class C<T> where T: A, new() { public void M() { T t = new T {1, 2, 3, 4, 5}; foreach (var x in t) { Console.WriteLine(x); } } } class Test { static void Main() { C<A> testC = new C<A>(); testC.M(); } } "; string expectedOutput = @"1 2 3 4 5"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("C<T>.M", @" { // Code size 117 (0x75) .maxstack 3 .locals init (System.Collections.IEnumerator V_0, System.IDisposable V_1) IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: dup IL_0006: box ""T"" IL_000b: ldc.i4.1 IL_000c: callvirt ""void A.Add(int)"" IL_0011: dup IL_0012: box ""T"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void A.Add(int)"" IL_001d: dup IL_001e: box ""T"" IL_0023: ldc.i4.3 IL_0024: callvirt ""void A.Add(int)"" IL_0029: dup IL_002a: box ""T"" IL_002f: ldc.i4.4 IL_0030: callvirt ""void A.Add(int)"" IL_0035: dup IL_0036: box ""T"" IL_003b: ldc.i4.5 IL_003c: callvirt ""void A.Add(int)"" IL_0041: box ""T"" IL_0046: callvirt ""System.Collections.IEnumerator A.GetEnumerator()"" IL_004b: stloc.0 .try { IL_004c: br.s IL_0059 IL_004e: ldloc.0 IL_004f: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0054: call ""void System.Console.WriteLine(object)"" IL_0059: ldloc.0 IL_005a: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_005f: brtrue.s IL_004e IL_0061: leave.s IL_0074 } finally { IL_0063: ldloc.0 IL_0064: isinst ""System.IDisposable"" IL_0069: stloc.1 IL_006a: ldloc.1 IL_006b: brfalse.s IL_0073 IL_006d: ldloc.1 IL_006e: callvirt ""void System.IDisposable.Dispose()"" IL_0073: endfinally } IL_0074: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_ClassType() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { B coll = new B { 1, 2, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 4 9 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 58 (0x3a) .maxstack 3 IL_0000: newobj ""B..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: conv.i8 IL_0008: callvirt ""void B.Add(long)"" IL_000d: dup IL_000e: ldc.i4.2 IL_000f: conv.i8 IL_0010: callvirt ""void B.Add(long)"" IL_0015: dup IL_0016: ldc.i4.4 IL_0017: conv.i8 IL_0018: callvirt ""void B.Add(long)"" IL_001d: dup IL_001e: ldc.i4.s 9 IL_0020: conv.i8 IL_0021: callvirt ""void B.Add(long)"" IL_0026: dup IL_0027: ldc.i4.3 IL_0028: conv.i8 IL_0029: callvirt ""void B.Add(long)"" IL_002e: callvirt ""System.Collections.IEnumerator B.GetEnumerator()"" IL_0033: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_0038: ldc.i4.0 IL_0039: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_StructType() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { B coll = new B(1) { 2, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public struct B : IEnumerable { List<object> list; public B(long i) { list = new List<object>(); Add(i); } public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 4 9 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 62 (0x3e) .maxstack 2 .locals init (B V_0, //coll B V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.1 IL_0003: conv.i8 IL_0004: call ""B..ctor(long)"" IL_0009: ldloca.s V_1 IL_000b: ldc.i4.2 IL_000c: conv.i8 IL_000d: call ""void B.Add(long)"" IL_0012: ldloca.s V_1 IL_0014: ldc.i4.4 IL_0015: conv.i8 IL_0016: call ""void B.Add(long)"" IL_001b: ldloca.s V_1 IL_001d: ldc.i4.s 9 IL_001f: conv.i8 IL_0020: call ""void B.Add(long)"" IL_0025: ldloca.s V_1 IL_0027: ldc.i4.3 IL_0028: conv.i8 IL_0029: call ""void B.Add(long)"" IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: call ""System.Collections.IEnumerator B.GetEnumerator()"" IL_0037: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_003c: ldc.i4.0 IL_003d: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_MultipleAddOverloads() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { B coll = new B { 1, 2, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public B() { } public B(int i) { } public void Add(int i) { list.Add(i); } public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 4 9 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 55 (0x37) .maxstack 3 IL_0000: newobj ""B..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void B.Add(int)"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void B.Add(int)"" IL_0013: dup IL_0014: ldc.i4.4 IL_0015: conv.i8 IL_0016: callvirt ""void B.Add(long)"" IL_001b: dup IL_001c: ldc.i4.s 9 IL_001e: callvirt ""void B.Add(int)"" IL_0023: dup IL_0024: ldc.i4.3 IL_0025: conv.i8 IL_0026: callvirt ""void B.Add(long)"" IL_002b: callvirt ""System.Collections.IEnumerator B.GetEnumerator()"" IL_0030: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_0035: ldc.i4.0 IL_0036: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_AddOverload_OptionalArgument() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { D coll = new D { 1, { 2 }, { 3, (float?)4.4 } }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { if (collection.Current.GetType() == typeof(float)) Console.WriteLine(((float)collection.Current).ToString(System.Globalization.CultureInfo.InvariantCulture)); else Console.WriteLine(collection.Current); } } } public class D : IEnumerable { List<object> list = new List<object>(); public D() { } public void Add(int i, float? j = null) { list.Add(i); if (j.HasValue) { list.Add(j); } } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 3 4.4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 66 (0x42) .maxstack 4 .locals init (float? V_0) IL_0000: newobj ""D..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: ldloca.s V_0 IL_0009: initobj ""float?"" IL_000f: ldloc.0 IL_0010: callvirt ""void D.Add(int, float?)"" IL_0015: dup IL_0016: ldc.i4.2 IL_0017: ldloca.s V_0 IL_0019: initobj ""float?"" IL_001f: ldloc.0 IL_0020: callvirt ""void D.Add(int, float?)"" IL_0025: dup IL_0026: ldc.i4.3 IL_0027: ldc.r4 4.4 IL_002c: newobj ""float?..ctor(float)"" IL_0031: callvirt ""void D.Add(int, float?)"" IL_0036: callvirt ""System.Collections.IEnumerator D.GetEnumerator()"" IL_003b: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_0040: ldc.i4.0 IL_0041: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_AddOverload_ParamsArrayArgument() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var implicitTypedArr = new[] { 7.7, 8.8 }; D coll = new D { 1, { 2 }, { 3, 4.4 }, new double[] { 5, 6 }, implicitTypedArr, null }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { if (collection.Current.GetType() == typeof(double)) Console.WriteLine(((double)collection.Current).ToString(System.Globalization.CultureInfo.InvariantCulture)); else Console.WriteLine(collection.Current); } } } public class D : IEnumerable { List<object> list = new List<object>(); public D() { } public void Add(params double[] i) { if (i != null) { foreach (var x in i) { list.Add(x); } } } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 3 4.4 5 6 7.7 8.8"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 184 (0xb8) .maxstack 5 .locals init (double[] V_0, //implicitTypedArr D V_1) IL_0000: ldc.i4.2 IL_0001: newarr ""double"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.r8 7.7 IL_0011: stelem.r8 IL_0012: dup IL_0013: ldc.i4.1 IL_0014: ldc.r8 8.8 IL_001d: stelem.r8 IL_001e: stloc.0 IL_001f: newobj ""D..ctor()"" IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: ldc.i4.1 IL_0027: newarr ""double"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.r8 1 IL_0037: stelem.r8 IL_0038: callvirt ""void D.Add(params double[])"" IL_003d: ldloc.1 IL_003e: ldc.i4.1 IL_003f: newarr ""double"" IL_0044: dup IL_0045: ldc.i4.0 IL_0046: ldc.r8 2 IL_004f: stelem.r8 IL_0050: callvirt ""void D.Add(params double[])"" IL_0055: ldloc.1 IL_0056: ldc.i4.2 IL_0057: newarr ""double"" IL_005c: dup IL_005d: ldc.i4.0 IL_005e: ldc.r8 3 IL_0067: stelem.r8 IL_0068: dup IL_0069: ldc.i4.1 IL_006a: ldc.r8 4.4 IL_0073: stelem.r8 IL_0074: callvirt ""void D.Add(params double[])"" IL_0079: ldloc.1 IL_007a: ldc.i4.2 IL_007b: newarr ""double"" IL_0080: dup IL_0081: ldc.i4.0 IL_0082: ldc.r8 5 IL_008b: stelem.r8 IL_008c: dup IL_008d: ldc.i4.1 IL_008e: ldc.r8 6 IL_0097: stelem.r8 IL_0098: callvirt ""void D.Add(params double[])"" IL_009d: ldloc.1 IL_009e: ldloc.0 IL_009f: callvirt ""void D.Add(params double[])"" IL_00a4: ldloc.1 IL_00a5: ldnull IL_00a6: callvirt ""void D.Add(params double[])"" IL_00ab: ldloc.1 IL_00ac: callvirt ""System.Collections.IEnumerator D.GetEnumerator()"" IL_00b1: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_00b6: ldc.i4.0 IL_00b7: ret }"); } [Fact] public void CollectionInitializerTest_NestedCollectionInitializerExpression() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var listOfList = new List<List<int>>() { new List<int> { 1, 2, 3, 4, 5 }, new List<int> { 6, 7, 8, 9, 10 } }; DisplayCollectionOfCollection(listOfList); return 0; } public static void DisplayCollectionOfCollection(IEnumerable<List<int>> collectionOfCollection) { foreach (var collection in collectionOfCollection) { foreach (var i in collection) { Console.WriteLine(i); } } } } "; string expectedOutput = @"1 2 3 4 5 6 7 8 9 10"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 106 (0x6a) .maxstack 5 IL_0000: newobj ""System.Collections.Generic.List<System.Collections.Generic.List<int>>..ctor()"" IL_0005: dup IL_0006: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_000b: dup IL_000c: ldc.i4.1 IL_000d: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0012: dup IL_0013: ldc.i4.2 IL_0014: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0019: dup IL_001a: ldc.i4.3 IL_001b: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0020: dup IL_0021: ldc.i4.4 IL_0022: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0027: dup IL_0028: ldc.i4.5 IL_0029: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_002e: callvirt ""void System.Collections.Generic.List<System.Collections.Generic.List<int>>.Add(System.Collections.Generic.List<int>)"" IL_0033: dup IL_0034: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0039: dup IL_003a: ldc.i4.6 IL_003b: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0040: dup IL_0041: ldc.i4.7 IL_0042: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0047: dup IL_0048: ldc.i4.8 IL_0049: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_004e: dup IL_004f: ldc.i4.s 9 IL_0051: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0056: dup IL_0057: ldc.i4.s 10 IL_0059: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_005e: callvirt ""void System.Collections.Generic.List<System.Collections.Generic.List<int>>.Add(System.Collections.Generic.List<int>)"" IL_0063: call ""void Test.DisplayCollectionOfCollection(System.Collections.Generic.IEnumerable<System.Collections.Generic.List<int>>)"" IL_0068: ldc.i4.0 IL_0069: ret }"); } [Fact] public void CollectionInitializerTest_NestedObjectAndCollectionInitializer() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var coll = new List<B> { new B(0) { list = new List<int>() { 1, 2, 3 } }, new B(1) { list = { 2, 3 } } }; DisplayCollection(coll); return 0; } public static void DisplayCollection(IEnumerable<B> collection) { foreach (var i in collection) { i.Display(); } } } public class B { public List<int> list = new List<int>(); public B() { } public B(int i) { list.Add(i); } public void Display() { foreach (var i in list) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 3 1 2 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: newobj ""System.Collections.Generic.List<B>..ctor()"" IL_0005: dup IL_0006: ldc.i4.0 IL_0007: newobj ""B..ctor(int)"" IL_000c: dup IL_000d: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0019: dup IL_001a: ldc.i4.2 IL_001b: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0020: dup IL_0021: ldc.i4.3 IL_0022: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0027: stfld ""System.Collections.Generic.List<int> B.list"" IL_002c: callvirt ""void System.Collections.Generic.List<B>.Add(B)"" IL_0031: dup IL_0032: ldc.i4.1 IL_0033: newobj ""B..ctor(int)"" IL_0038: dup IL_0039: ldfld ""System.Collections.Generic.List<int> B.list"" IL_003e: ldc.i4.2 IL_003f: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0044: dup IL_0045: ldfld ""System.Collections.Generic.List<int> B.list"" IL_004a: ldc.i4.3 IL_004b: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0050: callvirt ""void System.Collections.Generic.List<B>.Add(B)"" IL_0055: call ""void Test.DisplayCollection(System.Collections.Generic.IEnumerable<B>)"" IL_005a: ldc.i4.0 IL_005b: ret }"); } [Fact] public void CollectionInitializerTest_CtorAddsToCollection() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { B coll = new B(1) { 2 }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public B() { } public B(int i) { list.Add(i); } public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 3 IL_0000: ldc.i4.1 IL_0001: newobj ""B..ctor(int)"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: conv.i8 IL_0009: callvirt ""void B.Add(long)"" IL_000e: callvirt ""System.Collections.IEnumerator B.GetEnumerator()"" IL_0013: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_0018: ldc.i4.0 IL_0019: ret }"); } [Fact] public void CollectionInitializerTest_NestedObjectAndCollectionInitializer_02() { // -------------------------------------------------------------------------------------------- // SPEC: 7.6.10.3 Collection initializers // -------------------------------------------------------------------------------------------- // // SPEC: The following class represents a contact with a name and a list of phone numbers: // // SPEC: public class Contact // SPEC: { // SPEC: string name; // SPEC: List<string> phoneNumbers = new List<string>(); // SPEC: public string Name { get { return name; } set { name = value; } } // SPEC: public List<string> PhoneNumbers { get { return phoneNumbers; } } // SPEC: } // // SPEC: A List<Contact> can be created and initialized as follows: // // SPEC: var contacts = new List<Contact> { // SPEC: new Contact { // SPEC: Name = "Chris Smith", // SPEC: PhoneNumbers = { "206-555-0101", "425-882-8080" } // SPEC: }, // SPEC: new Contact { // SPEC: Name = "Bob Harris", // SPEC: PhoneNumbers = { "650-555-0199" } // SPEC: } // SPEC: }; // // SPEC: which has the same effect as // // SPEC: var __clist = new List<Contact>(); // SPEC: Contact __c1 = new Contact(); // SPEC: __c1.Name = "Chris Smith"; // SPEC: __c1.PhoneNumbers.Add("206-555-0101"); // SPEC: __c1.PhoneNumbers.Add("425-882-8080"); // SPEC: __clist.Add(__c1); // SPEC: Contact __c2 = new Contact(); // SPEC: __c2.Name = "Bob Harris"; // SPEC: __c2.PhoneNumbers.Add("650-555-0199"); // SPEC: __clist.Add(__c2); // SPEC: var contacts = __clist; // // SPEC: where __clist, __c1 and __c2 are temporary variables that are otherwise invisible and inaccessible. var source = @" using System; using System.Collections.Generic; using System.Collections; public class Contact { string name; List<string> phoneNumbers = new List<string>(); public string Name { get { return name; } set { name = value; } } public List<string> PhoneNumbers { get { return phoneNumbers; } } public void DisplayContact() { Console.WriteLine(""Name:"" + name); Console.WriteLine(""PH:""); foreach (var ph in phoneNumbers) { Console.WriteLine(ph); } } } class Test { public static void Main() { var contacts = new List<Contact> { new Contact { Name = ""Chris Smith"", PhoneNumbers = { ""206-555-0101"", ""425-882-8080"" } }, new Contact { Name = ""Bob Harris"", PhoneNumbers = { ""650-555-0199"" } } }; DisplayContacts(contacts); } public static void DisplayContacts(IEnumerable<Contact> contacts) { foreach (var contact in contacts) { contact.DisplayContact(); } } } "; string expectedOutput = @"Name:Chris Smith PH: 206-555-0101 425-882-8080 Name:Bob Harris PH: 650-555-0199"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 103 (0x67) .maxstack 5 IL_0000: newobj ""System.Collections.Generic.List<Contact>..ctor()"" IL_0005: dup IL_0006: newobj ""Contact..ctor()"" IL_000b: dup IL_000c: ldstr ""Chris Smith"" IL_0011: callvirt ""void Contact.Name.set"" IL_0016: dup IL_0017: callvirt ""System.Collections.Generic.List<string> Contact.PhoneNumbers.get"" IL_001c: ldstr ""206-555-0101"" IL_0021: callvirt ""void System.Collections.Generic.List<string>.Add(string)"" IL_0026: dup IL_0027: callvirt ""System.Collections.Generic.List<string> Contact.PhoneNumbers.get"" IL_002c: ldstr ""425-882-8080"" IL_0031: callvirt ""void System.Collections.Generic.List<string>.Add(string)"" IL_0036: callvirt ""void System.Collections.Generic.List<Contact>.Add(Contact)"" IL_003b: dup IL_003c: newobj ""Contact..ctor()"" IL_0041: dup IL_0042: ldstr ""Bob Harris"" IL_0047: callvirt ""void Contact.Name.set"" IL_004c: dup IL_004d: callvirt ""System.Collections.Generic.List<string> Contact.PhoneNumbers.get"" IL_0052: ldstr ""650-555-0199"" IL_0057: callvirt ""void System.Collections.Generic.List<string>.Add(string)"" IL_005c: callvirt ""void System.Collections.Generic.List<Contact>.Add(Contact)"" IL_0061: call ""void Test.DisplayContacts(System.Collections.Generic.IEnumerable<Contact>)"" IL_0066: ret }"); } [Fact] public void PartialAddMethods() { var source = @" using System; using System.Collections; partial class C : IEnumerable { public IEnumerator GetEnumerator() { return null; } partial void Add(int i); partial void Add(char c); partial void Add(char c) { } static void Main() { Console.WriteLine(new C { 1, 2, 3 }); // all removed Console.WriteLine(new C { 1, 'b', 3 }); // some removed Console.WriteLine(new C { 'a', 'b', 'c' }); // none removed } }"; CompileAndVerify(source).VerifyIL("C.Main", @" { // Code size 63 (0x3f) .maxstack 3 IL_0000: newobj ""C..ctor()"" IL_0005: call ""void System.Console.WriteLine(object)"" IL_000a: newobj ""C..ctor()"" IL_000f: dup IL_0010: ldc.i4.s 98 IL_0012: callvirt ""void C.Add(char)"" IL_0017: call ""void System.Console.WriteLine(object)"" IL_001c: newobj ""C..ctor()"" IL_0021: dup IL_0022: ldc.i4.s 97 IL_0024: callvirt ""void C.Add(char)"" IL_0029: dup IL_002a: ldc.i4.s 98 IL_002c: callvirt ""void C.Add(char)"" IL_0031: dup IL_0032: ldc.i4.s 99 IL_0034: callvirt ""void C.Add(char)"" IL_0039: call ""void System.Console.WriteLine(object)"" IL_003e: ret } "); } [Fact, WorkItem(1089276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089276")] public void PointerIndexing_01() { var source = @" unsafe class C { int* X; static void Main() { var array = new[] { 0 }; fixed (int* p = array) { new C(p) { X = {[0] = 1 } }; } System.Console.WriteLine(array[0]); } C(int* x) { X = x; } }"; CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), expectedOutput: "1", verify: Verification.Fails); } [Fact, WorkItem(1089276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089276")] public void PointerIndexing_02() { var source = @" unsafe class C { int** X; static void Main() { var array = new[] { 0, 0 }; fixed (int* p = array) { var array2 = new[] { p }; fixed (int** pp = array2 ) { new C(pp) { X = {[Index] = {[0] = 2, [1] = 3} } }; } } System.Console.WriteLine(array[0]); System.Console.WriteLine(array[1]); } static int Index { get { System.Console.WriteLine(""get_Index""); return 0; } } C(int** x) { X = x; } }"; CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"get_Index 2 3"); } [Fact] [WorkItem(38726, "https://github.com/dotnet/roslyn/issues/38726")] public void CollectionInitializerBoxingConversion_01() { var source = @"using System; using System.Collections; interface IAppend { void Append(object o); } struct S1 { internal S2 S2; } struct S2 : IEnumerable, IAppend { IEnumerator IEnumerable.GetEnumerator() => null; void IAppend.Append(object o) { } } static class Program { static void Add(this IAppend x, object y) { x.Append(y); Console.Write(y); } static void Main() { _ = new S2() { 1, 2 }; _ = new S1() { S2 = { 3, 4 } }; } }"; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "1234"); } [Fact] [WorkItem(38726, "https://github.com/dotnet/roslyn/issues/38726")] public void CollectionInitializerBoxingConversion_02() { var source = @"using System; using System.Collections; interface IAppend { void Append(object o); } struct S : IEnumerable, IAppend { IEnumerator IEnumerable.GetEnumerator() => null; void IAppend.Append(object o) { } } static class Program { static void Add(this IAppend x, object y) { x.Append(y); Console.Write(y); } static T F<T>() where T : IEnumerable, IAppend, new() { return new T() { 1, 2 }; } static void Main() { _ = F<S>(); } }"; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "12"); } #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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class ObjectAndCollectionInitializerTests : EmitMetadataTestBase { #region "Object Initializer Tests" [Fact] public void ObjectInitializerTest_ClassType() { var source = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { x = 1, y = 2 }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 41 (0x29) .maxstack 3 IL_0000: newobj ""MemberInitializerTest..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld ""int MemberInitializerTest.x"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void MemberInitializerTest.y.set"" IL_0013: dup IL_0014: ldfld ""int MemberInitializerTest.x"" IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: callvirt ""int MemberInitializerTest.y.get"" IL_0023: call ""void System.Console.WriteLine(int)"" IL_0028: ret }"); } [Fact] public void ObjectInitializerTest_StructType() { var source = @" public struct MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { x = 1, y = 2 }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 50 (0x32) .maxstack 2 .locals init (MemberInitializerTest V_0, //i MemberInitializerTest V_1) IL_0000: ldloca.s V_1 IL_0002: initobj ""MemberInitializerTest"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int MemberInitializerTest.x"" IL_0010: ldloca.s V_1 IL_0012: ldc.i4.2 IL_0013: call ""void MemberInitializerTest.y.set"" IL_0018: ldloc.1 IL_0019: stloc.0 IL_001a: ldloc.0 IL_001b: ldfld ""int MemberInitializerTest.x"" IL_0020: call ""void System.Console.WriteLine(int)"" IL_0025: ldloca.s V_0 IL_0027: call ""readonly int MemberInitializerTest.y.get"" IL_002c: call ""void System.Console.WriteLine(int)"" IL_0031: ret }"); } [Fact] public void ObjectInitializerTest_TypeParameterType() { var source = @" public class Base { public Base() {} public int x; public int y { get; set; } public static void Main() { MemberInitializerTest<Base>.Goo(); } } public class MemberInitializerTest<T> where T: Base, new() { public static void Goo() { var i = new T() { x = 1, y = 2 }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest<T>.Goo", @" { // Code size 61 (0x3d) .maxstack 3 IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: dup IL_0006: box ""T"" IL_000b: ldc.i4.1 IL_000c: stfld ""int Base.x"" IL_0011: dup IL_0012: box ""T"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void Base.y.set"" IL_001d: dup IL_001e: box ""T"" IL_0023: ldfld ""int Base.x"" IL_0028: call ""void System.Console.WriteLine(int)"" IL_002d: box ""T"" IL_0032: callvirt ""int Base.y.get"" IL_0037: call ""void System.Console.WriteLine(int)"" IL_003c: ret }"); } [Fact] public void ObjectInitializerTest_TypeParameterType_InterfaceConstraint() { var source = @" using System; class MemberInitializerTest { static int Main() { Console.WriteLine(Goo<S>()); return 0; } static byte Goo<T>() where T : I, new() { var b = new T { X = 1 }; return b.X; } } interface I { byte X { get; set; } } struct S : I { public byte X { get; set; } } "; string expectedOutput = "1"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Goo<T>", @" { // Code size 36 (0x24) .maxstack 2 .locals init (T V_0, //b T V_1) IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: ldc.i4.1 IL_0009: constrained. ""T"" IL_000f: callvirt ""void I.X.set"" IL_0014: ldloc.1 IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: constrained. ""T"" IL_001e: callvirt ""byte I.X.get"" IL_0023: ret }"); } [Fact] public void ObjectInitializerTest_NullableType() { var source = @" using System; class MemberInitializerTest { static int Main() { Console.WriteLine(Goo<S>().Value.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0; } static Decimal? Goo<T>() where T : I, new() { var b = new T { X = 1.1M }; return b.X; } } interface I { Decimal? X { get; set; } } struct S : I { public Decimal? X { get; set; } }"; string expectedOutput = "1.1"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Goo<T>", @" { // Code size 51 (0x33) .maxstack 6 .locals init (T V_0, //b T V_1) IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: stloc.1 IL_0006: ldloca.s V_1 IL_0008: ldc.i4.s 11 IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: ldc.i4.1 IL_000e: newobj ""decimal..ctor(int, int, int, bool, byte)"" IL_0013: newobj ""decimal?..ctor(decimal)"" IL_0018: constrained. ""T"" IL_001e: callvirt ""void I.X.set"" IL_0023: ldloc.1 IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: constrained. ""T"" IL_002d: callvirt ""decimal? I.X.get"" IL_0032: ret }"); } [Fact] public void ObjectInitializerTest_AssignWriteOnlyProperty() { var source = @" public class MemberInitializerTest { public int x; public int Prop { set { x = value; } } public static void Main() { var i = new MemberInitializerTest() { Prop = 1 }; System.Console.WriteLine(i.x); } } "; string expectedOutput = "1"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 23 (0x17) .maxstack 3 IL_0000: newobj ""MemberInitializerTest..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void MemberInitializerTest.Prop.set"" IL_000c: ldfld ""int MemberInitializerTest.x"" IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: ret }"); } [Fact] public void ObjectInitializerTest_AssignMembersOfReadOnlyField() { var source = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public readonly MemberInitializerTest m = new MemberInitializerTest(); public static void Main() { var i = new Test() { m = { x = 1, y = 2 } }; System.Console.WriteLine(i.m.x); System.Console.WriteLine(i.m.y); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 61 (0x3d) .maxstack 3 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldfld ""MemberInitializerTest Test.m"" IL_000b: ldc.i4.1 IL_000c: stfld ""int MemberInitializerTest.x"" IL_0011: dup IL_0012: ldfld ""MemberInitializerTest Test.m"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void MemberInitializerTest.y.set"" IL_001d: dup IL_001e: ldfld ""MemberInitializerTest Test.m"" IL_0023: ldfld ""int MemberInitializerTest.x"" IL_0028: call ""void System.Console.WriteLine(int)"" IL_002d: ldfld ""MemberInitializerTest Test.m"" IL_0032: callvirt ""int MemberInitializerTest.y.get"" IL_0037: call ""void System.Console.WriteLine(int)"" IL_003c: ret }"); } [Fact] public void ObjectInitializerTest_AssignFieldWithSameNameAsLocal() { var source = @" public class MemberInitializerTest { public int x; public static void Main() { int x = 1; MemberInitializerTest m = new MemberInitializerTest() { x = x + 1 }; System.Console.WriteLine(x); System.Console.WriteLine(m.x); } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 33 (0x21) .maxstack 4 .locals init (int V_0) //x IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""MemberInitializerTest..ctor()"" IL_0007: dup IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: add IL_000b: stfld ""int MemberInitializerTest.x"" IL_0010: ldloc.0 IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: ldfld ""int MemberInitializerTest.x"" IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ret }"); } [Fact] public void ObjectInitializerTest_AssignmentOrderingIsPreserved() { var source = @" public class MemberInitializerTest { public int x, y, z; public static void Main() { Goo(); } public static void Goo(MemberInitializerTest nullArg = null) { MemberInitializerTest m = new MemberInitializerTest() { x = -1, y = -1, z = -1 }; try { m = new MemberInitializerTest { x = Bar(1), y = nullArg.y, z = Bar(3) }; } catch(System.NullReferenceException) { } System.Console.WriteLine(m.x); System.Console.WriteLine(m.y); System.Console.WriteLine(m.z); } public static int Bar(int i) { System.Console.WriteLine(i); return i; } } "; string expectedOutput = @"1 -1 -1 -1"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("MemberInitializerTest.Goo", @" { // Code size 108 (0x6c) .maxstack 3 .locals init (MemberInitializerTest V_0) //m IL_0000: newobj ""MemberInitializerTest..ctor()"" IL_0005: dup IL_0006: ldc.i4.m1 IL_0007: stfld ""int MemberInitializerTest.x"" IL_000c: dup IL_000d: ldc.i4.m1 IL_000e: stfld ""int MemberInitializerTest.y"" IL_0013: dup IL_0014: ldc.i4.m1 IL_0015: stfld ""int MemberInitializerTest.z"" IL_001a: stloc.0 .try { IL_001b: newobj ""MemberInitializerTest..ctor()"" IL_0020: dup IL_0021: ldc.i4.1 IL_0022: call ""int MemberInitializerTest.Bar(int)"" IL_0027: stfld ""int MemberInitializerTest.x"" IL_002c: dup IL_002d: ldarg.0 IL_002e: ldfld ""int MemberInitializerTest.y"" IL_0033: stfld ""int MemberInitializerTest.y"" IL_0038: dup IL_0039: ldc.i4.3 IL_003a: call ""int MemberInitializerTest.Bar(int)"" IL_003f: stfld ""int MemberInitializerTest.z"" IL_0044: stloc.0 IL_0045: leave.s IL_004a } catch System.NullReferenceException { IL_0047: pop IL_0048: leave.s IL_004a } IL_004a: ldloc.0 IL_004b: ldfld ""int MemberInitializerTest.x"" IL_0050: call ""void System.Console.WriteLine(int)"" IL_0055: ldloc.0 IL_0056: ldfld ""int MemberInitializerTest.y"" IL_005b: call ""void System.Console.WriteLine(int)"" IL_0060: ldloc.0 IL_0061: ldfld ""int MemberInitializerTest.z"" IL_0066: call ""void System.Console.WriteLine(int)"" IL_006b: ret }"); } [Fact] public void ObjectInitializerTest_NestedObjectInitializerExpression() { var source = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public int x; public int y { get; set; } public MemberInitializerTest z; public static void Main() { var i = new Test() { x = 1, y = 2, z = new MemberInitializerTest() { x = 3, y = 4 } }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); System.Console.WriteLine(i.z.x); System.Console.WriteLine(i.z.y); } } "; string expectedOutput = @"1 2 3 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 98 (0x62) .maxstack 5 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld ""int Test.x"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void Test.y.set"" IL_0013: dup IL_0014: newobj ""MemberInitializerTest..ctor()"" IL_0019: dup IL_001a: ldc.i4.3 IL_001b: stfld ""int MemberInitializerTest.x"" IL_0020: dup IL_0021: ldc.i4.4 IL_0022: callvirt ""void MemberInitializerTest.y.set"" IL_0027: stfld ""MemberInitializerTest Test.z"" IL_002c: dup IL_002d: ldfld ""int Test.x"" IL_0032: call ""void System.Console.WriteLine(int)"" IL_0037: dup IL_0038: callvirt ""int Test.y.get"" IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: dup IL_0043: ldfld ""MemberInitializerTest Test.z"" IL_0048: ldfld ""int MemberInitializerTest.x"" IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: ldfld ""MemberInitializerTest Test.z"" IL_0057: callvirt ""int MemberInitializerTest.y.get"" IL_005c: call ""void System.Console.WriteLine(int)"" IL_0061: ret }"); } [Fact()] public void ObjectInitializerTest_NestedObjectInitializer_InitializerValue() { var source = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public int x; public int y { get; set; } public readonly MemberInitializerTest z = new MemberInitializerTest(); public static void Main() { var i = new Test() { x = 1, y = 2, z = { x = 3, y = 4 } }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); System.Console.WriteLine(i.z.x); System.Console.WriteLine(i.z.y); } } "; string expectedOutput = @"1 2 3 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 97 (0x61) .maxstack 3 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: stfld ""int Test.x"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void Test.y.set"" IL_0013: dup IL_0014: ldfld ""MemberInitializerTest Test.z"" IL_0019: ldc.i4.3 IL_001a: stfld ""int MemberInitializerTest.x"" IL_001f: dup IL_0020: ldfld ""MemberInitializerTest Test.z"" IL_0025: ldc.i4.4 IL_0026: callvirt ""void MemberInitializerTest.y.set"" IL_002b: dup IL_002c: ldfld ""int Test.x"" IL_0031: call ""void System.Console.WriteLine(int)"" IL_0036: dup IL_0037: callvirt ""int Test.y.get"" IL_003c: call ""void System.Console.WriteLine(int)"" IL_0041: dup IL_0042: ldfld ""MemberInitializerTest Test.z"" IL_0047: ldfld ""int MemberInitializerTest.x"" IL_004c: call ""void System.Console.WriteLine(int)"" IL_0051: ldfld ""MemberInitializerTest Test.z"" IL_0056: callvirt ""int MemberInitializerTest.y.get"" IL_005b: call ""void System.Console.WriteLine(int)"" IL_0060: ret }"); } [Fact] public void ObjectInitializerTest_NestedCollectionInitializerExpression() { var source = @" using System; using System.Collections.Generic; public class MemberInitializerTest { public List<int> x = new List<int>(); public List<int> y { get { return x; } set { x = value; } } } public class Test { public List<int> x = new List<int>(); public List<int> y { get { return x; } set { x = value; } } public MemberInitializerTest z; public static void Main() { var i = new Test() { x = { 1 }, y = { 2 }, z = new MemberInitializerTest() { x = { 3 }, y = { 4 } } }; DisplayCollection(i.x); DisplayCollection(i.y); DisplayCollection(i.z.x); DisplayCollection(i.z.y); } public static void DisplayCollection<T>(IEnumerable<T> collection) { foreach (var i in collection) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 1 2 3 4 3 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 118 (0x76) .maxstack 5 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldfld ""System.Collections.Generic.List<int> Test.x"" IL_000b: ldc.i4.1 IL_000c: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0011: dup IL_0012: callvirt ""System.Collections.Generic.List<int> Test.y.get"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_001d: dup IL_001e: newobj ""MemberInitializerTest..ctor()"" IL_0023: dup IL_0024: ldfld ""System.Collections.Generic.List<int> MemberInitializerTest.x"" IL_0029: ldc.i4.3 IL_002a: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_002f: dup IL_0030: callvirt ""System.Collections.Generic.List<int> MemberInitializerTest.y.get"" IL_0035: ldc.i4.4 IL_0036: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_003b: stfld ""MemberInitializerTest Test.z"" IL_0040: dup IL_0041: ldfld ""System.Collections.Generic.List<int> Test.x"" IL_0046: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_004b: dup IL_004c: callvirt ""System.Collections.Generic.List<int> Test.y.get"" IL_0051: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0056: dup IL_0057: ldfld ""MemberInitializerTest Test.z"" IL_005c: ldfld ""System.Collections.Generic.List<int> MemberInitializerTest.x"" IL_0061: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0066: ldfld ""MemberInitializerTest Test.z"" IL_006b: callvirt ""System.Collections.Generic.List<int> MemberInitializerTest.y.get"" IL_0070: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0075: ret }"); } [Fact] public void ObjectInitializerTest_NestedCollectionInitializer_InitializerValue() { var source = @" using System; using System.Collections.Generic; public class MemberInitializerTest { public List<int> x = new List<int>(); public List<int> y { get { return x; } set { x = value; } } } public class Test { public List<int> x = new List<int>(); public List<int> y { get { return x; } set { x = value; } } public MemberInitializerTest z = new MemberInitializerTest(); public static void Main() { var i = new Test() { x = { 1 }, y = { 2 }, z = { x = { 3 }, y = { 4 } } }; DisplayCollection(i.x); DisplayCollection(i.y); DisplayCollection(i.z.x); DisplayCollection(i.z.y); } public static void DisplayCollection<T>(IEnumerable<T> collection) { foreach (var i in collection) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 1 2 3 4 3 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 117 (0x75) .maxstack 3 IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldfld ""System.Collections.Generic.List<int> Test.x"" IL_000b: ldc.i4.1 IL_000c: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0011: dup IL_0012: callvirt ""System.Collections.Generic.List<int> Test.y.get"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_001d: dup IL_001e: ldfld ""MemberInitializerTest Test.z"" IL_0023: ldfld ""System.Collections.Generic.List<int> MemberInitializerTest.x"" IL_0028: ldc.i4.3 IL_0029: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_002e: dup IL_002f: ldfld ""MemberInitializerTest Test.z"" IL_0034: callvirt ""System.Collections.Generic.List<int> MemberInitializerTest.y.get"" IL_0039: ldc.i4.4 IL_003a: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_003f: dup IL_0040: ldfld ""System.Collections.Generic.List<int> Test.x"" IL_0045: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_004a: dup IL_004b: callvirt ""System.Collections.Generic.List<int> Test.y.get"" IL_0050: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0055: dup IL_0056: ldfld ""MemberInitializerTest Test.z"" IL_005b: ldfld ""System.Collections.Generic.List<int> MemberInitializerTest.x"" IL_0060: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0065: ldfld ""MemberInitializerTest Test.z"" IL_006a: callvirt ""System.Collections.Generic.List<int> MemberInitializerTest.y.get"" IL_006f: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_0074: ret }"); } [WorkItem(2021, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/2021")] [Fact()] public void ObjectInitializerFieldlikeEvent() { var source = @" public delegate void D(); public struct MemberInitializerTest { public event D z; public static void Main() { var i = new MemberInitializerTest() { z = null }; } }"; var compVerifier = CompileAndVerify(source, expectedOutput: ""); compVerifier.VerifyIL("MemberInitializerTest.Main", @" { // Code size 17 (0x11) .maxstack 2 .locals init (MemberInitializerTest V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""MemberInitializerTest"" IL_0008: ldloca.s V_0 IL_000a: ldnull IL_000b: stfld ""D MemberInitializerTest.z"" IL_0010: ret }"); } [Fact] public void ObjectInitializerTest_UseVariableBeingAssignedInObjectInitializer() { var source = @" public class Test { public int x, y; public static void Main() { Test m = new Test() { x = Goo(out m), y = m.x }; System.Console.WriteLine(m.x); // Print 1 System.Console.WriteLine(m.y); // Print 0 } public static int Goo(out Test m) { m = new Test() { x = 0 }; return 1; } } "; string expectedOutput = @"1 0"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (Test V_0) //m IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: ldloca.s V_0 IL_0008: call ""int Test.Goo(out Test)"" IL_000d: stfld ""int Test.x"" IL_0012: dup IL_0013: ldloc.0 IL_0014: ldfld ""int Test.x"" IL_0019: stfld ""int Test.y"" IL_001e: stloc.0 IL_001f: ldloc.0 IL_0020: ldfld ""int Test.x"" IL_0025: call ""void System.Console.WriteLine(int)"" IL_002a: ldloc.0 IL_002b: ldfld ""int Test.y"" IL_0030: call ""void System.Console.WriteLine(int)"" IL_0035: ret }"); } [Fact] public void DictionaryInitializerTest001() { var source = @" using System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Dictionary<string, int>() {[""aaa""] = 3}; System.Console.WriteLine(x[""aaa""]); } } "; string expectedOutput = @"3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Program.Main", @" { // Code size 33 (0x21) .maxstack 4 IL_0000: newobj ""System.Collections.Generic.Dictionary<string, int>..ctor()"" IL_0005: dup IL_0006: ldstr ""aaa"" IL_000b: ldc.i4.3 IL_000c: callvirt ""void System.Collections.Generic.Dictionary<string, int>.this[string].set"" IL_0011: ldstr ""aaa"" IL_0016: callvirt ""int System.Collections.Generic.Dictionary<string, int>.this[string].get"" IL_001b: call ""void System.Console.WriteLine(int)"" IL_0020: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001() { var source = @" using System; class A { A this[int x] { get { Console.WriteLine(x); return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[x: x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 1 1 1 - - 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 86 (0x56) .maxstack 3 .locals init (int V_0, //x A V_1, int V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""A..ctor()"" IL_0007: stloc.1 IL_0008: ldloc.0 IL_0009: dup IL_000a: ldc.i4.1 IL_000b: add IL_000c: stloc.0 IL_000d: stloc.2 IL_000e: ldloc.1 IL_000f: ldloc.2 IL_0010: callvirt ""A A.this[int].get"" IL_0015: ldc.i4.1 IL_0016: stfld ""int A.X"" IL_001b: ldloc.1 IL_001c: ldloc.2 IL_001d: callvirt ""A A.this[int].get"" IL_0022: ldc.i4.1 IL_0023: stfld ""int A.Y"" IL_0028: ldloc.1 IL_0029: ldloc.2 IL_002a: callvirt ""A A.this[int].get"" IL_002f: ldc.i4.1 IL_0030: stfld ""int A.Z"" IL_0035: ldc.i4.s 45 IL_0037: call ""void System.Console.WriteLine(char)"" IL_003c: newobj ""A..ctor()"" IL_0041: pop IL_0042: ldloc.0 IL_0043: dup IL_0044: ldc.i4.1 IL_0045: add IL_0046: stloc.0 IL_0047: pop IL_0048: ldc.i4.s 45 IL_004a: call ""void System.Console.WriteLine(char)"" IL_004f: ldloc.0 IL_0050: call ""void System.Console.WriteLine(int)"" IL_0055: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001param() { var source = @" using System; class A { A this[params int[] x] { get { Console.WriteLine(x[0]); x[0] = 12345; return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 1 1 1 - - 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 113 (0x71) .maxstack 5 .locals init (int V_0, //x A V_1, int V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""A..ctor()"" IL_0007: stloc.1 IL_0008: ldloc.0 IL_0009: dup IL_000a: ldc.i4.1 IL_000b: add IL_000c: stloc.0 IL_000d: stloc.2 IL_000e: ldloc.1 IL_000f: ldc.i4.1 IL_0010: newarr ""int"" IL_0015: dup IL_0016: ldc.i4.0 IL_0017: ldloc.2 IL_0018: stelem.i4 IL_0019: callvirt ""A A.this[params int[]].get"" IL_001e: ldc.i4.1 IL_001f: stfld ""int A.X"" IL_0024: ldloc.1 IL_0025: ldc.i4.1 IL_0026: newarr ""int"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldloc.2 IL_002e: stelem.i4 IL_002f: callvirt ""A A.this[params int[]].get"" IL_0034: ldc.i4.1 IL_0035: stfld ""int A.Y"" IL_003a: ldloc.1 IL_003b: ldc.i4.1 IL_003c: newarr ""int"" IL_0041: dup IL_0042: ldc.i4.0 IL_0043: ldloc.2 IL_0044: stelem.i4 IL_0045: callvirt ""A A.this[params int[]].get"" IL_004a: ldc.i4.1 IL_004b: stfld ""int A.Z"" IL_0050: ldc.i4.s 45 IL_0052: call ""void System.Console.WriteLine(char)"" IL_0057: newobj ""A..ctor()"" IL_005c: pop IL_005d: ldloc.0 IL_005e: dup IL_005f: ldc.i4.1 IL_0060: add IL_0061: stloc.0 IL_0062: pop IL_0063: ldc.i4.s 45 IL_0065: call ""void System.Console.WriteLine(char)"" IL_006a: ldloc.0 IL_006b: call ""void System.Console.WriteLine(int)"" IL_0070: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001named() { var source = @" using System; class A { A this[int x, int y] { get { Console.WriteLine(x); Console.WriteLine(y); return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[y: x++, x: x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[y: x++, x: x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 2 1 2 1 2 1 - - 5"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects001namedAsync() { var source = @" using System; using System.Threading.Tasks; class A { A this[int x, int y] { get { Console.WriteLine(x); Console.WriteLine(y); return new A(); } } int X, Y, Z; static void Main() { Test().Wait(); } private static async Task<int> Test() { int x = 1; new A {[y: await F(x++), x: await F(x++)] = { X = 1, Y = await F(1), Z = 1 } }; Console.WriteLine('-'); new A {[y: x++, x: x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); return 42; } private static async Task<int> F(int x) { await Task.Yield(); return x; } } "; string expectedOutput = @" 2 1 2 1 2 1 - - 5"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects001dyn() { var source = @" using System; class A { dynamic this[int x] { get { Console.WriteLine(x); return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 1 1 1 - - 3"; var compVerifier = CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects001namedDynamic() { var source = @" using System; class A { dynamic this[int x, int y] { get { Console.WriteLine(x); Console.WriteLine(y); return new A(); } } dynamic this[string x, string y] { get { throw null; } } int X, Y, Z; static void Main() { dynamic x = 1; new A {[y: x++, x: x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine('-'); new A {[y: x++, x: x++] = { } }; Console.WriteLine('-'); Console.WriteLine(x); } } "; string expectedOutput = @" 2 1 2 1 2 1 - - 5"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects001a() { var source = @" using System; struct A { public A[] arr; int X, Y, Z; public A(int x) { X = 0; Y = 0; Z = 0; arr = new A[x]; } static void Main() { int x = 1; var v = new A(3) {arr = {[x++] = { X = 1, Y = x, Z = 3 },[x++] = { X = 1, Y = x, Z = 3 }} }; System.Console.WriteLine(v.arr[0].Y); System.Console.WriteLine(v.arr[1].Y); System.Console.WriteLine(v.arr[2].Y); } } "; string expectedOutput = @" 0 2 3"; var compVerifier = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 194 (0xc2) .maxstack 4 .locals init (int V_0, //x int V_1, int V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.3 IL_0003: newobj ""A..ctor(int)"" IL_0008: ldloc.0 IL_0009: dup IL_000a: ldc.i4.1 IL_000b: add IL_000c: stloc.0 IL_000d: stloc.1 IL_000e: dup IL_000f: ldfld ""A[] A.arr"" IL_0014: ldloc.1 IL_0015: ldelema ""A"" IL_001a: ldc.i4.1 IL_001b: stfld ""int A.X"" IL_0020: dup IL_0021: ldfld ""A[] A.arr"" IL_0026: ldloc.1 IL_0027: ldelema ""A"" IL_002c: ldloc.0 IL_002d: stfld ""int A.Y"" IL_0032: dup IL_0033: ldfld ""A[] A.arr"" IL_0038: ldloc.1 IL_0039: ldelema ""A"" IL_003e: ldc.i4.3 IL_003f: stfld ""int A.Z"" IL_0044: ldloc.0 IL_0045: dup IL_0046: ldc.i4.1 IL_0047: add IL_0048: stloc.0 IL_0049: stloc.2 IL_004a: dup IL_004b: ldfld ""A[] A.arr"" IL_0050: ldloc.2 IL_0051: ldelema ""A"" IL_0056: ldc.i4.1 IL_0057: stfld ""int A.X"" IL_005c: dup IL_005d: ldfld ""A[] A.arr"" IL_0062: ldloc.2 IL_0063: ldelema ""A"" IL_0068: ldloc.0 IL_0069: stfld ""int A.Y"" IL_006e: dup IL_006f: ldfld ""A[] A.arr"" IL_0074: ldloc.2 IL_0075: ldelema ""A"" IL_007a: ldc.i4.3 IL_007b: stfld ""int A.Z"" IL_0080: dup IL_0081: ldfld ""A[] A.arr"" IL_0086: ldc.i4.0 IL_0087: ldelema ""A"" IL_008c: ldfld ""int A.Y"" IL_0091: call ""void System.Console.WriteLine(int)"" IL_0096: dup IL_0097: ldfld ""A[] A.arr"" IL_009c: ldc.i4.1 IL_009d: ldelema ""A"" IL_00a2: ldfld ""int A.Y"" IL_00a7: call ""void System.Console.WriteLine(int)"" IL_00ac: ldfld ""A[] A.arr"" IL_00b1: ldc.i4.2 IL_00b2: ldelema ""A"" IL_00b7: ldfld ""int A.Y"" IL_00bc: call ""void System.Console.WriteLine(int)"" IL_00c1: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001a1() { var source = @" using System; struct A { private A[] _arr; public A[] arr { get { System.Console.WriteLine(""get""); return _arr; } } int X, Y, Z; public A(int x) { X = 0; Y = 0; Z = 0; _arr = new A[x]; } static void Main() { int x = 1; var v = new A(3) {arr = {[x++] = { X = 1, Y = x, Z = 3 },[x++] = { X = 1, Y = x, Z = 3 }} }; System.Console.WriteLine(""=======""); System.Console.WriteLine(v.arr[0].Y); System.Console.WriteLine(v.arr[1].Y); System.Console.WriteLine(v.arr[2].Y); } } "; string expectedOutput = @" get get get get get get ======= get 0 get 2 get 3"; var compVerifier = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 222 (0xde) .maxstack 3 .locals init (int V_0, //x A V_1, //v A V_2, int V_3, int V_4) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.3 IL_0005: call ""A..ctor(int)"" IL_000a: ldloc.0 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: add IL_000e: stloc.0 IL_000f: stloc.3 IL_0010: ldloca.s V_2 IL_0012: call ""A[] A.arr.get"" IL_0017: ldloc.3 IL_0018: ldelema ""A"" IL_001d: ldc.i4.1 IL_001e: stfld ""int A.X"" IL_0023: ldloca.s V_2 IL_0025: call ""A[] A.arr.get"" IL_002a: ldloc.3 IL_002b: ldelema ""A"" IL_0030: ldloc.0 IL_0031: stfld ""int A.Y"" IL_0036: ldloca.s V_2 IL_0038: call ""A[] A.arr.get"" IL_003d: ldloc.3 IL_003e: ldelema ""A"" IL_0043: ldc.i4.3 IL_0044: stfld ""int A.Z"" IL_0049: ldloc.0 IL_004a: dup IL_004b: ldc.i4.1 IL_004c: add IL_004d: stloc.0 IL_004e: stloc.s V_4 IL_0050: ldloca.s V_2 IL_0052: call ""A[] A.arr.get"" IL_0057: ldloc.s V_4 IL_0059: ldelema ""A"" IL_005e: ldc.i4.1 IL_005f: stfld ""int A.X"" IL_0064: ldloca.s V_2 IL_0066: call ""A[] A.arr.get"" IL_006b: ldloc.s V_4 IL_006d: ldelema ""A"" IL_0072: ldloc.0 IL_0073: stfld ""int A.Y"" IL_0078: ldloca.s V_2 IL_007a: call ""A[] A.arr.get"" IL_007f: ldloc.s V_4 IL_0081: ldelema ""A"" IL_0086: ldc.i4.3 IL_0087: stfld ""int A.Z"" IL_008c: ldloc.2 IL_008d: stloc.1 IL_008e: ldstr ""======="" IL_0093: call ""void System.Console.WriteLine(string)"" IL_0098: ldloca.s V_1 IL_009a: call ""A[] A.arr.get"" IL_009f: ldc.i4.0 IL_00a0: ldelema ""A"" IL_00a5: ldfld ""int A.Y"" IL_00aa: call ""void System.Console.WriteLine(int)"" IL_00af: ldloca.s V_1 IL_00b1: call ""A[] A.arr.get"" IL_00b6: ldc.i4.1 IL_00b7: ldelema ""A"" IL_00bc: ldfld ""int A.Y"" IL_00c1: call ""void System.Console.WriteLine(int)"" IL_00c6: ldloca.s V_1 IL_00c8: call ""A[] A.arr.get"" IL_00cd: ldc.i4.2 IL_00ce: ldelema ""A"" IL_00d3: ldfld ""int A.Y"" IL_00d8: call ""void System.Console.WriteLine(int)"" IL_00dd: ret } "); } [Fact] public void DictionaryInitializerTestSideeffects001async() { var source = @" using System; using System.Threading.Tasks; struct A { private A[] _arr; public A[] arr { get { System.Console.WriteLine(""get""); return _arr; } } int X, Y, Z; public A(int x) { X = 0; Y = 0; Z = 0; _arr = new A[x]; } static void Main() { Test().Wait(); } private static async Task<int> Test() { int x = 1; var v = new A(3) { arr = {[x++] = { X = 1, Y = await F(x), Z = 3 },[await F(x++)] = { X = 1, Y = x, Z = await F(3) } } }; System.Console.WriteLine(""=======""); System.Console.WriteLine(v.arr[0].Y); System.Console.WriteLine(v.arr[1].Y); System.Console.WriteLine(v.arr[2].Y); return 42; } private static async Task<int> F(int x) { await Task.Yield(); return x; } } "; string expectedOutput = @" get get get get get get ======= get 0 get 2 get 3"; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTestSideeffects002() { var source = @" using System; class A { A this[int x, int y] { get { Console.Write(x); Console.WriteLine(y); return new A(); } } A this[int x, int y, int z] { get { Console.Write(x); Console.Write(y); Console.WriteLine(z); return new A(); } } int X, Y, Z; static void Main() { int x = 1; new A {[x++, 5] = { X = 1, Y = 1, Z = 1 } , [x++, 7, x++] = { X = 1, Y = 1, Z = 1 } }; Console.WriteLine(x); } } "; string expectedOutput = @" 15 15 15 273 273 273 4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("A.Main()", @" { // Code size 118 (0x76) .maxstack 5 .locals init (int V_0, //x int V_1, int V_2, int V_3) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: newobj ""A..ctor()"" IL_0007: ldloc.0 IL_0008: dup IL_0009: ldc.i4.1 IL_000a: add IL_000b: stloc.0 IL_000c: stloc.1 IL_000d: dup IL_000e: ldloc.1 IL_000f: ldc.i4.5 IL_0010: callvirt ""A A.this[int, int].get"" IL_0015: ldc.i4.1 IL_0016: stfld ""int A.X"" IL_001b: dup IL_001c: ldloc.1 IL_001d: ldc.i4.5 IL_001e: callvirt ""A A.this[int, int].get"" IL_0023: ldc.i4.1 IL_0024: stfld ""int A.Y"" IL_0029: dup IL_002a: ldloc.1 IL_002b: ldc.i4.5 IL_002c: callvirt ""A A.this[int, int].get"" IL_0031: ldc.i4.1 IL_0032: stfld ""int A.Z"" IL_0037: ldloc.0 IL_0038: dup IL_0039: ldc.i4.1 IL_003a: add IL_003b: stloc.0 IL_003c: stloc.2 IL_003d: ldloc.0 IL_003e: dup IL_003f: ldc.i4.1 IL_0040: add IL_0041: stloc.0 IL_0042: stloc.3 IL_0043: dup IL_0044: ldloc.2 IL_0045: ldc.i4.7 IL_0046: ldloc.3 IL_0047: callvirt ""A A.this[int, int, int].get"" IL_004c: ldc.i4.1 IL_004d: stfld ""int A.X"" IL_0052: dup IL_0053: ldloc.2 IL_0054: ldc.i4.7 IL_0055: ldloc.3 IL_0056: callvirt ""A A.this[int, int, int].get"" IL_005b: ldc.i4.1 IL_005c: stfld ""int A.Y"" IL_0061: ldloc.2 IL_0062: ldc.i4.7 IL_0063: ldloc.3 IL_0064: callvirt ""A A.this[int, int, int].get"" IL_0069: ldc.i4.1 IL_006a: stfld ""int A.Z"" IL_006f: ldloc.0 IL_0070: call ""void System.Console.WriteLine(int)"" IL_0075: ret } "); } [Fact] public void DictionaryInitializerTest002() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { var l = new cls1() { [""aaa""] = { 1, 2 }, [""bbb""] = { 42 } }; System.Console.Write(l[""bbb""][0]); System.Console.Write(l[""aaa""][1]); } class cls1 { private Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>(); public dynamic this[string value] { get { List<int> member; if (dict.TryGetValue(value, out member)) { return member; } return dict[value] = new List<int>(); } } } } "; string expectedOutput = @"422"; var compVerifier = CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTest003() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { var l = new Cls1() { [""aaa""] = { [""x""] = 1, [""y""] = 2 }, [""bbb""] = { [""z""] = 42 } }; System.Console.Write(l[""bbb""][""z""]); System.Console.Write(l[""aaa""][""y""]); } class Cls1 { private Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>(); public Dictionary<string, int> this[string arg] { get { Dictionary<string, int> member; if (dict.TryGetValue(arg, out member)) { return member; } return dict[arg] = new Dictionary<string, int>(); } } } } "; string expectedOutput = @"422"; var compVerifier = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: expectedOutput); } [Fact] public void DictionaryInitializerTest004() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { var l = new Cls1() { [""aaa""] = { [""x""] = 1, [""y""] = 2 }, [""bbb""] = { [""z""] = 42 } }; System.Console.Write(l[""bbb""][""z""]); System.Console.Write(l[""aaa""][""y""]); } class Cls1 { private Dictionary<string, Dictionary<string, int>> dict = new Dictionary<string, Dictionary<string, int>>(); public dynamic this[string arg] { get { Dictionary<string, int> member; if (dict.TryGetValue(arg, out member)) { return member; } return dict[arg] = new Dictionary<string, int>(); } } } } "; string expectedOutput = @"422"; var compVerifier = CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: expectedOutput); } [Fact, WorkItem(1073330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073330")] public void NestedIndexerInitializerArray() { var source = @" class C { int[] a = new int[2]; static void Main() { var a = new C { a = { [0] = 1, [1] = 2 } }; System.Console.Write(""{0} {1}"", a.a[0], a.a[1]); } } "; CompileAndVerify(source, expectedOutput: "1 2").VerifyIL("C.Main", @" { // Code size 61 (0x3d) .maxstack 4 .locals init (C V_0) //a IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldfld ""int[] C.a"" IL_000b: ldc.i4.0 IL_000c: ldc.i4.1 IL_000d: stelem.i4 IL_000e: dup IL_000f: ldfld ""int[] C.a"" IL_0014: ldc.i4.1 IL_0015: ldc.i4.2 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ldstr ""{0} {1}"" IL_001d: ldloc.0 IL_001e: ldfld ""int[] C.a"" IL_0023: ldc.i4.0 IL_0024: ldelem.i4 IL_0025: box ""int"" IL_002a: ldloc.0 IL_002b: ldfld ""int[] C.a"" IL_0030: ldc.i4.1 IL_0031: ldelem.i4 IL_0032: box ""int"" IL_0037: call ""void System.Console.Write(string, object, object)"" IL_003c: ret }"); } [Fact, WorkItem(1073330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073330")] public void NestedIndexerInitializerMDArray() { var source = @" class C { int[,] a = new int[2,2]; static void Main() { var a = new C { a = { [0, 0] = 1, [0, 1] = 2, [1, 0] = 3, [1, 1] = 4} }; System.Console.Write(""{0} {1} {2} {3}"", a.a[0, 0], a.a[0, 1], a.a[1, 0], a.a[1, 1]); } } "; CompileAndVerify(source, expectedOutput: "1 2 3 4").VerifyIL("C.Main", @" { // Code size 163 (0xa3) .maxstack 7 .locals init (C V_0) //a IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldfld ""int[,] C.a"" IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: ldc.i4.1 IL_000e: call ""int[*,*].Set"" IL_0013: dup IL_0014: ldfld ""int[,] C.a"" IL_0019: ldc.i4.0 IL_001a: ldc.i4.1 IL_001b: ldc.i4.2 IL_001c: call ""int[*,*].Set"" IL_0021: dup IL_0022: ldfld ""int[,] C.a"" IL_0027: ldc.i4.1 IL_0028: ldc.i4.0 IL_0029: ldc.i4.3 IL_002a: call ""int[*,*].Set"" IL_002f: dup IL_0030: ldfld ""int[,] C.a"" IL_0035: ldc.i4.1 IL_0036: ldc.i4.1 IL_0037: ldc.i4.4 IL_0038: call ""int[*,*].Set"" IL_003d: stloc.0 IL_003e: ldstr ""{0} {1} {2} {3}"" IL_0043: ldc.i4.4 IL_0044: newarr ""object"" IL_0049: dup IL_004a: ldc.i4.0 IL_004b: ldloc.0 IL_004c: ldfld ""int[,] C.a"" IL_0051: ldc.i4.0 IL_0052: ldc.i4.0 IL_0053: call ""int[*,*].Get"" IL_0058: box ""int"" IL_005d: stelem.ref IL_005e: dup IL_005f: ldc.i4.1 IL_0060: ldloc.0 IL_0061: ldfld ""int[,] C.a"" IL_0066: ldc.i4.0 IL_0067: ldc.i4.1 IL_0068: call ""int[*,*].Get"" IL_006d: box ""int"" IL_0072: stelem.ref IL_0073: dup IL_0074: ldc.i4.2 IL_0075: ldloc.0 IL_0076: ldfld ""int[,] C.a"" IL_007b: ldc.i4.1 IL_007c: ldc.i4.0 IL_007d: call ""int[*,*].Get"" IL_0082: box ""int"" IL_0087: stelem.ref IL_0088: dup IL_0089: ldc.i4.3 IL_008a: ldloc.0 IL_008b: ldfld ""int[,] C.a"" IL_0090: ldc.i4.1 IL_0091: ldc.i4.1 IL_0092: call ""int[*,*].Get"" IL_0097: box ""int"" IL_009c: stelem.ref IL_009d: call ""void System.Console.Write(string, params object[])"" IL_00a2: ret }"); } [Fact, WorkItem(1073330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073330")] public void NestedIndexerInitializerJaggedArrayNestedInitializer() { var source = @" class C { int[][] a = new int[1][] { new int[2] }; static void Main() { var a = new C { a = { [0] = { [0] = 1, [1] = 2 } } }; System.Console.Write(""{0} {1}"", a.a[0][0], a.a[0][1]); } } "; CompileAndVerify(source, expectedOutput: "1 2").VerifyIL("C.Main", @" { // Code size 69 (0x45) .maxstack 4 .locals init (C V_0) //a IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldfld ""int[][] C.a"" IL_000b: ldc.i4.0 IL_000c: ldelem.ref IL_000d: ldc.i4.0 IL_000e: ldc.i4.1 IL_000f: stelem.i4 IL_0010: dup IL_0011: ldfld ""int[][] C.a"" IL_0016: ldc.i4.0 IL_0017: ldelem.ref IL_0018: ldc.i4.1 IL_0019: ldc.i4.2 IL_001a: stelem.i4 IL_001b: stloc.0 IL_001c: ldstr ""{0} {1}"" IL_0021: ldloc.0 IL_0022: ldfld ""int[][] C.a"" IL_0027: ldc.i4.0 IL_0028: ldelem.ref IL_0029: ldc.i4.0 IL_002a: ldelem.i4 IL_002b: box ""int"" IL_0030: ldloc.0 IL_0031: ldfld ""int[][] C.a"" IL_0036: ldc.i4.0 IL_0037: ldelem.ref IL_0038: ldc.i4.1 IL_0039: ldelem.i4 IL_003a: box ""int"" IL_003f: call ""void System.Console.Write(string, object, object)"" IL_0044: ret }"); } [Fact, WorkItem(1073330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073330")] public void NestedIndexerInitializerArrayNestedObjectInitializer() { var source = @" class C { C[] a; int b; C() { } C(bool unused) { this.a = new C[2] { new C(), new C() }; } static void Main() { var a = new C(true) { a = { [0] = { b = 1 }, [1] = { b = 2 } } }; System.Console.Write(""{0} {1}"", a.a[0].b, a.a[1].b); } } "; CompileAndVerify(source, expectedOutput: "1 2").VerifyIL("C.Main", @" { // Code size 82 (0x52) .maxstack 4 .locals init (C V_0) //a IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(bool)"" IL_0006: dup IL_0007: ldfld ""C[] C.a"" IL_000c: ldc.i4.0 IL_000d: ldelem.ref IL_000e: ldc.i4.1 IL_000f: stfld ""int C.b"" IL_0014: dup IL_0015: ldfld ""C[] C.a"" IL_001a: ldc.i4.1 IL_001b: ldelem.ref IL_001c: ldc.i4.2 IL_001d: stfld ""int C.b"" IL_0022: stloc.0 IL_0023: ldstr ""{0} {1}"" IL_0028: ldloc.0 IL_0029: ldfld ""C[] C.a"" IL_002e: ldc.i4.0 IL_002f: ldelem.ref IL_0030: ldfld ""int C.b"" IL_0035: box ""int"" IL_003a: ldloc.0 IL_003b: ldfld ""C[] C.a"" IL_0040: ldc.i4.1 IL_0041: ldelem.ref IL_0042: ldfld ""int C.b"" IL_0047: box ""int"" IL_004c: call ""void System.Console.Write(string, object, object)"" IL_0051: ret }"); } #endregion #region "Collection Initializer Tests" [Fact] public void CollectionInitializerTest_GenericList() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<int> list = new List<int>() { 1, 2, 3, 4, 5 }; DisplayCollection(list); return 0; } public static void DisplayCollection<T>(IEnumerable<T> collection) { foreach (var i in collection) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 3 4 5"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 47 (0x2f) .maxstack 3 IL_0000: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0013: dup IL_0014: ldc.i4.3 IL_0015: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_001a: dup IL_001b: ldc.i4.4 IL_001c: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0021: dup IL_0022: ldc.i4.5 IL_0023: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0028: call ""void Test.DisplayCollection<int>(System.Collections.Generic.IEnumerable<int>)"" IL_002d: ldc.i4.0 IL_002e: ret }"); } [Fact] public void CollectionInitializerTest_GenericList_WithComplexElementInitializer() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<long> list = new List<long>() { 1, 2, { 4L }, { 9 }, 3L }; DisplayCollection(list); return 0; } public static void DisplayCollection<T>(IEnumerable<T> collection) { foreach (var i in collection) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 4 9 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 53 (0x35) .maxstack 3 IL_0000: newobj ""System.Collections.Generic.List<long>..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: conv.i8 IL_0008: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_000d: dup IL_000e: ldc.i4.2 IL_000f: conv.i8 IL_0010: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_0015: dup IL_0016: ldc.i4.4 IL_0017: conv.i8 IL_0018: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_001d: dup IL_001e: ldc.i4.s 9 IL_0020: conv.i8 IL_0021: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_0026: dup IL_0027: ldc.i4.3 IL_0028: conv.i8 IL_0029: callvirt ""void System.Collections.Generic.List<long>.Add(long)"" IL_002e: call ""void Test.DisplayCollection<long>(System.Collections.Generic.IEnumerable<long>)"" IL_0033: ldc.i4.0 IL_0034: ret }"); } [Fact] public void CollectionInitializerTest_TypeParameter() { var source = @" using System; using System.Collections; using System.Collections.Generic; class A:IEnumerable { public static List<int> list = new List<int>(); public void Add(int i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } class C<T> where T: A, new() { public void M() { T t = new T {1, 2, 3, 4, 5}; foreach (var x in t) { Console.WriteLine(x); } } } class Test { static void Main() { C<A> testC = new C<A>(); testC.M(); } } "; string expectedOutput = @"1 2 3 4 5"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("C<T>.M", @" { // Code size 117 (0x75) .maxstack 3 .locals init (System.Collections.IEnumerator V_0, System.IDisposable V_1) IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: dup IL_0006: box ""T"" IL_000b: ldc.i4.1 IL_000c: callvirt ""void A.Add(int)"" IL_0011: dup IL_0012: box ""T"" IL_0017: ldc.i4.2 IL_0018: callvirt ""void A.Add(int)"" IL_001d: dup IL_001e: box ""T"" IL_0023: ldc.i4.3 IL_0024: callvirt ""void A.Add(int)"" IL_0029: dup IL_002a: box ""T"" IL_002f: ldc.i4.4 IL_0030: callvirt ""void A.Add(int)"" IL_0035: dup IL_0036: box ""T"" IL_003b: ldc.i4.5 IL_003c: callvirt ""void A.Add(int)"" IL_0041: box ""T"" IL_0046: callvirt ""System.Collections.IEnumerator A.GetEnumerator()"" IL_004b: stloc.0 .try { IL_004c: br.s IL_0059 IL_004e: ldloc.0 IL_004f: callvirt ""object System.Collections.IEnumerator.Current.get"" IL_0054: call ""void System.Console.WriteLine(object)"" IL_0059: ldloc.0 IL_005a: callvirt ""bool System.Collections.IEnumerator.MoveNext()"" IL_005f: brtrue.s IL_004e IL_0061: leave.s IL_0074 } finally { IL_0063: ldloc.0 IL_0064: isinst ""System.IDisposable"" IL_0069: stloc.1 IL_006a: ldloc.1 IL_006b: brfalse.s IL_0073 IL_006d: ldloc.1 IL_006e: callvirt ""void System.IDisposable.Dispose()"" IL_0073: endfinally } IL_0074: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_ClassType() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { B coll = new B { 1, 2, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 4 9 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 58 (0x3a) .maxstack 3 IL_0000: newobj ""B..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: conv.i8 IL_0008: callvirt ""void B.Add(long)"" IL_000d: dup IL_000e: ldc.i4.2 IL_000f: conv.i8 IL_0010: callvirt ""void B.Add(long)"" IL_0015: dup IL_0016: ldc.i4.4 IL_0017: conv.i8 IL_0018: callvirt ""void B.Add(long)"" IL_001d: dup IL_001e: ldc.i4.s 9 IL_0020: conv.i8 IL_0021: callvirt ""void B.Add(long)"" IL_0026: dup IL_0027: ldc.i4.3 IL_0028: conv.i8 IL_0029: callvirt ""void B.Add(long)"" IL_002e: callvirt ""System.Collections.IEnumerator B.GetEnumerator()"" IL_0033: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_0038: ldc.i4.0 IL_0039: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_StructType() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { B coll = new B(1) { 2, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public struct B : IEnumerable { List<object> list; public B(long i) { list = new List<object>(); Add(i); } public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 4 9 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 62 (0x3e) .maxstack 2 .locals init (B V_0, //coll B V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.1 IL_0003: conv.i8 IL_0004: call ""B..ctor(long)"" IL_0009: ldloca.s V_1 IL_000b: ldc.i4.2 IL_000c: conv.i8 IL_000d: call ""void B.Add(long)"" IL_0012: ldloca.s V_1 IL_0014: ldc.i4.4 IL_0015: conv.i8 IL_0016: call ""void B.Add(long)"" IL_001b: ldloca.s V_1 IL_001d: ldc.i4.s 9 IL_001f: conv.i8 IL_0020: call ""void B.Add(long)"" IL_0025: ldloca.s V_1 IL_0027: ldc.i4.3 IL_0028: conv.i8 IL_0029: call ""void B.Add(long)"" IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: call ""System.Collections.IEnumerator B.GetEnumerator()"" IL_0037: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_003c: ldc.i4.0 IL_003d: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_MultipleAddOverloads() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { B coll = new B { 1, 2, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public B() { } public B(int i) { } public void Add(int i) { list.Add(i); } public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 4 9 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 55 (0x37) .maxstack 3 IL_0000: newobj ""B..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void B.Add(int)"" IL_000c: dup IL_000d: ldc.i4.2 IL_000e: callvirt ""void B.Add(int)"" IL_0013: dup IL_0014: ldc.i4.4 IL_0015: conv.i8 IL_0016: callvirt ""void B.Add(long)"" IL_001b: dup IL_001c: ldc.i4.s 9 IL_001e: callvirt ""void B.Add(int)"" IL_0023: dup IL_0024: ldc.i4.3 IL_0025: conv.i8 IL_0026: callvirt ""void B.Add(long)"" IL_002b: callvirt ""System.Collections.IEnumerator B.GetEnumerator()"" IL_0030: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_0035: ldc.i4.0 IL_0036: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_AddOverload_OptionalArgument() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { D coll = new D { 1, { 2 }, { 3, (float?)4.4 } }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { if (collection.Current.GetType() == typeof(float)) Console.WriteLine(((float)collection.Current).ToString(System.Globalization.CultureInfo.InvariantCulture)); else Console.WriteLine(collection.Current); } } } public class D : IEnumerable { List<object> list = new List<object>(); public D() { } public void Add(int i, float? j = null) { list.Add(i); if (j.HasValue) { list.Add(j); } } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 3 4.4"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 66 (0x42) .maxstack 4 .locals init (float? V_0) IL_0000: newobj ""D..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: ldloca.s V_0 IL_0009: initobj ""float?"" IL_000f: ldloc.0 IL_0010: callvirt ""void D.Add(int, float?)"" IL_0015: dup IL_0016: ldc.i4.2 IL_0017: ldloca.s V_0 IL_0019: initobj ""float?"" IL_001f: ldloc.0 IL_0020: callvirt ""void D.Add(int, float?)"" IL_0025: dup IL_0026: ldc.i4.3 IL_0027: ldc.r4 4.4 IL_002c: newobj ""float?..ctor(float)"" IL_0031: callvirt ""void D.Add(int, float?)"" IL_0036: callvirt ""System.Collections.IEnumerator D.GetEnumerator()"" IL_003b: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_0040: ldc.i4.0 IL_0041: ret }"); } [Fact] public void CollectionInitializerTest_InitializerTypeImplementsIEnumerable_AddOverload_ParamsArrayArgument() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var implicitTypedArr = new[] { 7.7, 8.8 }; D coll = new D { 1, { 2 }, { 3, 4.4 }, new double[] { 5, 6 }, implicitTypedArr, null }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { if (collection.Current.GetType() == typeof(double)) Console.WriteLine(((double)collection.Current).ToString(System.Globalization.CultureInfo.InvariantCulture)); else Console.WriteLine(collection.Current); } } } public class D : IEnumerable { List<object> list = new List<object>(); public D() { } public void Add(params double[] i) { if (i != null) { foreach (var x in i) { list.Add(x); } } } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2 3 4.4 5 6 7.7 8.8"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 184 (0xb8) .maxstack 5 .locals init (double[] V_0, //implicitTypedArr D V_1) IL_0000: ldc.i4.2 IL_0001: newarr ""double"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.r8 7.7 IL_0011: stelem.r8 IL_0012: dup IL_0013: ldc.i4.1 IL_0014: ldc.r8 8.8 IL_001d: stelem.r8 IL_001e: stloc.0 IL_001f: newobj ""D..ctor()"" IL_0024: stloc.1 IL_0025: ldloc.1 IL_0026: ldc.i4.1 IL_0027: newarr ""double"" IL_002c: dup IL_002d: ldc.i4.0 IL_002e: ldc.r8 1 IL_0037: stelem.r8 IL_0038: callvirt ""void D.Add(params double[])"" IL_003d: ldloc.1 IL_003e: ldc.i4.1 IL_003f: newarr ""double"" IL_0044: dup IL_0045: ldc.i4.0 IL_0046: ldc.r8 2 IL_004f: stelem.r8 IL_0050: callvirt ""void D.Add(params double[])"" IL_0055: ldloc.1 IL_0056: ldc.i4.2 IL_0057: newarr ""double"" IL_005c: dup IL_005d: ldc.i4.0 IL_005e: ldc.r8 3 IL_0067: stelem.r8 IL_0068: dup IL_0069: ldc.i4.1 IL_006a: ldc.r8 4.4 IL_0073: stelem.r8 IL_0074: callvirt ""void D.Add(params double[])"" IL_0079: ldloc.1 IL_007a: ldc.i4.2 IL_007b: newarr ""double"" IL_0080: dup IL_0081: ldc.i4.0 IL_0082: ldc.r8 5 IL_008b: stelem.r8 IL_008c: dup IL_008d: ldc.i4.1 IL_008e: ldc.r8 6 IL_0097: stelem.r8 IL_0098: callvirt ""void D.Add(params double[])"" IL_009d: ldloc.1 IL_009e: ldloc.0 IL_009f: callvirt ""void D.Add(params double[])"" IL_00a4: ldloc.1 IL_00a5: ldnull IL_00a6: callvirt ""void D.Add(params double[])"" IL_00ab: ldloc.1 IL_00ac: callvirt ""System.Collections.IEnumerator D.GetEnumerator()"" IL_00b1: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_00b6: ldc.i4.0 IL_00b7: ret }"); } [Fact] public void CollectionInitializerTest_NestedCollectionInitializerExpression() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var listOfList = new List<List<int>>() { new List<int> { 1, 2, 3, 4, 5 }, new List<int> { 6, 7, 8, 9, 10 } }; DisplayCollectionOfCollection(listOfList); return 0; } public static void DisplayCollectionOfCollection(IEnumerable<List<int>> collectionOfCollection) { foreach (var collection in collectionOfCollection) { foreach (var i in collection) { Console.WriteLine(i); } } } } "; string expectedOutput = @"1 2 3 4 5 6 7 8 9 10"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 106 (0x6a) .maxstack 5 IL_0000: newobj ""System.Collections.Generic.List<System.Collections.Generic.List<int>>..ctor()"" IL_0005: dup IL_0006: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_000b: dup IL_000c: ldc.i4.1 IL_000d: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0012: dup IL_0013: ldc.i4.2 IL_0014: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0019: dup IL_001a: ldc.i4.3 IL_001b: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0020: dup IL_0021: ldc.i4.4 IL_0022: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0027: dup IL_0028: ldc.i4.5 IL_0029: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_002e: callvirt ""void System.Collections.Generic.List<System.Collections.Generic.List<int>>.Add(System.Collections.Generic.List<int>)"" IL_0033: dup IL_0034: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0039: dup IL_003a: ldc.i4.6 IL_003b: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0040: dup IL_0041: ldc.i4.7 IL_0042: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0047: dup IL_0048: ldc.i4.8 IL_0049: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_004e: dup IL_004f: ldc.i4.s 9 IL_0051: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0056: dup IL_0057: ldc.i4.s 10 IL_0059: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_005e: callvirt ""void System.Collections.Generic.List<System.Collections.Generic.List<int>>.Add(System.Collections.Generic.List<int>)"" IL_0063: call ""void Test.DisplayCollectionOfCollection(System.Collections.Generic.IEnumerable<System.Collections.Generic.List<int>>)"" IL_0068: ldc.i4.0 IL_0069: ret }"); } [Fact] public void CollectionInitializerTest_NestedObjectAndCollectionInitializer() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var coll = new List<B> { new B(0) { list = new List<int>() { 1, 2, 3 } }, new B(1) { list = { 2, 3 } } }; DisplayCollection(coll); return 0; } public static void DisplayCollection(IEnumerable<B> collection) { foreach (var i in collection) { i.Display(); } } } public class B { public List<int> list = new List<int>(); public B() { } public B(int i) { list.Add(i); } public void Display() { foreach (var i in list) { Console.WriteLine(i); } } } "; string expectedOutput = @"1 2 3 1 2 3"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 92 (0x5c) .maxstack 7 IL_0000: newobj ""System.Collections.Generic.List<B>..ctor()"" IL_0005: dup IL_0006: ldc.i4.0 IL_0007: newobj ""B..ctor(int)"" IL_000c: dup IL_000d: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0019: dup IL_001a: ldc.i4.2 IL_001b: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0020: dup IL_0021: ldc.i4.3 IL_0022: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0027: stfld ""System.Collections.Generic.List<int> B.list"" IL_002c: callvirt ""void System.Collections.Generic.List<B>.Add(B)"" IL_0031: dup IL_0032: ldc.i4.1 IL_0033: newobj ""B..ctor(int)"" IL_0038: dup IL_0039: ldfld ""System.Collections.Generic.List<int> B.list"" IL_003e: ldc.i4.2 IL_003f: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0044: dup IL_0045: ldfld ""System.Collections.Generic.List<int> B.list"" IL_004a: ldc.i4.3 IL_004b: callvirt ""void System.Collections.Generic.List<int>.Add(int)"" IL_0050: callvirt ""void System.Collections.Generic.List<B>.Add(B)"" IL_0055: call ""void Test.DisplayCollection(System.Collections.Generic.IEnumerable<B>)"" IL_005a: ldc.i4.0 IL_005b: ret }"); } [Fact] public void CollectionInitializerTest_CtorAddsToCollection() { var source = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { B coll = new B(1) { 2 }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public B() { } public B(int i) { list.Add(i); } public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; string expectedOutput = @"1 2"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 3 IL_0000: ldc.i4.1 IL_0001: newobj ""B..ctor(int)"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: conv.i8 IL_0009: callvirt ""void B.Add(long)"" IL_000e: callvirt ""System.Collections.IEnumerator B.GetEnumerator()"" IL_0013: call ""void Test.DisplayCollection(System.Collections.IEnumerator)"" IL_0018: ldc.i4.0 IL_0019: ret }"); } [Fact] public void CollectionInitializerTest_NestedObjectAndCollectionInitializer_02() { // -------------------------------------------------------------------------------------------- // SPEC: 7.6.10.3 Collection initializers // -------------------------------------------------------------------------------------------- // // SPEC: The following class represents a contact with a name and a list of phone numbers: // // SPEC: public class Contact // SPEC: { // SPEC: string name; // SPEC: List<string> phoneNumbers = new List<string>(); // SPEC: public string Name { get { return name; } set { name = value; } } // SPEC: public List<string> PhoneNumbers { get { return phoneNumbers; } } // SPEC: } // // SPEC: A List<Contact> can be created and initialized as follows: // // SPEC: var contacts = new List<Contact> { // SPEC: new Contact { // SPEC: Name = "Chris Smith", // SPEC: PhoneNumbers = { "206-555-0101", "425-882-8080" } // SPEC: }, // SPEC: new Contact { // SPEC: Name = "Bob Harris", // SPEC: PhoneNumbers = { "650-555-0199" } // SPEC: } // SPEC: }; // // SPEC: which has the same effect as // // SPEC: var __clist = new List<Contact>(); // SPEC: Contact __c1 = new Contact(); // SPEC: __c1.Name = "Chris Smith"; // SPEC: __c1.PhoneNumbers.Add("206-555-0101"); // SPEC: __c1.PhoneNumbers.Add("425-882-8080"); // SPEC: __clist.Add(__c1); // SPEC: Contact __c2 = new Contact(); // SPEC: __c2.Name = "Bob Harris"; // SPEC: __c2.PhoneNumbers.Add("650-555-0199"); // SPEC: __clist.Add(__c2); // SPEC: var contacts = __clist; // // SPEC: where __clist, __c1 and __c2 are temporary variables that are otherwise invisible and inaccessible. var source = @" using System; using System.Collections.Generic; using System.Collections; public class Contact { string name; List<string> phoneNumbers = new List<string>(); public string Name { get { return name; } set { name = value; } } public List<string> PhoneNumbers { get { return phoneNumbers; } } public void DisplayContact() { Console.WriteLine(""Name:"" + name); Console.WriteLine(""PH:""); foreach (var ph in phoneNumbers) { Console.WriteLine(ph); } } } class Test { public static void Main() { var contacts = new List<Contact> { new Contact { Name = ""Chris Smith"", PhoneNumbers = { ""206-555-0101"", ""425-882-8080"" } }, new Contact { Name = ""Bob Harris"", PhoneNumbers = { ""650-555-0199"" } } }; DisplayContacts(contacts); } public static void DisplayContacts(IEnumerable<Contact> contacts) { foreach (var contact in contacts) { contact.DisplayContact(); } } } "; string expectedOutput = @"Name:Chris Smith PH: 206-555-0101 425-882-8080 Name:Bob Harris PH: 650-555-0199"; var compVerifier = CompileAndVerify(source, expectedOutput: expectedOutput); compVerifier.VerifyIL("Test.Main", @" { // Code size 103 (0x67) .maxstack 5 IL_0000: newobj ""System.Collections.Generic.List<Contact>..ctor()"" IL_0005: dup IL_0006: newobj ""Contact..ctor()"" IL_000b: dup IL_000c: ldstr ""Chris Smith"" IL_0011: callvirt ""void Contact.Name.set"" IL_0016: dup IL_0017: callvirt ""System.Collections.Generic.List<string> Contact.PhoneNumbers.get"" IL_001c: ldstr ""206-555-0101"" IL_0021: callvirt ""void System.Collections.Generic.List<string>.Add(string)"" IL_0026: dup IL_0027: callvirt ""System.Collections.Generic.List<string> Contact.PhoneNumbers.get"" IL_002c: ldstr ""425-882-8080"" IL_0031: callvirt ""void System.Collections.Generic.List<string>.Add(string)"" IL_0036: callvirt ""void System.Collections.Generic.List<Contact>.Add(Contact)"" IL_003b: dup IL_003c: newobj ""Contact..ctor()"" IL_0041: dup IL_0042: ldstr ""Bob Harris"" IL_0047: callvirt ""void Contact.Name.set"" IL_004c: dup IL_004d: callvirt ""System.Collections.Generic.List<string> Contact.PhoneNumbers.get"" IL_0052: ldstr ""650-555-0199"" IL_0057: callvirt ""void System.Collections.Generic.List<string>.Add(string)"" IL_005c: callvirt ""void System.Collections.Generic.List<Contact>.Add(Contact)"" IL_0061: call ""void Test.DisplayContacts(System.Collections.Generic.IEnumerable<Contact>)"" IL_0066: ret }"); } [Fact] public void PartialAddMethods() { var source = @" using System; using System.Collections; partial class C : IEnumerable { public IEnumerator GetEnumerator() { return null; } partial void Add(int i); partial void Add(char c); partial void Add(char c) { } static void Main() { Console.WriteLine(new C { 1, 2, 3 }); // all removed Console.WriteLine(new C { 1, 'b', 3 }); // some removed Console.WriteLine(new C { 'a', 'b', 'c' }); // none removed } }"; CompileAndVerify(source).VerifyIL("C.Main", @" { // Code size 63 (0x3f) .maxstack 3 IL_0000: newobj ""C..ctor()"" IL_0005: call ""void System.Console.WriteLine(object)"" IL_000a: newobj ""C..ctor()"" IL_000f: dup IL_0010: ldc.i4.s 98 IL_0012: callvirt ""void C.Add(char)"" IL_0017: call ""void System.Console.WriteLine(object)"" IL_001c: newobj ""C..ctor()"" IL_0021: dup IL_0022: ldc.i4.s 97 IL_0024: callvirt ""void C.Add(char)"" IL_0029: dup IL_002a: ldc.i4.s 98 IL_002c: callvirt ""void C.Add(char)"" IL_0031: dup IL_0032: ldc.i4.s 99 IL_0034: callvirt ""void C.Add(char)"" IL_0039: call ""void System.Console.WriteLine(object)"" IL_003e: ret } "); } [Fact, WorkItem(1089276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089276")] public void PointerIndexing_01() { var source = @" unsafe class C { int* X; static void Main() { var array = new[] { 0 }; fixed (int* p = array) { new C(p) { X = {[0] = 1 } }; } System.Console.WriteLine(array[0]); } C(int* x) { X = x; } }"; CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), expectedOutput: "1", verify: Verification.Fails); } [Fact, WorkItem(1089276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089276")] public void PointerIndexing_02() { var source = @" unsafe class C { int** X; static void Main() { var array = new[] { 0, 0 }; fixed (int* p = array) { var array2 = new[] { p }; fixed (int** pp = array2 ) { new C(pp) { X = {[Index] = {[0] = 2, [1] = 3} } }; } } System.Console.WriteLine(array[0]); System.Console.WriteLine(array[1]); } static int Index { get { System.Console.WriteLine(""get_Index""); return 0; } } C(int** x) { X = x; } }"; CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"get_Index 2 3"); } [Fact] [WorkItem(38726, "https://github.com/dotnet/roslyn/issues/38726")] public void CollectionInitializerBoxingConversion_01() { var source = @"using System; using System.Collections; interface IAppend { void Append(object o); } struct S1 { internal S2 S2; } struct S2 : IEnumerable, IAppend { IEnumerator IEnumerable.GetEnumerator() => null; void IAppend.Append(object o) { } } static class Program { static void Add(this IAppend x, object y) { x.Append(y); Console.Write(y); } static void Main() { _ = new S2() { 1, 2 }; _ = new S1() { S2 = { 3, 4 } }; } }"; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "1234"); } [Fact] [WorkItem(38726, "https://github.com/dotnet/roslyn/issues/38726")] public void CollectionInitializerBoxingConversion_02() { var source = @"using System; using System.Collections; interface IAppend { void Append(object o); } struct S : IEnumerable, IAppend { IEnumerator IEnumerable.GetEnumerator() => null; void IAppend.Append(object o) { } } static class Program { static void Add(this IAppend x, object y) { x.Append(y); Console.Write(y); } static T F<T>() where T : IEnumerable, IAppend, new() { return new T() { 1, 2 }; } static void Main() { _ = F<S>(); } }"; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "12"); } #endregion } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/CSharp/Portable/BoundTree/Constructors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundFieldAccess { public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, LookupResultKind.Viable, fieldSymbol.Type, hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: false, type: type, hasErrors: hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, bool isDeclaration, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: isDeclaration, type: type, hasErrors: hasErrors) { } public BoundFieldAccess Update( BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol typeSymbol) { return this.Update(receiver, fieldSymbol, constantValueOpt, resultKind, this.IsByValue, this.IsDeclaration, typeSymbol); } private static bool NeedsByValueFieldAccess(BoundExpression? receiver, FieldSymbol fieldSymbol) { if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsValueType || receiver == null) // receiver may be null in error cases { return false; } switch (receiver.Kind) { case BoundKind.FieldAccess: return ((BoundFieldAccess)receiver).IsByValue; case BoundKind.Local: var localSymbol = ((BoundLocal)receiver).LocalSymbol; return !(localSymbol.IsWritableVariable || localSymbol.IsRef); default: return false; } } } internal partial class BoundCall { public BoundCall( SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, originalMethodsOpt: default, type, hasErrors) { } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type) => Update(receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, this.OriginalMethodsOpt, type); public static BoundCall ErrorCall( SyntaxNode node, BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, bool isDelegateCall, bool invokedAsExtensionMethod, ImmutableArray<MethodSymbol> originalMethods, LookupResultKind resultKind, Binder binder) { if (!originalMethods.IsEmpty) resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); Debug.Assert(arguments.IsDefaultOrEmpty || (object)receiverOpt != (object)arguments[0]); return new BoundCall( syntax: node, receiverOpt: binder.BindToTypeForErrorRecovery(receiverOpt), method: method, arguments: arguments.SelectAsArray((e, binder) => binder.BindToTypeForErrorRecovery(e), binder), argumentNamesOpt: namedArguments, argumentRefKindsOpt: refKinds, isDelegateCall: isDelegateCall, expanded: false, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: resultKind, originalMethodsOpt: originalMethods, type: method.ReturnType, hasErrors: true); } public BoundCall Update(ImmutableArray<BoundExpression> arguments) { return this.Update(ReceiverOpt, Method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return this.Update(receiverOpt, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method) { return Synthesized(syntax, receiverOpt, method, ImmutableArray<BoundExpression>.Empty); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, BoundExpression arg0) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, BoundExpression arg0, BoundExpression arg1) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0, arg1)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return new BoundCall(syntax, receiverOpt, method, arguments, argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: method.ParameterRefKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, originalMethodsOpt: default, type: method.ReturnType, hasErrors: method.OriginalDefinition is ErrorMethodSymbol ) { WasCompilerGenerated = true }; } } internal sealed partial class BoundObjectCreationExpression { public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, params BoundExpression[] arguments) : this(syntax, constructor, ImmutableArray.Create<BoundExpression>(arguments), default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), default(BitVector), null, null, constructor.ContainingType) { } public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray<BoundExpression> arguments) : this(syntax, constructor, arguments, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), default(BitVector), null, null, constructor.ContainingType) { } } internal partial class BoundIndexerAccess { public static BoundIndexerAccess ErrorAccess( SyntaxNode node, BoundExpression receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, ImmutableArray<PropertySymbol> originalIndexers) { return new BoundIndexerAccess( node, receiverOpt, indexer, arguments, namedArguments, refKinds, expanded: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), originalIndexers, type: indexer.Type, hasErrors: true); } public BoundIndexerAccess( SyntaxNode syntax, BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, originalIndexersOpt: default, type, hasErrors) { } public BoundIndexerAccess Update(BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type) => Update(receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, this.OriginalIndexersOpt, type); } internal sealed partial class BoundConversion { /// <remarks> /// This method is intended for passes other than the LocalRewriter. /// Use MakeConversion helper method in the LocalRewriter instead, /// it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion SynthesizedNonUserDefined(SyntaxNode syntax, BoundExpression operand, Conversion conversion, TypeSymbol type, ConstantValue? constantValueOpt = null) { return new BoundConversion( syntax, operand, conversion, isBaseConversion: false, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: constantValueOpt, originalUserDefinedConversionsOpt: default, type: type) { WasCompilerGenerated = true }; } /// <remarks> /// NOTE: This method is intended for passes other than the LocalRewriter. /// NOTE: Use MakeConversion helper method in the LocalRewriter instead, /// NOTE: it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion Synthesized( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) { return new BoundConversion( syntax, operand, conversion, @checked, explicitCastInCode: explicitCastInCode, conversionGroupOpt, constantValueOpt, type, hasErrors || !conversion.IsValid) { WasCompilerGenerated = true }; } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operand, conversion, isBaseConversion: false, @checked: @checked, explicitCastInCode: explicitCastInCode, constantValueOpt: constantValueOpt, conversionGroupOpt, conversion.OriginalUserDefinedConversions, type: type, hasErrors: hasErrors || !conversion.IsValid) { } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, originalUserDefinedConversionsOpt: default, type, hasErrors) { } public BoundConversion Update(BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type) => Update(operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, this.OriginalUserDefinedConversionsOpt, type); } internal sealed partial class BoundBinaryOperator { public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt), resultKind, left, right, type, hasErrors) { } public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt: default), resultKind, left, right, type, hasErrors) { } public BoundBinaryOperator Update(BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) { var uncommonData = UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, OriginalUserDefinedOperatorsOpt); return Update(operatorKind, uncommonData, resultKind, left, right, type); } public BoundBinaryOperator Update(UncommonData uncommonData) { return Update(OperatorKind, uncommonData, ResultKind, Left, Right, Type); } } internal sealed partial class BoundUserDefinedConditionalLogicalOperator { public BoundUserDefinedConditionalLogicalOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt, left, right, type, hasErrors) { Debug.Assert(operatorKind.IsUserDefined() && operatorKind.IsLogical()); } public BoundUserDefinedConditionalLogicalOperator Update(BinaryOperatorKind operatorKind, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) => Update(operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, left, right, type); } internal sealed partial class BoundParameter { public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, bool hasErrors = false) : this(syntax, parameterSymbol, parameterSymbol.Type, hasErrors) { } public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol) : this(syntax, parameterSymbol, parameterSymbol.Type) { } } internal sealed partial class BoundTypeExpression { public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, ImmutableArray<BoundExpression> boundDimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, boundDimensionsOpt, typeWithAnnotations, typeWithAnnotations.Type, hasErrors) { Debug.Assert((object)typeWithAnnotations.Type != null, "Field 'type' cannot be null"); } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, ImmutableArray<BoundExpression>.Empty, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, aliasOpt, null, TypeWithAnnotations.Create(type), hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, ImmutableArray<BoundExpression> dimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, dimensionsOpt, typeWithAnnotations, hasErrors) { } } internal sealed partial class BoundNamespaceExpression { public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, bool hasErrors = false) : this(syntax, namespaceSymbol, null, hasErrors) { } public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol) : this(syntax, namespaceSymbol, null) { } public BoundNamespaceExpression Update(NamespaceSymbol namespaceSymbol) { return Update(namespaceSymbol, this.AliasOpt); } } internal sealed partial class BoundAssignmentOperator { public BoundAssignmentOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type, bool isRef = false, bool hasErrors = false) : this(syntax, left, right, isRef, type, hasErrors) { } } internal sealed partial class BoundBadExpression { public BoundBadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol?> symbols, ImmutableArray<BoundExpression> childBoundNodes, TypeSymbol type) : this(syntax, resultKind, symbols, childBoundNodes, type, true) { Debug.Assert((object)type != null); } } internal partial class BoundStatementList { public static BoundStatementList Synthesized(SyntaxNode syntax, params BoundStatement[] statements) { return Synthesized(syntax, false, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, params BoundStatement[] statements) { return Synthesized(syntax, hasErrors, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return Synthesized(syntax, false, statements); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, ImmutableArray<BoundStatement> statements) { return new BoundStatementList(syntax, statements, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundReturnStatement { public static BoundReturnStatement Synthesized(SyntaxNode syntax, RefKind refKind, BoundExpression expression, bool hasErrors = false) { return new BoundReturnStatement(syntax, refKind, expression, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundYieldBreakStatement { public static BoundYieldBreakStatement Synthesized(SyntaxNode syntax, bool hasErrors = false) { return new BoundYieldBreakStatement(syntax, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundGotoStatement { public BoundGotoStatement(SyntaxNode syntax, LabelSymbol label, bool hasErrors = false) : this(syntax, label, caseExpressionOpt: null, labelExpressionOpt: null, hasErrors: hasErrors) { } } internal partial class BoundBlock { public BoundBlock(SyntaxNode syntax, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> statements, bool hasErrors = false) : this(syntax, locals, ImmutableArray<LocalFunctionSymbol>.Empty, statements, hasErrors) { } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, BoundStatement statement) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, params BoundStatement[] statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements.AsImmutableOrNull()) { WasCompilerGenerated = true }; } } internal sealed partial class BoundDefaultExpression { public BoundDefaultExpression(SyntaxNode syntax, TypeSymbol type, bool hasErrors = false) : this(syntax, targetType: null, type.GetDefaultValue(), type, hasErrors) { } public override ConstantValue? ConstantValue => ConstantValueOpt; } internal partial class BoundTryStatement { public BoundTryStatement(SyntaxNode syntax, BoundBlock tryBlock, ImmutableArray<BoundCatchBlock> catchBlocks, BoundBlock? finallyBlockOpt, LabelSymbol? finallyLabelOpt = null) : this(syntax, tryBlock, catchBlocks, finallyBlockOpt, finallyLabelOpt, preferFaultHandler: false, hasErrors: false) { } } internal partial class BoundAddressOfOperator { public BoundAddressOfOperator(SyntaxNode syntax, BoundExpression operand, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, isManaged: false, type, hasErrors) { } } internal partial class BoundDagTemp { public BoundDagTemp(SyntaxNode syntax, TypeSymbol type, BoundDagEvaluation? source) : this(syntax, type, source, index: 0, hasErrors: false) { } public static BoundDagTemp ForOriginalInput(BoundExpression expr) => new BoundDagTemp(expr.Syntax, expr.Type!, source: null); } internal partial class BoundCompoundAssignmentOperator { public BoundCompoundAssignmentOperator(SyntaxNode syntax, BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, @operator, left, right, leftConversion, finalConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundCompoundAssignmentOperator Update(BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type) => Update(@operator, left, right, leftConversion, finalConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundUnaryOperator { public BoundUnaryOperator( SyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundUnaryOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type) => Update(operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundIncrementOperator { public BoundIncrementOperator( CSharpSyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, methodOpt, constrainedToTypeOpt, operandConversion, resultConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundIncrementOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type) { return Update(operatorKind, operand, methodOpt, constrainedToTypeOpt, operandConversion, resultConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class BoundFieldAccess { public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, LookupResultKind.Viable, fieldSymbol.Type, hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: false, type: type, hasErrors: hasErrors) { } public BoundFieldAccess( SyntaxNode syntax, BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, bool isDeclaration, TypeSymbol type, bool hasErrors = false) : this(syntax, receiver, fieldSymbol, constantValueOpt, resultKind, NeedsByValueFieldAccess(receiver, fieldSymbol), isDeclaration: isDeclaration, type: type, hasErrors: hasErrors) { } public BoundFieldAccess Update( BoundExpression? receiver, FieldSymbol fieldSymbol, ConstantValue? constantValueOpt, LookupResultKind resultKind, TypeSymbol typeSymbol) { return this.Update(receiver, fieldSymbol, constantValueOpt, resultKind, this.IsByValue, this.IsDeclaration, typeSymbol); } private static bool NeedsByValueFieldAccess(BoundExpression? receiver, FieldSymbol fieldSymbol) { if (fieldSymbol.IsStatic || !fieldSymbol.ContainingType.IsValueType || receiver == null) // receiver may be null in error cases { return false; } switch (receiver.Kind) { case BoundKind.FieldAccess: return ((BoundFieldAccess)receiver).IsByValue; case BoundKind.Local: var localSymbol = ((BoundLocal)receiver).LocalSymbol; return !(localSymbol.IsWritableVariable || localSymbol.IsRef); default: return false; } } } internal partial class BoundCall { public BoundCall( SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, originalMethodsOpt: default, type, hasErrors) { } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool isDelegateCall, bool expanded, bool invokedAsExtensionMethod, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, LookupResultKind resultKind, TypeSymbol type) => Update(receiverOpt, method, arguments, argumentNamesOpt, argumentRefKindsOpt, isDelegateCall, expanded, invokedAsExtensionMethod, argsToParamsOpt, defaultArguments, resultKind, this.OriginalMethodsOpt, type); public static BoundCall ErrorCall( SyntaxNode node, BoundExpression receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, bool isDelegateCall, bool invokedAsExtensionMethod, ImmutableArray<MethodSymbol> originalMethods, LookupResultKind resultKind, Binder binder) { if (!originalMethods.IsEmpty) resultKind = resultKind.WorseResultKind(LookupResultKind.OverloadResolutionFailure); Debug.Assert(arguments.IsDefaultOrEmpty || (object)receiverOpt != (object)arguments[0]); return new BoundCall( syntax: node, receiverOpt: binder.BindToTypeForErrorRecovery(receiverOpt), method: method, arguments: arguments.SelectAsArray((e, binder) => binder.BindToTypeForErrorRecovery(e), binder), argumentNamesOpt: namedArguments, argumentRefKindsOpt: refKinds, isDelegateCall: isDelegateCall, expanded: false, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: resultKind, originalMethodsOpt: originalMethods, type: method.ReturnType, hasErrors: true); } public BoundCall Update(ImmutableArray<BoundExpression> arguments) { return this.Update(ReceiverOpt, Method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); } public BoundCall Update(BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return this.Update(receiverOpt, method, arguments, ArgumentNamesOpt, ArgumentRefKindsOpt, IsDelegateCall, Expanded, InvokedAsExtensionMethod, ArgsToParamsOpt, DefaultArguments, ResultKind, OriginalMethodsOpt, Type); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method) { return Synthesized(syntax, receiverOpt, method, ImmutableArray<BoundExpression>.Empty); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, BoundExpression arg0) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, BoundExpression arg0, BoundExpression arg1) { return Synthesized(syntax, receiverOpt, method, ImmutableArray.Create(arg0, arg1)); } public static BoundCall Synthesized(SyntaxNode syntax, BoundExpression? receiverOpt, MethodSymbol method, ImmutableArray<BoundExpression> arguments) { return new BoundCall(syntax, receiverOpt, method, arguments, argumentNamesOpt: default(ImmutableArray<string>), argumentRefKindsOpt: method.ParameterRefKinds, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), resultKind: LookupResultKind.Viable, originalMethodsOpt: default, type: method.ReturnType, hasErrors: method.OriginalDefinition is ErrorMethodSymbol ) { WasCompilerGenerated = true }; } } internal sealed partial class BoundObjectCreationExpression { public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, params BoundExpression[] arguments) : this(syntax, constructor, ImmutableArray.Create<BoundExpression>(arguments), default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), default(BitVector), null, null, constructor.ContainingType) { } public BoundObjectCreationExpression(SyntaxNode syntax, MethodSymbol constructor, ImmutableArray<BoundExpression> arguments) : this(syntax, constructor, arguments, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), false, default(ImmutableArray<int>), default(BitVector), null, null, constructor.ContainingType) { } } internal partial class BoundIndexerAccess { public static BoundIndexerAccess ErrorAccess( SyntaxNode node, BoundExpression receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> namedArguments, ImmutableArray<RefKind> refKinds, ImmutableArray<PropertySymbol> originalIndexers) { return new BoundIndexerAccess( node, receiverOpt, indexer, arguments, namedArguments, refKinds, expanded: false, argsToParamsOpt: default(ImmutableArray<int>), defaultArguments: default(BitVector), originalIndexers, type: indexer.Type, hasErrors: true); } public BoundIndexerAccess( SyntaxNode syntax, BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type, bool hasErrors = false) : this(syntax, receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, originalIndexersOpt: default, type, hasErrors) { } public BoundIndexerAccess Update(BoundExpression? receiverOpt, PropertySymbol indexer, ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, ImmutableArray<RefKind> argumentRefKindsOpt, bool expanded, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, TypeSymbol type) => Update(receiverOpt, indexer, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, this.OriginalIndexersOpt, type); } internal sealed partial class BoundConversion { /// <remarks> /// This method is intended for passes other than the LocalRewriter. /// Use MakeConversion helper method in the LocalRewriter instead, /// it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion SynthesizedNonUserDefined(SyntaxNode syntax, BoundExpression operand, Conversion conversion, TypeSymbol type, ConstantValue? constantValueOpt = null) { return new BoundConversion( syntax, operand, conversion, isBaseConversion: false, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: constantValueOpt, originalUserDefinedConversionsOpt: default, type: type) { WasCompilerGenerated = true }; } /// <remarks> /// NOTE: This method is intended for passes other than the LocalRewriter. /// NOTE: Use MakeConversion helper method in the LocalRewriter instead, /// NOTE: it generates a synthesized conversion in its lowered form. /// </remarks> public static BoundConversion Synthesized( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) { return new BoundConversion( syntax, operand, conversion, @checked, explicitCastInCode: explicitCastInCode, conversionGroupOpt, constantValueOpt, type, hasErrors || !conversion.IsValid) { WasCompilerGenerated = true }; } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool @checked, bool explicitCastInCode, ConversionGroup? conversionGroupOpt, ConstantValue? constantValueOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operand, conversion, isBaseConversion: false, @checked: @checked, explicitCastInCode: explicitCastInCode, constantValueOpt: constantValueOpt, conversionGroupOpt, conversion.OriginalUserDefinedConversions, type: type, hasErrors: hasErrors || !conversion.IsValid) { } public BoundConversion( SyntaxNode syntax, BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, originalUserDefinedConversionsOpt: default, type, hasErrors) { } public BoundConversion Update(BoundExpression operand, Conversion conversion, bool isBaseConversion, bool @checked, bool explicitCastInCode, ConstantValue? constantValueOpt, ConversionGroup? conversionGroupOpt, TypeSymbol type) => Update(operand, conversion, isBaseConversion, @checked, explicitCastInCode, constantValueOpt, conversionGroupOpt, this.OriginalUserDefinedConversionsOpt, type); } internal sealed partial class BoundBinaryOperator { public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt), resultKind, left, right, type, hasErrors) { } public BoundBinaryOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, originalUserDefinedOperatorsOpt: default), resultKind, left, right, type, hasErrors) { } public BoundBinaryOperator Update(BinaryOperatorKind operatorKind, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) { var uncommonData = UncommonData.CreateIfNeeded(constantValueOpt, methodOpt, constrainedToTypeOpt, OriginalUserDefinedOperatorsOpt); return Update(operatorKind, uncommonData, resultKind, left, right, type); } public BoundBinaryOperator Update(UncommonData uncommonData) { return Update(OperatorKind, uncommonData, ResultKind, Left, Right, Type); } } internal sealed partial class BoundUserDefinedConditionalLogicalOperator { public BoundUserDefinedConditionalLogicalOperator( SyntaxNode syntax, BinaryOperatorKind operatorKind, BoundExpression left, BoundExpression right, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, ImmutableArray<MethodSymbol> originalUserDefinedOperatorsOpt, TypeSymbol type, bool hasErrors = false) : this( syntax, operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt, left, right, type, hasErrors) { Debug.Assert(operatorKind.IsUserDefined() && operatorKind.IsLogical()); } public BoundUserDefinedConditionalLogicalOperator Update(BinaryOperatorKind operatorKind, MethodSymbol logicalOperator, MethodSymbol trueOperator, MethodSymbol falseOperator, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, BoundExpression left, BoundExpression right, TypeSymbol type) => Update(operatorKind, logicalOperator, trueOperator, falseOperator, constrainedToTypeOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, left, right, type); } internal sealed partial class BoundParameter { public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol, bool hasErrors = false) : this(syntax, parameterSymbol, parameterSymbol.Type, hasErrors) { } public BoundParameter(SyntaxNode syntax, ParameterSymbol parameterSymbol) : this(syntax, parameterSymbol, parameterSymbol.Type) { } } internal sealed partial class BoundTypeExpression { public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, ImmutableArray<BoundExpression> boundDimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, boundDimensionsOpt, typeWithAnnotations, typeWithAnnotations.Type, hasErrors) { Debug.Assert((object)typeWithAnnotations.Type != null, "Field 'type' cannot be null"); } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, BoundTypeExpression? boundContainingTypeOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, boundContainingTypeOpt, ImmutableArray<BoundExpression>.Empty, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, typeWithAnnotations, hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, TypeSymbol type, bool hasErrors = false) : this(syntax, aliasOpt, null, TypeWithAnnotations.Create(type), hasErrors) { } public BoundTypeExpression(SyntaxNode syntax, AliasSymbol? aliasOpt, ImmutableArray<BoundExpression> dimensionsOpt, TypeWithAnnotations typeWithAnnotations, bool hasErrors = false) : this(syntax, aliasOpt, null, dimensionsOpt, typeWithAnnotations, hasErrors) { } } internal sealed partial class BoundNamespaceExpression { public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol, bool hasErrors = false) : this(syntax, namespaceSymbol, null, hasErrors) { } public BoundNamespaceExpression(SyntaxNode syntax, NamespaceSymbol namespaceSymbol) : this(syntax, namespaceSymbol, null) { } public BoundNamespaceExpression Update(NamespaceSymbol namespaceSymbol) { return Update(namespaceSymbol, this.AliasOpt); } } internal sealed partial class BoundAssignmentOperator { public BoundAssignmentOperator(SyntaxNode syntax, BoundExpression left, BoundExpression right, TypeSymbol type, bool isRef = false, bool hasErrors = false) : this(syntax, left, right, isRef, type, hasErrors) { } } internal sealed partial class BoundBadExpression { public BoundBadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol?> symbols, ImmutableArray<BoundExpression> childBoundNodes, TypeSymbol type) : this(syntax, resultKind, symbols, childBoundNodes, type, true) { Debug.Assert((object)type != null); } } internal partial class BoundStatementList { public static BoundStatementList Synthesized(SyntaxNode syntax, params BoundStatement[] statements) { return Synthesized(syntax, false, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, params BoundStatement[] statements) { return Synthesized(syntax, hasErrors, statements.AsImmutableOrNull()); } public static BoundStatementList Synthesized(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return Synthesized(syntax, false, statements); } public static BoundStatementList Synthesized(SyntaxNode syntax, bool hasErrors, ImmutableArray<BoundStatement> statements) { return new BoundStatementList(syntax, statements, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundReturnStatement { public static BoundReturnStatement Synthesized(SyntaxNode syntax, RefKind refKind, BoundExpression expression, bool hasErrors = false) { return new BoundReturnStatement(syntax, refKind, expression, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundYieldBreakStatement { public static BoundYieldBreakStatement Synthesized(SyntaxNode syntax, bool hasErrors = false) { return new BoundYieldBreakStatement(syntax, hasErrors) { WasCompilerGenerated = true }; } } internal sealed partial class BoundGotoStatement { public BoundGotoStatement(SyntaxNode syntax, LabelSymbol label, bool hasErrors = false) : this(syntax, label, caseExpressionOpt: null, labelExpressionOpt: null, hasErrors: hasErrors) { } } internal partial class BoundBlock { public BoundBlock(SyntaxNode syntax, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundStatement> statements, bool hasErrors = false) : this(syntax, locals, ImmutableArray<LocalFunctionSymbol>.Empty, statements, hasErrors) { } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, BoundStatement statement) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, ImmutableArray<BoundStatement> statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements) { WasCompilerGenerated = true }; } public static BoundBlock SynthesizedNoLocals(SyntaxNode syntax, params BoundStatement[] statements) { return new BoundBlock(syntax, ImmutableArray<LocalSymbol>.Empty, statements.AsImmutableOrNull()) { WasCompilerGenerated = true }; } } internal sealed partial class BoundDefaultExpression { public BoundDefaultExpression(SyntaxNode syntax, TypeSymbol type, bool hasErrors = false) : this(syntax, targetType: null, type.GetDefaultValue(), type, hasErrors) { } public override ConstantValue? ConstantValue => ConstantValueOpt; } internal partial class BoundTryStatement { public BoundTryStatement(SyntaxNode syntax, BoundBlock tryBlock, ImmutableArray<BoundCatchBlock> catchBlocks, BoundBlock? finallyBlockOpt, LabelSymbol? finallyLabelOpt = null) : this(syntax, tryBlock, catchBlocks, finallyBlockOpt, finallyLabelOpt, preferFaultHandler: false, hasErrors: false) { } } internal partial class BoundAddressOfOperator { public BoundAddressOfOperator(SyntaxNode syntax, BoundExpression operand, TypeSymbol type, bool hasErrors = false) : this(syntax, operand, isManaged: false, type, hasErrors) { } } internal partial class BoundDagTemp { public BoundDagTemp(SyntaxNode syntax, TypeSymbol type, BoundDagEvaluation? source) : this(syntax, type, source, index: 0, hasErrors: false) { } public static BoundDagTemp ForOriginalInput(BoundExpression expr) => new BoundDagTemp(expr.Syntax, expr.Type!, source: null); } internal partial class BoundCompoundAssignmentOperator { public BoundCompoundAssignmentOperator(SyntaxNode syntax, BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, @operator, left, right, leftConversion, finalConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundCompoundAssignmentOperator Update(BinaryOperatorSignature @operator, BoundExpression left, BoundExpression right, Conversion leftConversion, Conversion finalConversion, LookupResultKind resultKind, TypeSymbol type) => Update(@operator, left, right, leftConversion, finalConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundUnaryOperator { public BoundUnaryOperator( SyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundUnaryOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, ConstantValue? constantValueOpt, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, LookupResultKind resultKind, TypeSymbol type) => Update(operatorKind, operand, constantValueOpt, methodOpt, constrainedToTypeOpt, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } internal partial class BoundIncrementOperator { public BoundIncrementOperator( CSharpSyntaxNode syntax, UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type, bool hasErrors = false) : this(syntax, operatorKind, operand, methodOpt, constrainedToTypeOpt, operandConversion, resultConversion, resultKind, originalUserDefinedOperatorsOpt: default, type, hasErrors) { } public BoundIncrementOperator Update(UnaryOperatorKind operatorKind, BoundExpression operand, MethodSymbol? methodOpt, TypeSymbol? constrainedToTypeOpt, Conversion operandConversion, Conversion resultConversion, LookupResultKind resultKind, TypeSymbol type) { return Update(operatorKind, operand, methodOpt, constrainedToTypeOpt, operandConversion, resultConversion, resultKind, this.OriginalUserDefinedOperatorsOpt, type); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/Compilers/CSharp/Portable/Errors/LazyUseSiteDiagnosticsInfoForNullableType.cs
// Licensed to the .NET Foundation under one or more 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.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyUseSiteDiagnosticsInfoForNullableType : LazyDiagnosticInfo { private readonly LanguageVersion _languageVersion; private readonly TypeWithAnnotations _possiblyNullableTypeSymbol; internal LazyUseSiteDiagnosticsInfoForNullableType(LanguageVersion languageVersion, TypeWithAnnotations possiblyNullableTypeSymbol) { _languageVersion = languageVersion; _possiblyNullableTypeSymbol = possiblyNullableTypeSymbol; } protected override DiagnosticInfo? ResolveInfo() { if (_possiblyNullableTypeSymbol.IsNullableType()) { return _possiblyNullableTypeSymbol.Type.OriginalDefinition.GetUseSiteInfo().DiagnosticInfo; } return Binder.GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(_languageVersion, _possiblyNullableTypeSymbol); } } }
// Licensed to the .NET Foundation under one or more 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.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyUseSiteDiagnosticsInfoForNullableType : LazyDiagnosticInfo { private readonly LanguageVersion _languageVersion; private readonly TypeWithAnnotations _possiblyNullableTypeSymbol; internal LazyUseSiteDiagnosticsInfoForNullableType(LanguageVersion languageVersion, TypeWithAnnotations possiblyNullableTypeSymbol) { _languageVersion = languageVersion; _possiblyNullableTypeSymbol = possiblyNullableTypeSymbol; } protected override DiagnosticInfo? ResolveInfo() { if (_possiblyNullableTypeSymbol.IsNullableType()) { return _possiblyNullableTypeSymbol.Type.OriginalDefinition.GetUseSiteInfo().DiagnosticInfo; } return Binder.GetNullableUnconstrainedTypeParameterDiagnosticIfNecessary(_languageVersion, _possiblyNullableTypeSymbol); } } }
-1
dotnet/roslyn
55,826
Fix generate type with file-scoped namespaces
Fix https://github.com/dotnet/roslyn/issues/54746
CyrusNajmabadi
2021-08-23T20:52:33Z
2021-08-23T23:50:21Z
ab7aae6e44d5bc695aa0372330ee9500f2c5e64d
f670785be5fb3c53dc6f5553c00b4fedece0d8a1
Fix generate type with file-scoped namespaces. Fix https://github.com/dotnet/roslyn/issues/54746
./src/VisualStudio/CSharp/Impl/LanguageService/CSharpEditorFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.FileHeaders; using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.FileHeaders; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { [ExcludeFromCodeCoverage] [Guid(Guids.CSharpEditorFactoryIdString)] internal class CSharpEditorFactory : AbstractEditorFactory { public CSharpEditorFactory(IComponentModel componentModel) : base(componentModel) { } protected override string ContentTypeName => ContentTypeNames.CSharpContentType; protected override string LanguageName => LanguageNames.CSharp; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.FileHeaders; using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.FileHeaders; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { [ExcludeFromCodeCoverage] [Guid(Guids.CSharpEditorFactoryIdString)] internal class CSharpEditorFactory : AbstractEditorFactory { public CSharpEditorFactory(IComponentModel componentModel) : base(componentModel) { } protected override string ContentTypeName => ContentTypeNames.CSharpContentType; protected override string LanguageName => LanguageNames.CSharp; } }
-1