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,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/Core/Host/IStreamingFindReferencesPresenter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; namespace Microsoft.CodeAnalysis.Editor.Host { /// <summary> /// API for hosts to provide if they can present FindUsages results in a streaming manner. /// i.e. if they support showing results as they are found instead of after all of the results /// are found. /// </summary> internal interface IStreamingFindUsagesPresenter { /// <summary> /// Tells the presenter that a search is starting. The returned <see cref="FindUsagesContext"/> /// is used to push information about the search into. i.e. when a reference is found /// <see cref="FindUsagesContext.OnReferenceFoundAsync"/> should be called. When the /// search completes <see cref="FindUsagesContext.OnCompletedAsync"/> should be called. /// etc. etc. /// </summary> /// <param name="title">A title to display to the user in the presentation of the results.</param> /// <param name="supportsReferences">Whether or not showing references is supported. /// If true, then the presenter can group by definition, showing references underneath. /// It can also show messages about no references being found at the end of the search. /// If false, the presenter will not group by definitions, and will show the definition /// items in isolation.</param> /// <returns>A cancellation token that will be triggered if the presenter thinks the search /// should stop. This can normally happen if the presenter view is closed, or recycled to /// start a new search in it. Callers should only use this if they intend to report results /// asynchronously and thus relinquish their own control over cancellation from their own /// surrounding context. If the caller intends to populate the presenter synchronously, /// then this cancellation token can be ignored.</returns> (FindUsagesContext context, CancellationToken cancellationToken) StartSearch(string title, bool supportsReferences); /// <summary> /// Call this method to display the Containing Type, Containing Member, or Kind columns /// </summary> (FindUsagesContext context, CancellationToken cancellationToken) StartSearchWithCustomColumns(string title, bool supportsReferences, bool includeContainingTypeAndMemberColumns, bool includeKindColumn); /// <summary> /// Clears all the items from the presenter. /// </summary> void ClearAll(); } internal static class IStreamingFindUsagesPresenterExtensions { /// <summary> /// If there's only a single item, navigates to it. Otherwise, presents all the /// items to the user. /// </summary> public static async Task<bool> TryNavigateToOrPresentItemsAsync( this IStreamingFindUsagesPresenter presenter, IThreadingContext threadingContext, Workspace workspace, string title, ImmutableArray<DefinitionItem> items, CancellationToken cancellationToken) { // Can only navigate or present items on UI thread. await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Ignore any definitions that we can't navigate to. var definitions = items.WhereAsArray(d => d.CanNavigateTo(workspace, cancellationToken)); // See if there's a third party external item we can navigate to. If so, defer // to that item and finish. var externalItems = definitions.WhereAsArray(d => d.IsExternal); foreach (var item in externalItems) { // If we're directly going to a location we need to activate the preview so // that focus follows to the new cursor position. This behavior is expected // because we are only going to navigate once successfully if (item.TryNavigateTo(workspace, showInPreviewTab: true, activateTab: true, cancellationToken)) { return true; } } var nonExternalItems = definitions.WhereAsArray(d => !d.IsExternal); if (nonExternalItems.Length == 0) { return false; } if (nonExternalItems.Length == 1 && nonExternalItems[0].SourceSpans.Length <= 1) { // There was only one location to navigate to. Just directly go to that location. If we're directly // going to a location we need to activate the preview so that focus follows to the new cursor position. return nonExternalItems[0].TryNavigateTo(workspace, showInPreviewTab: true, activateTab: true, cancellationToken); } if (presenter != null) { // We have multiple definitions, or we have definitions with multiple locations. Present this to the // user so they can decide where they want to go to. // // We ignore the cancellation token returned by StartSearch as we're in a context where // we've computed all the results and we're synchronously populating the UI with it. var (context, _) = presenter.StartSearch(title, supportsReferences: false); try { foreach (var definition in nonExternalItems) await context.OnDefinitionFoundAsync(definition, cancellationToken).ConfigureAwait(false); } finally { await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false); } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; namespace Microsoft.CodeAnalysis.Editor.Host { /// <summary> /// API for hosts to provide if they can present FindUsages results in a streaming manner. /// i.e. if they support showing results as they are found instead of after all of the results /// are found. /// </summary> internal interface IStreamingFindUsagesPresenter { /// <summary> /// Tells the presenter that a search is starting. The returned <see cref="FindUsagesContext"/> /// is used to push information about the search into. i.e. when a reference is found /// <see cref="FindUsagesContext.OnReferenceFoundAsync"/> should be called. When the /// search completes <see cref="FindUsagesContext.OnCompletedAsync"/> should be called. /// etc. etc. /// </summary> /// <param name="title">A title to display to the user in the presentation of the results.</param> /// <param name="supportsReferences">Whether or not showing references is supported. /// If true, then the presenter can group by definition, showing references underneath. /// It can also show messages about no references being found at the end of the search. /// If false, the presenter will not group by definitions, and will show the definition /// items in isolation.</param> /// <returns>A cancellation token that will be triggered if the presenter thinks the search /// should stop. This can normally happen if the presenter view is closed, or recycled to /// start a new search in it. Callers should only use this if they intend to report results /// asynchronously and thus relinquish their own control over cancellation from their own /// surrounding context. If the caller intends to populate the presenter synchronously, /// then this cancellation token can be ignored.</returns> (FindUsagesContext context, CancellationToken cancellationToken) StartSearch(string title, bool supportsReferences); /// <summary> /// Call this method to display the Containing Type, Containing Member, or Kind columns /// </summary> (FindUsagesContext context, CancellationToken cancellationToken) StartSearchWithCustomColumns(string title, bool supportsReferences, bool includeContainingTypeAndMemberColumns, bool includeKindColumn); /// <summary> /// Clears all the items from the presenter. /// </summary> void ClearAll(); } internal static class IStreamingFindUsagesPresenterExtensions { /// <summary> /// If there's only a single item, navigates to it. Otherwise, presents all the /// items to the user. /// </summary> public static async Task<bool> TryNavigateToOrPresentItemsAsync( this IStreamingFindUsagesPresenter presenter, IThreadingContext threadingContext, Workspace workspace, string title, ImmutableArray<DefinitionItem> items, CancellationToken cancellationToken) { if (items.IsDefaultOrEmpty) return false; // Can only navigate or present items on UI thread. await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Ignore any definitions that we can't navigate to. var definitions = items.WhereAsArray(d => d.CanNavigateTo(workspace, cancellationToken)); // See if there's a third party external item we can navigate to. If so, defer // to that item and finish. var externalItems = definitions.WhereAsArray(d => d.IsExternal); foreach (var item in externalItems) { // If we're directly going to a location we need to activate the preview so // that focus follows to the new cursor position. This behavior is expected // because we are only going to navigate once successfully if (item.TryNavigateTo(workspace, showInPreviewTab: true, activateTab: true, cancellationToken)) { return true; } } var nonExternalItems = definitions.WhereAsArray(d => !d.IsExternal); if (nonExternalItems.Length == 0) { return false; } if (nonExternalItems.Length == 1 && nonExternalItems[0].SourceSpans.Length <= 1) { // There was only one location to navigate to. Just directly go to that location. If we're directly // going to a location we need to activate the preview so that focus follows to the new cursor position. return nonExternalItems[0].TryNavigateTo(workspace, showInPreviewTab: true, activateTab: true, cancellationToken); } if (presenter != null) { // We have multiple definitions, or we have definitions with multiple locations. Present this to the // user so they can decide where they want to go to. // // We ignore the cancellation token returned by StartSearch as we're in a context where // we've computed all the results and we're synchronously populating the UI with it. var (context, _) = presenter.StartSearch(title, supportsReferences: false); try { foreach (var definition in nonExternalItems) await context.OnDefinitionFoundAsync(definition, cancellationToken).ConfigureAwait(false); } finally { await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false); } } return true; } } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/Core/InheritanceMargin/InheritanceTargetItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; namespace Microsoft.CodeAnalysis.InheritanceMargin { /// <summary> /// Information used to decided the margin image and responsible for performing navigations /// </summary> internal readonly struct InheritanceTargetItem { /// <summary> /// Indicate the inheritance relationship between the target and member. /// </summary> public readonly InheritanceRelationship RelationToMember; /// <summary> /// DefinitionItem used to display the additional information and performs navigation. /// </summary> public readonly DefinitionItem DefinitionItem; /// <summary> /// The glyph for this target. /// </summary> public readonly Glyph Glyph; /// <summary> /// The display name used in margin. /// </summary> public readonly string DisplayName; public InheritanceTargetItem( InheritanceRelationship relationToMember, DefinitionItem definitionItem, Glyph glyph, string displayName) { RelationToMember = relationToMember; DefinitionItem = definitionItem; Glyph = glyph; DisplayName = displayName; } public static async ValueTask<InheritanceTargetItem> ConvertAsync( Solution solution, SerializableInheritanceTargetItem serializableItem, CancellationToken cancellationToken) { var definitionItem = await serializableItem.DefinitionItem.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false); return new InheritanceTargetItem( serializableItem.RelationToMember, definitionItem, serializableItem.Glyph, serializableItem.DisplayName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindUsages; namespace Microsoft.CodeAnalysis.InheritanceMargin { /// <summary> /// Information used to decided the margin image and responsible for performing navigations /// </summary> internal readonly struct InheritanceTargetItem { /// <summary> /// Indicate the inheritance relationship between the target and member. /// </summary> public readonly InheritanceRelationship RelationToMember; /// <summary> /// DefinitionItem used to display the additional information and performs navigation. /// </summary> public readonly DefinitionItem.DetachedDefinitionItem DefinitionItem; /// <summary> /// The glyph for this target. /// </summary> public readonly Glyph Glyph; /// <summary> /// The display name used in margin. /// </summary> public readonly string DisplayName; public InheritanceTargetItem( InheritanceRelationship relationToMember, DefinitionItem.DetachedDefinitionItem definitionItem, Glyph glyph, string displayName) { RelationToMember = relationToMember; DefinitionItem = definitionItem; Glyph = glyph; DisplayName = displayName; } public static async ValueTask<InheritanceTargetItem> ConvertAsync( Solution solution, SerializableInheritanceTargetItem serializableItem, CancellationToken cancellationToken) { var definitionItem = await serializableItem.DefinitionItem.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false); // detach this item so that it doesn't hold onto a full solution snapshot in other documents that // are not getting updated. return new InheritanceTargetItem( serializableItem.RelationToMember, definitionItem.Detach(), serializableItem.Glyph, serializableItem.DisplayName); } } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/Test/InheritanceMargin/InheritanceMarginTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.InheritanceMargin { [Trait(Traits.Feature, Traits.Features.InheritanceMargin)] [UseExportProvider] public class InheritanceMarginTests { private const string SearchAreaTag = "SeachTag"; #region Helpers private static Task VerifyNoItemForDocumentAsync(string markup, string languageName) => VerifyInSingleDocumentAsync(markup, languageName); private static Task VerifyInSingleDocumentAsync( string markup, string languageName, params TestInheritanceMemberItem[] memberItems) { markup = @$"<![CDATA[ {markup}]]>"; var workspaceFile = $@" <Workspace> <Project Language=""{languageName}"" CommonReferences=""true""> <Document> {markup} </Document> </Project> </Workspace>"; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( workspaceFile, composition: EditorTestCompositions.EditorFeatures); var testHostDocument = testWorkspace.Documents[0]; return VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument, memberItems, cancellationToken); } private static async Task VerifyTestMemberInDocumentAsync( TestWorkspace testWorkspace, TestHostDocument testHostDocument, TestInheritanceMemberItem[] memberItems, CancellationToken cancellationToken) { var document = testWorkspace.CurrentSolution.GetRequiredDocument(testHostDocument.Id); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var searchingSpan = root.Span; // Look for the search span, if not found, then pass the whole document span to the service. if (testHostDocument.AnnotatedSpans.TryGetValue(SearchAreaTag, out var spans) && spans.IsSingle()) { searchingSpan = spans[0]; } var service = document.GetRequiredLanguageService<IInheritanceMarginService>(); var actualItems = await service.GetInheritanceMemberItemsAsync( document, searchingSpan, cancellationToken).ConfigureAwait(false); var sortedActualItems = actualItems.OrderBy(item => item.LineNumber).ToImmutableArray(); var sortedExpectedItems = memberItems.OrderBy(item => item.LineNumber).ToImmutableArray(); Assert.Equal(sortedExpectedItems.Length, sortedActualItems.Length); for (var i = 0; i < sortedActualItems.Length; i++) { VerifyInheritanceMember(testWorkspace, sortedExpectedItems[i], sortedActualItems[i]); } } private static void VerifyInheritanceMember(TestWorkspace testWorkspace, TestInheritanceMemberItem expectedItem, InheritanceMarginItem actualItem) { Assert.Equal(expectedItem.LineNumber, actualItem.LineNumber); Assert.Equal(expectedItem.MemberName, actualItem.DisplayTexts.JoinText()); Assert.Equal(expectedItem.Targets.Length, actualItem.TargetItems.Length); var expectedTargets = expectedItem.Targets .Select(info => TestInheritanceTargetItem.Create(info, testWorkspace)) .OrderBy(target => target.TargetSymbolName) .ToImmutableArray(); var sortedActualTargets = actualItem.TargetItems.OrderBy(target => target.DefinitionItem.DisplayParts.JoinText()) .ToImmutableArray(); for (var i = 0; i < expectedTargets.Length; i++) { VerifyInheritanceTarget(expectedTargets[i], sortedActualTargets[i]); } } private static void VerifyInheritanceTarget(TestInheritanceTargetItem expectedTarget, InheritanceTargetItem actualTarget) { Assert.Equal(expectedTarget.TargetSymbolName, actualTarget.DefinitionItem.DisplayParts.JoinText()); Assert.Equal(expectedTarget.RelationshipToMember, actualTarget.RelationToMember); if (expectedTarget.IsInMetadata) { Assert.True(actualTarget.DefinitionItem.Properties.ContainsKey("MetadataSymbolKey")); Assert.True(actualTarget.DefinitionItem.SourceSpans.IsEmpty); } else { var actualDocumentSpans = actualTarget.DefinitionItem.SourceSpans.OrderBy(documentSpan => documentSpan.SourceSpan.Start).ToImmutableArray(); var expectedDocumentSpans = expectedTarget.DocumentSpans.OrderBy(documentSpan => documentSpan.SourceSpan.Start).ToImmutableArray(); Assert.Equal(expectedDocumentSpans.Length, actualDocumentSpans.Length); for (var i = 0; i < actualDocumentSpans.Length; i++) { Assert.Equal(expectedDocumentSpans[i].SourceSpan, actualDocumentSpans[i].SourceSpan); Assert.Equal(expectedDocumentSpans[i].Document.FilePath, actualDocumentSpans[i].Document.FilePath); } } } /// <summary> /// Project of markup1 is referencing project of markup2 /// </summary> private static async Task VerifyInDifferentProjectsAsync( (string markupInProject1, string languageName) markup1, (string markupInProject2, string languageName) markup2, TestInheritanceMemberItem[] memberItemsInMarkup1, TestInheritanceMemberItem[] memberItemsInMarkup2) { var workspaceFile = $@" <Workspace> <Project Language=""{markup1.languageName}"" AssemblyName=""Assembly1"" CommonReferences=""true""> <ProjectReference>Assembly2</ProjectReference> <Document> <![CDATA[ {markup1.markupInProject1}]]> </Document> </Project> <Project Language=""{markup2.languageName}"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> <![CDATA[ {markup2.markupInProject2}]]> </Document> </Project> </Workspace>"; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( workspaceFile, composition: EditorTestCompositions.EditorFeatures); var testHostDocument1 = testWorkspace.Documents.Single(doc => doc.Project.AssemblyName.Equals("Assembly1")); var testHostDocument2 = testWorkspace.Documents.Single(doc => doc.Project.AssemblyName.Equals("Assembly2")); await VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument1, memberItemsInMarkup1, cancellationToken).ConfigureAwait(false); await VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument2, memberItemsInMarkup2, cancellationToken).ConfigureAwait(false); } private class TestInheritanceMemberItem { public readonly int LineNumber; public readonly string MemberName; public readonly ImmutableArray<TargetInfo> Targets; public TestInheritanceMemberItem( int lineNumber, string memberName, ImmutableArray<TargetInfo> targets) { LineNumber = lineNumber; MemberName = memberName; Targets = targets; } } private class TargetInfo { public readonly string TargetSymbolDisplayName; public readonly string? LocationTag; public readonly InheritanceRelationship Relationship; public readonly bool InMetadata; public TargetInfo( string targetSymbolDisplayName, string locationTag, InheritanceRelationship relationship) { TargetSymbolDisplayName = targetSymbolDisplayName; LocationTag = locationTag; Relationship = relationship; InMetadata = false; } public TargetInfo( string targetSymbolDisplayName, InheritanceRelationship relationship, bool inMetadata) { TargetSymbolDisplayName = targetSymbolDisplayName; Relationship = relationship; InMetadata = inMetadata; LocationTag = null; } } private class TestInheritanceTargetItem { public readonly string TargetSymbolName; public readonly InheritanceRelationship RelationshipToMember; public readonly ImmutableArray<DocumentSpan> DocumentSpans; public readonly bool IsInMetadata; public TestInheritanceTargetItem( string targetSymbolName, InheritanceRelationship relationshipToMember, ImmutableArray<DocumentSpan> documentSpans, bool isInMetadata) { TargetSymbolName = targetSymbolName; RelationshipToMember = relationshipToMember; DocumentSpans = documentSpans; IsInMetadata = isInMetadata; } public static TestInheritanceTargetItem Create( TargetInfo targetInfo, TestWorkspace testWorkspace) { if (targetInfo.InMetadata) { return new TestInheritanceTargetItem( targetInfo.TargetSymbolDisplayName, targetInfo.Relationship, ImmutableArray<DocumentSpan>.Empty, isInMetadata: true); } else { using var _ = ArrayBuilder<DocumentSpan>.GetInstance(out var builder); // If the target is not in metadata, there must be a location tag to give the span! Assert.True(targetInfo.LocationTag != null); foreach (var testHostDocument in testWorkspace.Documents) { if (targetInfo.LocationTag != null) { var annotatedSpans = testHostDocument.AnnotatedSpans; if (annotatedSpans.TryGetValue(targetInfo.LocationTag, out var spans)) { var document = testWorkspace.CurrentSolution.GetRequiredDocument(testHostDocument.Id); builder.AddRange(spans.Select(span => new DocumentSpan(document, span))); } } } return new TestInheritanceTargetItem( targetInfo.TargetSymbolDisplayName, targetInfo.Relationship, builder.ToImmutable(), isInMetadata: false); } } } #endregion #region TestsForCSharp [Fact] public Task TestCSharpClassWithErrorBaseType() { var markup = @" public class Bar : SomethingUnknown { }"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp); } [Fact] public Task TestCSharpReferencingMetadata() { var markup = @" using System.Collections; public class Bar : IEnumerable { public IEnumerator GetEnumerator () { return null }; }"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true))); var itemForGetEnumerator = new TestInheritanceMemberItem( lineNumber: 5, memberName: "IEnumerator Bar.GetEnumerator()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "IEnumerator IEnumerable.GetEnumerator()", relationship: InheritanceRelationship.ImplementedMember, inMetadata: true))); return VerifyInSingleDocumentAsync(markup, LanguageNames.CSharp, itemForBar, itemForGetEnumerator); } [Fact] public Task TestCSharpClassImplementingInterface() { var markup = @" interface {|target1:IBar|} { } public class {|target2:Bar|} : IBar { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Fact] public Task TestCSharpInterfaceImplementingInterface() { var markup = @" interface {|target1:IBar|} { } interface {|target2:IBar2|} : IBar { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar2", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType)) ); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar2", targets: ImmutableArray<TargetInfo>.Empty .Add(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.InheritedInterface)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Fact] public Task TestCSharpClassInheritsClass() { var markup = @" class {|target2:A|} { } class {|target1:B|} : A { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class A", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class B", locationTag: "target1", relationship: InheritanceRelationship.DerivedType)) ); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class B", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class A", locationTag: "target2", relationship: InheritanceRelationship.BaseType)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] public Task TestCSharpTypeWithoutBaseType(string typeName) { var markup = $@" public {typeName} Bar {{ }}"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp); } [Theory] [InlineData("public Bar() { }")] [InlineData("public static void Bar3() { }")] [InlineData("public static void ~Bar() { }")] [InlineData("public static Bar operator +(Bar a, Bar b) => new Bar();")] public Task TestCSharpSpecialMember(string memberDeclaration) { var markup = $@" public abstract class {{|target1:Bar1|}} {{}} public class Bar : Bar1 {{ {{|{SearchAreaTag}:{memberDeclaration}|}} }}"; return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, new TestInheritanceMemberItem( lineNumber: 4, memberName: "class Bar", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType)))); } [Fact] public Task TestCSharpEventDeclaration() { var markup = @" using System; interface {|target2:IBar|} { event EventHandler {|target4:e|}; } public class {|target1:Bar|} : IBar { public event EventHandler {|target3:e|} { add {} remove {} } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 5, memberName: "event EventHandler IBar.e", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 9, memberName: "event EventHandler Bar.e", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestCSharpEventFieldDeclarations() { var markup = @"using System; interface {|target2:IBar|} { event EventHandler {|target5:e1|}, {|target6:e2|}; } public class {|target1:Bar|} : IBar { public event EventHandler {|target3:e1|}, {|target4:e2|}; }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForE1InInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "event EventHandler IBar.e1", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e1", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForE2InInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "event EventHandler IBar.e2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e2", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForE1InClass = new TestInheritanceMemberItem( lineNumber: 8, memberName: "event EventHandler Bar.e1", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e1", locationTag: "target5", relationship: InheritanceRelationship.ImplementedMember))); var itemForE2InClass = new TestInheritanceMemberItem( lineNumber: 8, memberName: "event EventHandler Bar.e2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e2", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForBar, itemForE1InInterface, itemForE2InInterface, itemForE1InClass, itemForE2InClass); } [Fact] public Task TestCSharpInterfaceMembers() { var markup = @"using System; interface {|target1:IBar|} { void {|target4:Foo|}(); int {|target6:Poo|} { get; set; } event EventHandler {|target8:Eoo|}; int {|target9:this|}[int i] { get; set; } } public class {|target2:Bar|} : IBar { public void {|target3:Foo|}() { } public int {|target5:Poo|} { get; set; } public event EventHandler {|target7:Eoo|}; public int {|target10:this|}[int i] { get => 1; set { } } }"; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 13, memberName: "event EventHandler Bar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.Eoo", locationTag: "target8", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForEooInInterface = new TestInheritanceMemberItem( lineNumber: 6, memberName: "event EventHandler IBar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.Eoo", locationTag: "target7", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForPooInInterface = new TestInheritanceMemberItem( lineNumber: 5, memberName: "int IBar.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int Bar.Poo { get; set; }", locationTag: "target5", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "int Bar.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int IBar.Poo { get; set; }", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForFooInInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 11, memberName: "void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType)) ); var itemForBar = new TestInheritanceMemberItem( lineNumber: 9, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface)) ); var itemForIndexerInClass = new TestInheritanceMemberItem( lineNumber: 14, memberName: "int Bar.this[int] { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int IBar.this[int] { get; set; }", locationTag: "target9", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForIndexerInInterface = new TestInheritanceMemberItem( lineNumber: 7, memberName: "int IBar.this[int] { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int Bar.this[int] { get; set; }", locationTag: "target10", relationship: InheritanceRelationship.ImplementingMember)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForEooInClass, itemForEooInInterface, itemForPooInInterface, itemForPooInClass, itemForFooInInterface, itemForFooInClass, itemForIBar, itemForBar, itemForIndexerInInterface, itemForIndexerInClass); } [Theory] [InlineData("abstract")] [InlineData("virtual")] public Task TestCSharpAbstractClassMembers(string modifier) { var markup = $@"using System; public abstract class {{|target2:Bar|}} {{ public {modifier} void {{|target4:Foo|}}(); public {modifier} int {{|target6:Poo|}} {{ get; set; }} public {modifier} event EventHandler {{|target8:Eoo|}}; }} public class {{|target1:Bar2|}} : Bar {{ public override void {{|target3:Foo|}}() {{ }} public override int {{|target5:Poo|}} {{ get; set; }} public override event EventHandler {{|target7:Eoo|}}; }} "; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override event EventHandler Bar2.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} event EventHandler Bar.Eoo", locationTag: "target8", relationship: InheritanceRelationship.OverriddenMember))); var itemForEooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 6, memberName: $"{modifier} event EventHandler Bar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override event EventHandler Bar2.Eoo", locationTag: "target7", relationship: InheritanceRelationship.OverridingMember))); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 11, memberName: "override int Bar2.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} int Bar.Poo {{ get; set; }}", locationTag: "target6", relationship: InheritanceRelationship.OverriddenMember))); var itemForPooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 5, memberName: $"{modifier} int Bar.Poo {{ get; set; }}", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override int Bar2.Poo { get; set; }", locationTag: "target5", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 4, memberName: $"{modifier} void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 10, memberName: "override void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} void Bar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.OverriddenMember))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "class Bar2", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForBar, itemForBar2, itemForFooInAbstractClass, itemForFooInClass, itemForPooInClass, itemForPooInAbstractClass, itemForEooInClass, itemForEooInAbstractClass); } [Theory] [CombinatorialData] public Task TestCSharpOverrideMemberCanFindImplementingInterface(bool testDuplicate) { var markup1 = @"using System; public interface {|target4:IBar|} { void {|target6:Foo|}(); } public class {|target1:Bar1|} : IBar { public virtual void {|target2:Foo|}() { } } public class {|target5:Bar2|} : Bar1 { public override void {|target3:Foo|}() { } }"; var markup2 = @"using System; public interface {|target4:IBar|} { void {|target6:Foo|}(); } public class {|target1:Bar1|} : IBar { public virtual void {|target2:Foo|}() { } } public class {|target5:Bar2|} : Bar1, IBar { public override void {|target3:Foo|}() { } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType), new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target5", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "virtual void Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface), new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target5", relationship: InheritanceRelationship.DerivedType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "virtual void Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 10, memberName: "class Bar2", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType), new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "virtual void Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( testDuplicate ? markup2 : markup1, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForBar1, itemForFooInBar1, itemForBar2, itemForFooInBar2); } [Fact] public Task TestCSharpFindGenericsBaseType() { var markup = @" public interface {|target2:IBar|}<T> { void {|target4:Foo|}(); } public class {|target1:Bar2|} : IBar<int>, IBar<string> { public void {|target3:Foo|}(); }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar<T>.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); // Only have one IBar<T> item var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class Bar2", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar<T>", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); // Only have one IBar<T>.Foo item var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 9, memberName: "void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar<T>.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForBar2, itemForFooInBar2); } [Fact] public Task TestCSharpExplicitInterfaceImplementation() { var markup = @" interface {|target2:IBar|}<T> { void {|target3:Foo|}(T t); } abstract class {|target1:AbsBar|} : IBar<int> { void IBar<int>.{|target4:Foo|}(int t) { throw new System.NotImplementedException(); } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class AbsBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar<T>.Foo(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void AbsBar.IBar<int>.Foo(int)", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForAbsBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class AbsBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar<T>", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInAbsBar = new TestInheritanceMemberItem( lineNumber: 9, memberName: "void AbsBar.IBar<int>.Foo(int)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar<T>.Foo(T)", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember) )); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForAbsBar, itemForFooInAbsBar); } [Fact] public Task TestStaticAbstractMemberInterface() { var markup = @" interface {|target5:I1|}<T> where T : I1<T> { static abstract void {|target4:M1|}(); static abstract int {|target7:P1|} { get; set; } static abstract event EventHandler {|target9:e1|}; static abstract int operator {|target11:+|}(T i1); static abstract implicit operator {|target12:int|}(T i1); } public class {|target1:Class1|} : I1<Class1> { public static void {|target2:M1|}() {} public static int {|target6:P1|} { get => 1; set { } } public static event EventHandler {|target8:e1|}; public static int operator {|target10:+|}(Class1 i) => 1; public static implicit operator {|target13:int|}(Class1 i) => 0; }"; var itemForI1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface I1<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Class1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForM1InI1 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void I1<T>.M1()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static void Class1.M1()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember))); var itemForAbsClass1 = new TestInheritanceMemberItem( lineNumber: 11, memberName: "class Class1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface I1<T>", locationTag: "target5", relationship: InheritanceRelationship.ImplementedInterface))); var itemForM1InClass1 = new TestInheritanceMemberItem( lineNumber: 13, memberName: "static void Class1.M1()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void I1<T>.M1()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); var itemForP1InI1 = new TestInheritanceMemberItem( lineNumber: 5, memberName: "int I1<T>.P1 { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static int Class1.P1 { get; set; }", locationTag: "target6", relationship: InheritanceRelationship.ImplementingMember))); var itemForP1InClass1 = new TestInheritanceMemberItem( lineNumber: 14, memberName: "static int Class1.P1 { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int I1<T>.P1 { get; set; }", locationTag: "target7", relationship: InheritanceRelationship.ImplementedMember))); var itemForE1InI1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "event EventHandler I1<T>.e1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static event EventHandler Class1.e1", locationTag: "target8", relationship: InheritanceRelationship.ImplementingMember))); var itemForE1InClass1 = new TestInheritanceMemberItem( lineNumber: 15, memberName: "static event EventHandler Class1.e1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler I1<T>.e1", locationTag: "target9", relationship: InheritanceRelationship.ImplementedMember))); var itemForPlusOperatorInI1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "int I1<T>.operator +(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static int Class1.operator +(Class1)", locationTag: "target10", relationship: InheritanceRelationship.ImplementingMember))); var itemForPlusOperatorInClass1 = new TestInheritanceMemberItem( lineNumber: 16, memberName: "static int Class1.operator +(Class1)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int I1<T>.operator +(T)", locationTag: "target11", relationship: InheritanceRelationship.ImplementedMember))); var itemForIntOperatorInI1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "I1<T>.implicit operator int(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static Class1.implicit operator int(Class1)", locationTag: "target13", relationship: InheritanceRelationship.ImplementingMember))); var itemForIntOperatorInClass1 = new TestInheritanceMemberItem( lineNumber: 17, memberName: "static Class1.implicit operator int(Class1)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "I1<T>.implicit operator int(T)", locationTag: "target12", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForI1, itemForAbsClass1, itemForM1InI1, itemForM1InClass1, itemForP1InI1, itemForP1InClass1, itemForE1InI1, itemForE1InClass1, itemForPlusOperatorInI1, itemForPlusOperatorInClass1, itemForIntOperatorInI1, itemForIntOperatorInClass1); } #endregion #region TestsForVisualBasic [Fact] public Task TestVisualBasicWithErrorBaseType() { var markup = @" Namespace MyNamespace Public Class Bar Implements SomethingNotExist End Class End Namespace"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic); } [Fact] public Task TestVisualBasicReferencingMetadata() { var markup = @" Namespace MyNamespace Public Class Bar Implements System.Collections.IEnumerable Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true))); var itemForGetEnumerator = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Function Bar.GetEnumerator() As IEnumerator", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function IEnumerable.GetEnumerator() As IEnumerator", relationship: InheritanceRelationship.ImplementedMember, inMetadata: true))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForBar, itemForGetEnumerator); } [Fact] public Task TestVisualBasicClassImplementingInterface() { var markup = @" Interface {|target2:IBar|} End Interface Class {|target1:Bar|} Implements IBar End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar); } [Fact] public Task TestVisualBasicInterfaceImplementingInterface() { var markup = @" Interface {|target2:IBar2|} End Interface Interface {|target1:IBar|} Inherits IBar2 End Interface"; var itemForIBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar2", locationTag: "target2", relationship: InheritanceRelationship.InheritedInterface))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForIBar2, itemForIBar); } [Fact] public Task TestVisualBasicClassInheritsClass() { var markup = @" Class {|target2:Bar2|} End Class Class {|target1:Bar|} Inherits Bar2 End Class"; var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForBar2, itemForBar); } [Theory] [InlineData("Class")] [InlineData("Structure")] [InlineData("Enum")] [InlineData("Interface")] public Task TestVisualBasicTypeWithoutBaseType(string typeName) { var markup = $@" {typeName} Bar End {typeName}"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic); } [Fact] public Task TestVisualBasicMetadataInterface() { var markup = @" Imports System.Collections Class Bar Implements IEnumerable End Class"; return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "Interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true)))); } [Fact] public Task TestVisualBasicEventStatement() { var markup = @" Interface {|target2:IBar|} Event {|target4:e|} As EventHandler End Interface Class {|target1:Bar|} Implements IBar Public Event {|target3:e|} As EventHandler Implements IBar.e End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Event IBar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event Bar.e As EventHandler", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Event Bar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event IBar.e As EventHandler", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestVisualBasicEventBlock() { var markup = @" Interface {|target2:IBar|} Event {|target4:e|} As EventHandler End Interface Class {|target1:Bar|} Implements IBar Public Custom Event {|target3:e|} As EventHandler Implements IBar.e End Event End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Event IBar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event Bar.e As EventHandler", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Event Bar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event IBar.e As EventHandler", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestVisualBasicInterfaceMembers() { var markup = @" Interface {|target2:IBar|} Property {|target4:Poo|} As Integer Function {|target6:Foo|}() As Integer End Interface Class {|target1:Bar|} Implements IBar Public Property {|target3:Poo|} As Integer Implements IBar.Poo Get Return 1 End Get Set(value As Integer) End Set End Property Public Function {|target5:Foo|}() As Integer Implements IBar.Foo Return 1 End Function End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForPooInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Property IBar.Poo As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Property Bar.Poo As Integer", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 9, memberName: "Property Bar.Poo As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Property IBar.Poo As Integer", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); var itemForFooInInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Function IBar.Foo() As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function Bar.Foo() As Integer", locationTag: "target5", relationship: InheritanceRelationship.ImplementingMember))); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 16, memberName: "Function Bar.Foo() As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function IBar.Foo() As Integer", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForPooInInterface, itemForPooInClass, itemForFooInInterface, itemForFooInClass); } [Fact] public Task TestVisualBasicMustInheritClassMember() { var markup = @" MustInherit Class {|target2:Bar1|} Public MustOverride Sub {|target4:Foo|}() End Class Class {|target1:Bar|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"Class Bar", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "MustOverride Sub Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInBar = new TestInheritanceMemberItem( lineNumber: 8, memberName: "Overrides Sub Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "MustOverride Sub Bar1.Foo()", locationTag: "target4", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForBar1, itemForBar, itemForFooInBar1, itemForFooInBar); } [Theory] [CombinatorialData] public Task TestVisualBasicOverrideMemberCanFindImplementingInterface(bool testDuplicate) { var markup1 = @" Interface {|target4:IBar|} Sub {|target6:Foo|}() End Interface Class {|target1:Bar1|} Implements IBar Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo End Sub End Class Class {|target5:Bar2|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var markup2 = @" Interface {|target4:IBar|} Sub {|target6:Foo|}() End Interface Class {|target1:Bar1|} Implements IBar Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo End Sub End Class Class {|target5:Bar2|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType), new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target5", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Sub IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Overridable Sub Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface), new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target5", relationship: InheritanceRelationship.DerivedType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "Overridable Sub Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 12, memberName: "Class Bar2", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType), new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 14, memberName: "Overrides Sub Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "Overridable Sub Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( testDuplicate ? markup2 : markup1, LanguageNames.VisualBasic, itemForIBar, itemForFooInIBar, itemForBar1, itemForFooInBar1, itemForBar2, itemForFooInBar2); } [Fact] public Task TestVisualBasicFindGenericsBaseType() { var markup = @" Public Interface {|target5:IBar|}(Of T) Sub {|target6:Foo|}() End Interface Public Class {|target1:Bar|} Implements IBar(Of Integer) Implements IBar(Of String) Public Sub {|target3:Foo|}() Implements IBar(Of Integer).Foo Throw New NotImplementedException() End Sub Private Sub {|target4:IBar_Foo|}() Implements IBar(Of String).Foo Throw New NotImplementedException() End Sub End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar(Of T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Sub IBar(Of T).Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "Sub Bar.IBar_Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar(Of T)", locationTag: "target5", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar = new TestInheritanceMemberItem( lineNumber: 10, memberName: "Sub Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar(Of T).Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar_FooInBar = new TestInheritanceMemberItem( lineNumber: 14, memberName: "Sub Bar.IBar_Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar(Of T).Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForFooInIBar, itemForBar, itemForFooInBar, itemForIBar_FooInBar); } #endregion [Fact] public Task TestCSharpProjectReferencingVisualBasicProject() { var markup1 = @" using MyNamespace; namespace BarNs { public class {|target2:Bar|} : IBar { public void {|target4:Foo|}() { } } }"; var markup2 = @" Namespace MyNamespace Public Interface {|target1:IBar|} Sub {|target3:Foo|}() End Interface End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInMarkup1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInMarkup2 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Sub IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); return VerifyInDifferentProjectsAsync( (markup1, LanguageNames.CSharp), (markup2, LanguageNames.VisualBasic), new[] { itemForBar, itemForFooInMarkup1 }, new[] { itemForIBar, itemForFooInMarkup2 }); } [Fact] public Task TestVisualBasicProjectReferencingCSharpProject() { var markup1 = @" Imports BarNs Namespace MyNamespace Public Class {|target2:Bar44|} Implements IBar Public Sub {|target4:Foo|}() Implements IBar.Foo End Sub End Class End Namespace"; var markup2 = @" namespace BarNs { public interface {|target1:IBar|} { void {|target3:Foo|}(); } }"; var itemForBar44 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar44", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInMarkup1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Sub Bar44.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar44", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInMarkup2 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub Bar44.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); return VerifyInDifferentProjectsAsync( (markup1, LanguageNames.VisualBasic), (markup2, LanguageNames.CSharp), new[] { itemForBar44, itemForFooInMarkup1 }, new[] { itemForIBar, itemForFooInMarkup2 }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.InheritanceMargin { [Trait(Traits.Feature, Traits.Features.InheritanceMargin)] [UseExportProvider] public class InheritanceMarginTests { private const string SearchAreaTag = "SeachTag"; #region Helpers private static Task VerifyNoItemForDocumentAsync(string markup, string languageName) => VerifyInSingleDocumentAsync(markup, languageName); private static Task VerifyInSingleDocumentAsync( string markup, string languageName, params TestInheritanceMemberItem[] memberItems) { markup = @$"<![CDATA[ {markup}]]>"; var workspaceFile = $@" <Workspace> <Project Language=""{languageName}"" CommonReferences=""true""> <Document> {markup} </Document> </Project> </Workspace>"; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( workspaceFile, composition: EditorTestCompositions.EditorFeatures); var testHostDocument = testWorkspace.Documents[0]; return VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument, memberItems, cancellationToken); } private static async Task VerifyTestMemberInDocumentAsync( TestWorkspace testWorkspace, TestHostDocument testHostDocument, TestInheritanceMemberItem[] memberItems, CancellationToken cancellationToken) { var document = testWorkspace.CurrentSolution.GetRequiredDocument(testHostDocument.Id); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var searchingSpan = root.Span; // Look for the search span, if not found, then pass the whole document span to the service. if (testHostDocument.AnnotatedSpans.TryGetValue(SearchAreaTag, out var spans) && spans.IsSingle()) { searchingSpan = spans[0]; } var service = document.GetRequiredLanguageService<IInheritanceMarginService>(); var actualItems = await service.GetInheritanceMemberItemsAsync( document, searchingSpan, cancellationToken).ConfigureAwait(false); var sortedActualItems = actualItems.OrderBy(item => item.LineNumber).ToImmutableArray(); var sortedExpectedItems = memberItems.OrderBy(item => item.LineNumber).ToImmutableArray(); Assert.Equal(sortedExpectedItems.Length, sortedActualItems.Length); for (var i = 0; i < sortedActualItems.Length; i++) { await VerifyInheritanceMemberAsync(testWorkspace, sortedExpectedItems[i], sortedActualItems[i]); } } private static async Task VerifyInheritanceMemberAsync(TestWorkspace testWorkspace, TestInheritanceMemberItem expectedItem, InheritanceMarginItem actualItem) { Assert.Equal(expectedItem.LineNumber, actualItem.LineNumber); Assert.Equal(expectedItem.MemberName, actualItem.DisplayTexts.JoinText()); Assert.Equal(expectedItem.Targets.Length, actualItem.TargetItems.Length); var expectedTargets = expectedItem.Targets .Select(info => TestInheritanceTargetItem.Create(info, testWorkspace)) .OrderBy(target => target.TargetSymbolName) .ToImmutableArray(); var sortedActualTargets = actualItem.TargetItems.OrderBy(target => target.DefinitionItem.DisplayParts.JoinText()) .ToImmutableArray(); for (var i = 0; i < expectedTargets.Length; i++) { await VerifyInheritanceTargetAsync(expectedTargets[i], sortedActualTargets[i]); } } private static async Task VerifyInheritanceTargetAsync(TestInheritanceTargetItem expectedTarget, InheritanceTargetItem actualTarget) { Assert.Equal(expectedTarget.TargetSymbolName, actualTarget.DefinitionItem.DisplayParts.JoinText()); Assert.Equal(expectedTarget.RelationshipToMember, actualTarget.RelationToMember); if (expectedTarget.IsInMetadata) { Assert.True(actualTarget.DefinitionItem.Properties.ContainsKey("MetadataSymbolKey")); Assert.True(actualTarget.DefinitionItem.SourceSpans.IsEmpty); } else { var actualDocumentSpans = actualTarget.DefinitionItem.SourceSpans.OrderBy(documentSpan => documentSpan.SourceSpan.Start).ToImmutableArray(); var expectedDocumentSpans = expectedTarget.DocumentSpans.OrderBy(documentSpan => documentSpan.SourceSpan.Start).ToImmutableArray(); Assert.Equal(expectedDocumentSpans.Length, actualDocumentSpans.Length); for (var i = 0; i < actualDocumentSpans.Length; i++) { Assert.Equal(expectedDocumentSpans[i].SourceSpan, actualDocumentSpans[i].SourceSpan); var rehydrated = await actualDocumentSpans[i].TryRehydrateAsync(CancellationToken.None); Assert.NotNull(rehydrated); Assert.Equal(expectedDocumentSpans[i].Document.FilePath, rehydrated.Value.Document.FilePath); } } } /// <summary> /// Project of markup1 is referencing project of markup2 /// </summary> private static async Task VerifyInDifferentProjectsAsync( (string markupInProject1, string languageName) markup1, (string markupInProject2, string languageName) markup2, TestInheritanceMemberItem[] memberItemsInMarkup1, TestInheritanceMemberItem[] memberItemsInMarkup2) { var workspaceFile = $@" <Workspace> <Project Language=""{markup1.languageName}"" AssemblyName=""Assembly1"" CommonReferences=""true""> <ProjectReference>Assembly2</ProjectReference> <Document> <![CDATA[ {markup1.markupInProject1}]]> </Document> </Project> <Project Language=""{markup2.languageName}"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> <![CDATA[ {markup2.markupInProject2}]]> </Document> </Project> </Workspace>"; var cancellationToken = CancellationToken.None; using var testWorkspace = TestWorkspace.Create( workspaceFile, composition: EditorTestCompositions.EditorFeatures); var testHostDocument1 = testWorkspace.Documents.Single(doc => doc.Project.AssemblyName.Equals("Assembly1")); var testHostDocument2 = testWorkspace.Documents.Single(doc => doc.Project.AssemblyName.Equals("Assembly2")); await VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument1, memberItemsInMarkup1, cancellationToken).ConfigureAwait(false); await VerifyTestMemberInDocumentAsync(testWorkspace, testHostDocument2, memberItemsInMarkup2, cancellationToken).ConfigureAwait(false); } private class TestInheritanceMemberItem { public readonly int LineNumber; public readonly string MemberName; public readonly ImmutableArray<TargetInfo> Targets; public TestInheritanceMemberItem( int lineNumber, string memberName, ImmutableArray<TargetInfo> targets) { LineNumber = lineNumber; MemberName = memberName; Targets = targets; } } private class TargetInfo { public readonly string TargetSymbolDisplayName; public readonly string? LocationTag; public readonly InheritanceRelationship Relationship; public readonly bool InMetadata; public TargetInfo( string targetSymbolDisplayName, string locationTag, InheritanceRelationship relationship) { TargetSymbolDisplayName = targetSymbolDisplayName; LocationTag = locationTag; Relationship = relationship; InMetadata = false; } public TargetInfo( string targetSymbolDisplayName, InheritanceRelationship relationship, bool inMetadata) { TargetSymbolDisplayName = targetSymbolDisplayName; Relationship = relationship; InMetadata = inMetadata; LocationTag = null; } } private class TestInheritanceTargetItem { public readonly string TargetSymbolName; public readonly InheritanceRelationship RelationshipToMember; public readonly ImmutableArray<DocumentSpan> DocumentSpans; public readonly bool IsInMetadata; public TestInheritanceTargetItem( string targetSymbolName, InheritanceRelationship relationshipToMember, ImmutableArray<DocumentSpan> documentSpans, bool isInMetadata) { TargetSymbolName = targetSymbolName; RelationshipToMember = relationshipToMember; DocumentSpans = documentSpans; IsInMetadata = isInMetadata; } public static TestInheritanceTargetItem Create( TargetInfo targetInfo, TestWorkspace testWorkspace) { if (targetInfo.InMetadata) { return new TestInheritanceTargetItem( targetInfo.TargetSymbolDisplayName, targetInfo.Relationship, ImmutableArray<DocumentSpan>.Empty, isInMetadata: true); } else { using var _ = ArrayBuilder<DocumentSpan>.GetInstance(out var builder); // If the target is not in metadata, there must be a location tag to give the span! Assert.True(targetInfo.LocationTag != null); foreach (var testHostDocument in testWorkspace.Documents) { if (targetInfo.LocationTag != null) { var annotatedSpans = testHostDocument.AnnotatedSpans; if (annotatedSpans.TryGetValue(targetInfo.LocationTag, out var spans)) { var document = testWorkspace.CurrentSolution.GetRequiredDocument(testHostDocument.Id); builder.AddRange(spans.Select(span => new DocumentSpan(document, span))); } } } return new TestInheritanceTargetItem( targetInfo.TargetSymbolDisplayName, targetInfo.Relationship, builder.ToImmutable(), isInMetadata: false); } } } #endregion #region TestsForCSharp [Fact] public Task TestCSharpClassWithErrorBaseType() { var markup = @" public class Bar : SomethingUnknown { }"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp); } [Fact] public Task TestCSharpReferencingMetadata() { var markup = @" using System.Collections; public class Bar : IEnumerable { public IEnumerator GetEnumerator () { return null }; }"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true))); var itemForGetEnumerator = new TestInheritanceMemberItem( lineNumber: 5, memberName: "IEnumerator Bar.GetEnumerator()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "IEnumerator IEnumerable.GetEnumerator()", relationship: InheritanceRelationship.ImplementedMember, inMetadata: true))); return VerifyInSingleDocumentAsync(markup, LanguageNames.CSharp, itemForBar, itemForGetEnumerator); } [Fact] public Task TestCSharpClassImplementingInterface() { var markup = @" interface {|target1:IBar|} { } public class {|target2:Bar|} : IBar { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Fact] public Task TestCSharpInterfaceImplementingInterface() { var markup = @" interface {|target1:IBar|} { } interface {|target2:IBar2|} : IBar { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar2", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType)) ); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar2", targets: ImmutableArray<TargetInfo>.Empty .Add(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.InheritedInterface)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Fact] public Task TestCSharpClassInheritsClass() { var markup = @" class {|target2:A|} { } class {|target1:B|} : A { } "; var itemOnLine2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class A", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class B", locationTag: "target1", relationship: InheritanceRelationship.DerivedType)) ); var itemOnLine3 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "class B", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class A", locationTag: "target2", relationship: InheritanceRelationship.BaseType)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemOnLine2, itemOnLine3); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("enum")] [InlineData("interface")] public Task TestCSharpTypeWithoutBaseType(string typeName) { var markup = $@" public {typeName} Bar {{ }}"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.CSharp); } [Theory] [InlineData("public Bar() { }")] [InlineData("public static void Bar3() { }")] [InlineData("public static void ~Bar() { }")] [InlineData("public static Bar operator +(Bar a, Bar b) => new Bar();")] public Task TestCSharpSpecialMember(string memberDeclaration) { var markup = $@" public abstract class {{|target1:Bar1|}} {{}} public class Bar : Bar1 {{ {{|{SearchAreaTag}:{memberDeclaration}|}} }}"; return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, new TestInheritanceMemberItem( lineNumber: 4, memberName: "class Bar", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType)))); } [Fact] public Task TestCSharpEventDeclaration() { var markup = @" using System; interface {|target2:IBar|} { event EventHandler {|target4:e|}; } public class {|target1:Bar|} : IBar { public event EventHandler {|target3:e|} { add {} remove {} } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 5, memberName: "event EventHandler IBar.e", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 9, memberName: "event EventHandler Bar.e", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestCSharpEventFieldDeclarations() { var markup = @"using System; interface {|target2:IBar|} { event EventHandler {|target5:e1|}, {|target6:e2|}; } public class {|target1:Bar|} : IBar { public event EventHandler {|target3:e1|}, {|target4:e2|}; }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForE1InInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "event EventHandler IBar.e1", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e1", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForE2InInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "event EventHandler IBar.e2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.e2", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForE1InClass = new TestInheritanceMemberItem( lineNumber: 8, memberName: "event EventHandler Bar.e1", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e1", locationTag: "target5", relationship: InheritanceRelationship.ImplementedMember))); var itemForE2InClass = new TestInheritanceMemberItem( lineNumber: 8, memberName: "event EventHandler Bar.e2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.e2", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForBar, itemForE1InInterface, itemForE2InInterface, itemForE1InClass, itemForE2InClass); } [Fact] public Task TestCSharpInterfaceMembers() { var markup = @"using System; interface {|target1:IBar|} { void {|target4:Foo|}(); int {|target6:Poo|} { get; set; } event EventHandler {|target8:Eoo|}; int {|target9:this|}[int i] { get; set; } } public class {|target2:Bar|} : IBar { public void {|target3:Foo|}() { } public int {|target5:Poo|} { get; set; } public event EventHandler {|target7:Eoo|}; public int {|target10:this|}[int i] { get => 1; set { } } }"; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 13, memberName: "event EventHandler Bar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler IBar.Eoo", locationTag: "target8", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForEooInInterface = new TestInheritanceMemberItem( lineNumber: 6, memberName: "event EventHandler IBar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler Bar.Eoo", locationTag: "target7", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForPooInInterface = new TestInheritanceMemberItem( lineNumber: 5, memberName: "int IBar.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int Bar.Poo { get; set; }", locationTag: "target5", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "int Bar.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int IBar.Poo { get; set; }", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForFooInInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember)) ); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 11, memberName: "void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType)) ); var itemForBar = new TestInheritanceMemberItem( lineNumber: 9, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface)) ); var itemForIndexerInClass = new TestInheritanceMemberItem( lineNumber: 14, memberName: "int Bar.this[int] { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int IBar.this[int] { get; set; }", locationTag: "target9", relationship: InheritanceRelationship.ImplementedMember)) ); var itemForIndexerInInterface = new TestInheritanceMemberItem( lineNumber: 7, memberName: "int IBar.this[int] { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int Bar.this[int] { get; set; }", locationTag: "target10", relationship: InheritanceRelationship.ImplementingMember)) ); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForEooInClass, itemForEooInInterface, itemForPooInInterface, itemForPooInClass, itemForFooInInterface, itemForFooInClass, itemForIBar, itemForBar, itemForIndexerInInterface, itemForIndexerInClass); } [Theory] [InlineData("abstract")] [InlineData("virtual")] public Task TestCSharpAbstractClassMembers(string modifier) { var markup = $@"using System; public abstract class {{|target2:Bar|}} {{ public {modifier} void {{|target4:Foo|}}(); public {modifier} int {{|target6:Poo|}} {{ get; set; }} public {modifier} event EventHandler {{|target8:Eoo|}}; }} public class {{|target1:Bar2|}} : Bar {{ public override void {{|target3:Foo|}}() {{ }} public override int {{|target5:Poo|}} {{ get; set; }} public override event EventHandler {{|target7:Eoo|}}; }} "; var itemForEooInClass = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override event EventHandler Bar2.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} event EventHandler Bar.Eoo", locationTag: "target8", relationship: InheritanceRelationship.OverriddenMember))); var itemForEooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 6, memberName: $"{modifier} event EventHandler Bar.Eoo", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override event EventHandler Bar2.Eoo", locationTag: "target7", relationship: InheritanceRelationship.OverridingMember))); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 11, memberName: "override int Bar2.Poo { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} int Bar.Poo {{ get; set; }}", locationTag: "target6", relationship: InheritanceRelationship.OverriddenMember))); var itemForPooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 5, memberName: $"{modifier} int Bar.Poo {{ get; set; }}", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override int Bar2.Poo { get; set; }", locationTag: "target5", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInAbstractClass = new TestInheritanceMemberItem( lineNumber: 4, memberName: $"{modifier} void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 10, memberName: "override void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"{modifier} void Bar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.OverriddenMember))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "class Bar2", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForBar, itemForBar2, itemForFooInAbstractClass, itemForFooInClass, itemForPooInClass, itemForPooInAbstractClass, itemForEooInClass, itemForEooInAbstractClass); } [Theory] [CombinatorialData] public Task TestCSharpOverrideMemberCanFindImplementingInterface(bool testDuplicate) { var markup1 = @"using System; public interface {|target4:IBar|} { void {|target6:Foo|}(); } public class {|target1:Bar1|} : IBar { public virtual void {|target2:Foo|}() { } } public class {|target5:Bar2|} : Bar1 { public override void {|target3:Foo|}() { } }"; var markup2 = @"using System; public interface {|target4:IBar|} { void {|target6:Foo|}(); } public class {|target1:Bar1|} : IBar { public virtual void {|target2:Foo|}() { } } public class {|target5:Bar2|} : Bar1, IBar { public override void {|target3:Foo|}() { } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType), new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target5", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "virtual void Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface), new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target5", relationship: InheritanceRelationship.DerivedType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "virtual void Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "override void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 10, memberName: "class Bar2", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType), new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 12, memberName: "override void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "virtual void Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( testDuplicate ? markup2 : markup1, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForBar1, itemForFooInBar1, itemForBar2, itemForFooInBar2); } [Fact] public Task TestCSharpFindGenericsBaseType() { var markup = @" public interface {|target2:IBar|}<T> { void {|target4:Foo|}(); } public class {|target1:Bar2|} : IBar<int>, IBar<string> { public void {|target3:Foo|}(); }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar2", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar<T>.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); // Only have one IBar<T> item var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class Bar2", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar<T>", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); // Only have one IBar<T>.Foo item var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 9, memberName: "void Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar<T>.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForBar2, itemForFooInBar2); } [Fact] public Task TestCSharpExplicitInterfaceImplementation() { var markup = @" interface {|target2:IBar|}<T> { void {|target3:Foo|}(T t); } abstract class {|target1:AbsBar|} : IBar<int> { void IBar<int>.{|target4:Foo|}(int t) { throw new System.NotImplementedException(); } }"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface IBar<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class AbsBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void IBar<T>.Foo(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void AbsBar.IBar<int>.Foo(int)", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForAbsBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "class AbsBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar<T>", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInAbsBar = new TestInheritanceMemberItem( lineNumber: 9, memberName: "void AbsBar.IBar<int>.Foo(int)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar<T>.Foo(T)", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember) )); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForIBar, itemForFooInIBar, itemForAbsBar, itemForFooInAbsBar); } [Fact] public Task TestStaticAbstractMemberInterface() { var markup = @" interface {|target5:I1|}<T> where T : I1<T> { static abstract void {|target4:M1|}(); static abstract int {|target7:P1|} { get; set; } static abstract event EventHandler {|target9:e1|}; static abstract int operator {|target11:+|}(T i1); static abstract implicit operator {|target12:int|}(T i1); } public class {|target1:Class1|} : I1<Class1> { public static void {|target2:M1|}() {} public static int {|target6:P1|} { get => 1; set { } } public static event EventHandler {|target8:e1|}; public static int operator {|target10:+|}(Class1 i) => 1; public static implicit operator {|target13:int|}(Class1 i) => 0; }"; var itemForI1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "interface I1<T>", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Class1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForM1InI1 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "void I1<T>.M1()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static void Class1.M1()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember))); var itemForAbsClass1 = new TestInheritanceMemberItem( lineNumber: 11, memberName: "class Class1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface I1<T>", locationTag: "target5", relationship: InheritanceRelationship.ImplementedInterface))); var itemForM1InClass1 = new TestInheritanceMemberItem( lineNumber: 13, memberName: "static void Class1.M1()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void I1<T>.M1()", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); var itemForP1InI1 = new TestInheritanceMemberItem( lineNumber: 5, memberName: "int I1<T>.P1 { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static int Class1.P1 { get; set; }", locationTag: "target6", relationship: InheritanceRelationship.ImplementingMember))); var itemForP1InClass1 = new TestInheritanceMemberItem( lineNumber: 14, memberName: "static int Class1.P1 { get; set; }", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int I1<T>.P1 { get; set; }", locationTag: "target7", relationship: InheritanceRelationship.ImplementedMember))); var itemForE1InI1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "event EventHandler I1<T>.e1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static event EventHandler Class1.e1", locationTag: "target8", relationship: InheritanceRelationship.ImplementingMember))); var itemForE1InClass1 = new TestInheritanceMemberItem( lineNumber: 15, memberName: "static event EventHandler Class1.e1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "event EventHandler I1<T>.e1", locationTag: "target9", relationship: InheritanceRelationship.ImplementedMember))); var itemForPlusOperatorInI1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "int I1<T>.operator +(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static int Class1.operator +(Class1)", locationTag: "target10", relationship: InheritanceRelationship.ImplementingMember))); var itemForPlusOperatorInClass1 = new TestInheritanceMemberItem( lineNumber: 16, memberName: "static int Class1.operator +(Class1)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "int I1<T>.operator +(T)", locationTag: "target11", relationship: InheritanceRelationship.ImplementedMember))); var itemForIntOperatorInI1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "I1<T>.implicit operator int(T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "static Class1.implicit operator int(Class1)", locationTag: "target13", relationship: InheritanceRelationship.ImplementingMember))); var itemForIntOperatorInClass1 = new TestInheritanceMemberItem( lineNumber: 17, memberName: "static Class1.implicit operator int(Class1)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "I1<T>.implicit operator int(T)", locationTag: "target12", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.CSharp, itemForI1, itemForAbsClass1, itemForM1InI1, itemForM1InClass1, itemForP1InI1, itemForP1InClass1, itemForE1InI1, itemForE1InClass1, itemForPlusOperatorInI1, itemForPlusOperatorInClass1, itemForIntOperatorInI1, itemForIntOperatorInClass1); } #endregion #region TestsForVisualBasic [Fact] public Task TestVisualBasicWithErrorBaseType() { var markup = @" Namespace MyNamespace Public Class Bar Implements SomethingNotExist End Class End Namespace"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic); } [Fact] public Task TestVisualBasicReferencingMetadata() { var markup = @" Namespace MyNamespace Public Class Bar Implements System.Collections.IEnumerable Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Throw New NotImplementedException() End Function End Class End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true))); var itemForGetEnumerator = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Function Bar.GetEnumerator() As IEnumerator", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function IEnumerable.GetEnumerator() As IEnumerator", relationship: InheritanceRelationship.ImplementedMember, inMetadata: true))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForBar, itemForGetEnumerator); } [Fact] public Task TestVisualBasicClassImplementingInterface() { var markup = @" Interface {|target2:IBar|} End Interface Class {|target1:Bar|} Implements IBar End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar); } [Fact] public Task TestVisualBasicInterfaceImplementingInterface() { var markup = @" Interface {|target2:IBar2|} End Interface Interface {|target1:IBar|} Inherits IBar2 End Interface"; var itemForIBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar2", locationTag: "target2", relationship: InheritanceRelationship.InheritedInterface))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForIBar2, itemForIBar); } [Fact] public Task TestVisualBasicClassInheritsClass() { var markup = @" Class {|target2:Bar2|} End Class Class {|target1:Bar|} Inherits Bar2 End Class"; var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar2", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); return VerifyInSingleDocumentAsync(markup, LanguageNames.VisualBasic, itemForBar2, itemForBar); } [Theory] [InlineData("Class")] [InlineData("Structure")] [InlineData("Enum")] [InlineData("Interface")] public Task TestVisualBasicTypeWithoutBaseType(string typeName) { var markup = $@" {typeName} Bar End {typeName}"; return VerifyNoItemForDocumentAsync(markup, LanguageNames.VisualBasic); } [Fact] public Task TestVisualBasicMetadataInterface() { var markup = @" Imports System.Collections Class Bar Implements IEnumerable End Class"; return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, new TestInheritanceMemberItem( lineNumber: 3, memberName: "Class Bar", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "Interface IEnumerable", relationship: InheritanceRelationship.ImplementedInterface, inMetadata: true)))); } [Fact] public Task TestVisualBasicEventStatement() { var markup = @" Interface {|target2:IBar|} Event {|target4:e|} As EventHandler End Interface Class {|target1:Bar|} Implements IBar Public Event {|target3:e|} As EventHandler Implements IBar.e End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Event IBar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event Bar.e As EventHandler", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Event Bar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event IBar.e As EventHandler", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestVisualBasicEventBlock() { var markup = @" Interface {|target2:IBar|} Event {|target4:e|} As EventHandler End Interface Class {|target1:Bar|} Implements IBar Public Custom Event {|target3:e|} As EventHandler Implements IBar.e End Event End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "Class Bar", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForEventInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Event IBar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event Bar.e As EventHandler", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForEventInClass = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Event Bar.e As EventHandler", ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Event IBar.e As EventHandler", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForEventInInterface, itemForEventInClass); } [Fact] public Task TestVisualBasicInterfaceMembers() { var markup = @" Interface {|target2:IBar|} Property {|target4:Poo|} As Integer Function {|target6:Foo|}() As Integer End Interface Class {|target1:Bar|} Implements IBar Public Property {|target3:Poo|} As Integer Implements IBar.Poo Get Return 1 End Get Set(value As Integer) End Set End Property Public Function {|target5:Foo|}() As Integer Implements IBar.Foo Return 1 End Function End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target2", relationship: InheritanceRelationship.ImplementedInterface))); var itemForPooInInterface = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Property IBar.Poo As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Property Bar.Poo As Integer", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForPooInClass = new TestInheritanceMemberItem( lineNumber: 9, memberName: "Property Bar.Poo As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Property IBar.Poo As Integer", locationTag: "target4", relationship: InheritanceRelationship.ImplementedMember))); var itemForFooInInterface = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Function IBar.Foo() As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function Bar.Foo() As Integer", locationTag: "target5", relationship: InheritanceRelationship.ImplementingMember))); var itemForFooInClass = new TestInheritanceMemberItem( lineNumber: 16, memberName: "Function Bar.Foo() As Integer", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Function IBar.Foo() As Integer", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForBar, itemForPooInInterface, itemForPooInClass, itemForFooInInterface, itemForFooInClass); } [Fact] public Task TestVisualBasicMustInheritClassMember() { var markup = @" MustInherit Class {|target2:Bar1|} Public MustOverride Sub {|target4:Foo|}() End Class Class {|target1:Bar|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: $"Class Bar", locationTag: "target1", relationship: InheritanceRelationship.DerivedType))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target2", relationship: InheritanceRelationship.BaseType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 3, memberName: "MustOverride Sub Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForFooInBar = new TestInheritanceMemberItem( lineNumber: 8, memberName: "Overrides Sub Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "MustOverride Sub Bar1.Foo()", locationTag: "target4", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForBar1, itemForBar, itemForFooInBar1, itemForFooInBar); } [Theory] [CombinatorialData] public Task TestVisualBasicOverrideMemberCanFindImplementingInterface(bool testDuplicate) { var markup1 = @" Interface {|target4:IBar|} Sub {|target6:Foo|}() End Interface Class {|target1:Bar1|} Implements IBar Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo End Sub End Class Class {|target5:Bar2|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var markup2 = @" Interface {|target4:IBar|} Sub {|target6:Foo|}() End Interface Class {|target1:Bar1|} Implements IBar Public Overridable Sub {|target2:Foo|}() Implements IBar.Foo End Sub End Class Class {|target5:Bar2|} Inherits Bar1 Public Overrides Sub {|target3:Foo|}() End Sub End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType), new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target5", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Sub IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Overridable Sub Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar1 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar1", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface), new TargetInfo( targetSymbolDisplayName: "Class Bar2", locationTag: "target5", relationship: InheritanceRelationship.DerivedType))); var itemForFooInBar1 = new TestInheritanceMemberItem( lineNumber: 8, memberName: "Overridable Sub Bar1.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "Overrides Sub Bar2.Foo()", locationTag: "target3", relationship: InheritanceRelationship.OverridingMember))); var itemForBar2 = new TestInheritanceMemberItem( lineNumber: 12, memberName: "Class Bar2", targets: ImmutableArray.Create( new TargetInfo( targetSymbolDisplayName: "Class Bar1", locationTag: "target1", relationship: InheritanceRelationship.BaseType), new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target4", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar2 = new TestInheritanceMemberItem( lineNumber: 14, memberName: "Overrides Sub Bar2.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember), new TargetInfo( targetSymbolDisplayName: "Overridable Sub Bar1.Foo()", locationTag: "target2", relationship: InheritanceRelationship.OverriddenMember))); return VerifyInSingleDocumentAsync( testDuplicate ? markup2 : markup1, LanguageNames.VisualBasic, itemForIBar, itemForFooInIBar, itemForBar1, itemForFooInBar1, itemForBar2, itemForFooInBar2); } [Fact] public Task TestVisualBasicFindGenericsBaseType() { var markup = @" Public Interface {|target5:IBar|}(Of T) Sub {|target6:Foo|}() End Interface Public Class {|target1:Bar|} Implements IBar(Of Integer) Implements IBar(Of String) Public Sub {|target3:Foo|}() Implements IBar(Of Integer).Foo Throw New NotImplementedException() End Sub Private Sub {|target4:IBar_Foo|}() Implements IBar(Of String).Foo Throw New NotImplementedException() End Sub End Class"; var itemForIBar = new TestInheritanceMemberItem( lineNumber: 2, memberName: "Interface IBar(Of T)", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar", locationTag: "target1", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Sub IBar(Of T).Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub Bar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementingMember), new TargetInfo( targetSymbolDisplayName: "Sub Bar.IBar_Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); var itemForBar = new TestInheritanceMemberItem( lineNumber: 6, memberName: "Class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar(Of T)", locationTag: "target5", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInBar = new TestInheritanceMemberItem( lineNumber: 10, memberName: "Sub Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar(Of T).Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar_FooInBar = new TestInheritanceMemberItem( lineNumber: 14, memberName: "Sub Bar.IBar_Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar(Of T).Foo()", locationTag: "target6", relationship: InheritanceRelationship.ImplementedMember))); return VerifyInSingleDocumentAsync( markup, LanguageNames.VisualBasic, itemForIBar, itemForFooInIBar, itemForBar, itemForFooInBar, itemForIBar_FooInBar); } #endregion [Fact] public Task TestCSharpProjectReferencingVisualBasicProject() { var markup1 = @" using MyNamespace; namespace BarNs { public class {|target2:Bar|} : IBar { public void {|target4:Foo|}() { } } }"; var markup2 = @" Namespace MyNamespace Public Interface {|target1:IBar|} Sub {|target3:Foo|}() End Interface End Namespace"; var itemForBar = new TestInheritanceMemberItem( lineNumber: 5, memberName: "class Bar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInMarkup1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "void Bar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub IBar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 3, memberName: "Interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "class Bar", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInMarkup2 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Sub IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void Bar.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); return VerifyInDifferentProjectsAsync( (markup1, LanguageNames.CSharp), (markup2, LanguageNames.VisualBasic), new[] { itemForBar, itemForFooInMarkup1 }, new[] { itemForIBar, itemForFooInMarkup2 }); } [Fact] public Task TestVisualBasicProjectReferencingCSharpProject() { var markup1 = @" Imports BarNs Namespace MyNamespace Public Class {|target2:Bar44|} Implements IBar Public Sub {|target4:Foo|}() Implements IBar.Foo End Sub End Class End Namespace"; var markup2 = @" namespace BarNs { public interface {|target1:IBar|} { void {|target3:Foo|}(); } }"; var itemForBar44 = new TestInheritanceMemberItem( lineNumber: 4, memberName: "Class Bar44", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "interface IBar", locationTag: "target1", relationship: InheritanceRelationship.ImplementedInterface))); var itemForFooInMarkup1 = new TestInheritanceMemberItem( lineNumber: 7, memberName: "Sub Bar44.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "void IBar.Foo()", locationTag: "target3", relationship: InheritanceRelationship.ImplementedMember))); var itemForIBar = new TestInheritanceMemberItem( lineNumber: 4, memberName: "interface IBar", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Class Bar44", locationTag: "target2", relationship: InheritanceRelationship.ImplementingType))); var itemForFooInMarkup2 = new TestInheritanceMemberItem( lineNumber: 6, memberName: "void IBar.Foo()", targets: ImmutableArray.Create(new TargetInfo( targetSymbolDisplayName: "Sub Bar44.Foo()", locationTag: "target4", relationship: InheritanceRelationship.ImplementingMember))); return VerifyInDifferentProjectsAsync( (markup1, LanguageNames.VisualBasic), (markup2, LanguageNames.CSharp), new[] { itemForBar44, itemForFooInMarkup1 }, new[] { itemForIBar, itemForFooInMarkup2 }); } } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/DocumentSpanExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis { internal static class DocumentSpanExtensions { public static bool CanNavigateTo(this DocumentSpan documentSpan, CancellationToken cancellationToken) { var workspace = documentSpan.Document.Project.Solution.Workspace; var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan, cancellationToken); } public static bool TryNavigateTo(this DocumentSpan documentSpan, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken) { var solution = documentSpan.Document.Project.Solution; var workspace = solution.Workspace; var service = workspace.Services.GetService<IDocumentNavigationService>(); var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, showInPreviewTab); options = options.WithChangedOption(NavigationOptions.ActivateTab, activateTab); return service.TryNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan, options, cancellationToken); } public static async Task<bool> IsHiddenAsync( this DocumentSpan documentSpan, CancellationToken cancellationToken) { var document = documentSpan.Document; if (document.SupportsSyntaxTree) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return tree.IsHiddenPosition(documentSpan.SourceSpan.Start, cancellationToken); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis { internal static class DocumentSpanExtensions { public static bool CanNavigateTo(this DocumentSpan documentSpan, CancellationToken cancellationToken) { var workspace = documentSpan.Document.Project.Solution.Workspace; var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToSpan(workspace, documentSpan.Document.Id, documentSpan.SourceSpan, cancellationToken); } public static bool TryNavigateTo(this DocumentSpan documentSpan, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken) { var solution = documentSpan.Document.Project.Solution; var workspace = solution.Workspace; var service = workspace.Services.GetService<IDocumentNavigationService>(); var options = solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, showInPreviewTab); options = options.WithChangedOption(NavigationOptions.ActivateTab, activateTab); // We're starting with one doc snapshot, but we're navigating to the current version of the doc. As such, // the span we're trying to navigate to may no longer be there. Allow for that and don't crash in that case. return service.TryNavigateToSpan( workspace, documentSpan.Document.Id, documentSpan.SourceSpan, options, allowInvalidSpan: true, cancellationToken); } public static async Task<bool> IsHiddenAsync( this DocumentSpan documentSpan, CancellationToken cancellationToken) { var document = documentSpan.Document; if (document.SupportsSyntaxTree) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return tree.IsHiddenPosition(documentSpan.SourceSpan.Start, cancellationToken); } return false; } } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/FindUsages/IRemoteFindUsagesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Composition; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { internal interface IRemoteFindUsagesService { internal interface ICallback { ValueTask AddItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken); ValueTask ItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask ReportMessageAsync(RemoteServiceCallbackId callbackId, string message, CancellationToken cancellationToken); ValueTask SetSearchTitleAsync(RemoteServiceCallbackId callbackId, string title, CancellationToken cancellationToken); ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableDefinitionItem definition, CancellationToken cancellationToken); ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSourceReferenceItem reference, CancellationToken cancellationToken); } ValueTask FindReferencesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectId, FindReferencesSearchOptions options, CancellationToken cancellationToken); ValueTask FindImplementationsAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectId, CancellationToken cancellationToken); } [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteFindUsagesService)), Shared] internal sealed class FindUsagesServerCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteFindUsagesService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindUsagesServerCallbackDispatcher() { } private new FindUsagesServerCallback GetCallback(RemoteServiceCallbackId callbackId) => (FindUsagesServerCallback)base.GetCallback(callbackId); public ValueTask AddItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken) => GetCallback(callbackId).AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetCallback(callbackId).ItemCompletedAsync(cancellationToken); public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableDefinitionItem definition, CancellationToken cancellationToken) => GetCallback(callbackId).OnDefinitionFoundAsync(definition, cancellationToken); public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSourceReferenceItem reference, CancellationToken cancellationToken) => GetCallback(callbackId).OnReferenceFoundAsync(reference, cancellationToken); public ValueTask ReportMessageAsync(RemoteServiceCallbackId callbackId, string message, CancellationToken cancellationToken) => GetCallback(callbackId).ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(RemoteServiceCallbackId callbackId, string title, CancellationToken cancellationToken) => GetCallback(callbackId).SetSearchTitleAsync(title, cancellationToken); } internal sealed class FindUsagesServerCallback { private readonly Solution _solution; private readonly IFindUsagesContext _context; private readonly Dictionary<int, DefinitionItem> _idToDefinition = new(); public FindUsagesServerCallback(Solution solution, IFindUsagesContext context) { _solution = solution; _context = context; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _context.ProgressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _context.ProgressTracker.ItemCompletedAsync(cancellationToken); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); public async ValueTask OnDefinitionFoundAsync(SerializableDefinitionItem definition, CancellationToken cancellationToken) { var id = definition.Id; var rehydrated = await definition.RehydrateAsync(_solution, cancellationToken).ConfigureAwait(false); lock (_idToDefinition) { _idToDefinition.Add(id, rehydrated); } await _context.OnDefinitionFoundAsync(rehydrated, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync(SerializableSourceReferenceItem reference, CancellationToken cancellationToken) { var rehydrated = await reference.RehydrateAsync(_solution, GetDefinition(reference.DefinitionId), cancellationToken).ConfigureAwait(false); await _context.OnReferenceFoundAsync(rehydrated, cancellationToken).ConfigureAwait(false); } private DefinitionItem GetDefinition(int definitionId) { lock (_idToDefinition) { Contract.ThrowIfFalse(_idToDefinition.ContainsKey(definitionId)); return _idToDefinition[definitionId]; } } } [DataContract] internal readonly struct SerializableDocumentSpan { [DataMember(Order = 0)] public readonly DocumentId DocumentId; [DataMember(Order = 1)] public readonly TextSpan SourceSpan; public SerializableDocumentSpan(DocumentId documentId, TextSpan sourceSpan) { DocumentId = documentId; SourceSpan = sourceSpan; } public static SerializableDocumentSpan Dehydrate(DocumentSpan documentSpan) => new(documentSpan.Document.Id, documentSpan.SourceSpan); public async ValueTask<DocumentSpan> RehydrateAsync(Solution solution, CancellationToken cancellationToken) { var document = solution.GetDocument(DocumentId) ?? await solution.GetSourceGeneratedDocumentAsync(DocumentId, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(document); return new DocumentSpan(document, SourceSpan); } } [DataContract] internal readonly struct SerializableDefinitionItem { [DataMember(Order = 0)] public readonly int Id; [DataMember(Order = 1)] public readonly ImmutableArray<string> Tags; [DataMember(Order = 2)] public readonly ImmutableArray<TaggedText> DisplayParts; [DataMember(Order = 3)] public readonly ImmutableArray<TaggedText> NameDisplayParts; [DataMember(Order = 4)] public readonly ImmutableArray<TaggedText> OriginationParts; [DataMember(Order = 5)] public readonly ImmutableArray<SerializableDocumentSpan> SourceSpans; [DataMember(Order = 6)] public readonly ImmutableDictionary<string, string> Properties; [DataMember(Order = 7)] public readonly ImmutableDictionary<string, string> DisplayableProperties; [DataMember(Order = 8)] public readonly bool DisplayIfNoReferences; public SerializableDefinitionItem( int id, ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<SerializableDocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Id = id; Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts; OriginationParts = originationParts; SourceSpans = sourceSpans; Properties = properties; DisplayableProperties = displayableProperties; DisplayIfNoReferences = displayIfNoReferences; } public static SerializableDefinitionItem Dehydrate(int id, DefinitionItem item) => new(id, item.Tags, item.DisplayParts, item.NameDisplayParts, item.OriginationParts, item.SourceSpans.SelectAsArray(ss => SerializableDocumentSpan.Dehydrate(ss)), item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); public async ValueTask<DefinitionItem> RehydrateAsync(Solution solution, CancellationToken cancellationToken) { var sourceSpans = await SourceSpans.SelectAsArrayAsync((ss, cancellationToken) => ss.RehydrateAsync(solution, cancellationToken), cancellationToken).ConfigureAwait(false); return new DefinitionItem.DefaultDefinitionItem( Tags, DisplayParts, NameDisplayParts, OriginationParts, sourceSpans, Properties, DisplayableProperties, DisplayIfNoReferences); } } [DataContract] internal readonly struct SerializableSourceReferenceItem { [DataMember(Order = 0)] public readonly int DefinitionId; [DataMember(Order = 1)] public readonly SerializableDocumentSpan SourceSpan; [DataMember(Order = 2)] public readonly SymbolUsageInfo SymbolUsageInfo; [DataMember(Order = 3)] public readonly ImmutableDictionary<string, string> AdditionalProperties; public SerializableSourceReferenceItem( int definitionId, SerializableDocumentSpan sourceSpan, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> additionalProperties) { DefinitionId = definitionId; SourceSpan = sourceSpan; SymbolUsageInfo = symbolUsageInfo; AdditionalProperties = additionalProperties; } public static SerializableSourceReferenceItem Dehydrate(int definitionId, SourceReferenceItem item) => new(definitionId, SerializableDocumentSpan.Dehydrate(item.SourceSpan), item.SymbolUsageInfo, item.AdditionalProperties); public async Task<SourceReferenceItem> RehydrateAsync(Solution solution, DefinitionItem definition, CancellationToken cancellationToken) => new(definition, await SourceSpan.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false), SymbolUsageInfo, AdditionalProperties.ToImmutableDictionary(t => t.Key, t => t.Value)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { internal interface IRemoteFindUsagesService { internal interface ICallback { ValueTask AddItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken); ValueTask ItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask ReportMessageAsync(RemoteServiceCallbackId callbackId, string message, CancellationToken cancellationToken); ValueTask SetSearchTitleAsync(RemoteServiceCallbackId callbackId, string title, CancellationToken cancellationToken); ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableDefinitionItem definition, CancellationToken cancellationToken); ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSourceReferenceItem reference, CancellationToken cancellationToken); } ValueTask FindReferencesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectId, FindReferencesSearchOptions options, CancellationToken cancellationToken); ValueTask FindImplementationsAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectId, CancellationToken cancellationToken); } [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteFindUsagesService)), Shared] internal sealed class FindUsagesServerCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteFindUsagesService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindUsagesServerCallbackDispatcher() { } private new FindUsagesServerCallback GetCallback(RemoteServiceCallbackId callbackId) => (FindUsagesServerCallback)base.GetCallback(callbackId); public ValueTask AddItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken) => GetCallback(callbackId).AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetCallback(callbackId).ItemCompletedAsync(cancellationToken); public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableDefinitionItem definition, CancellationToken cancellationToken) => GetCallback(callbackId).OnDefinitionFoundAsync(definition, cancellationToken); public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSourceReferenceItem reference, CancellationToken cancellationToken) => GetCallback(callbackId).OnReferenceFoundAsync(reference, cancellationToken); public ValueTask ReportMessageAsync(RemoteServiceCallbackId callbackId, string message, CancellationToken cancellationToken) => GetCallback(callbackId).ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(RemoteServiceCallbackId callbackId, string title, CancellationToken cancellationToken) => GetCallback(callbackId).SetSearchTitleAsync(title, cancellationToken); } internal sealed class FindUsagesServerCallback { private readonly Solution _solution; private readonly IFindUsagesContext _context; private readonly Dictionary<int, DefinitionItem> _idToDefinition = new(); public FindUsagesServerCallback(Solution solution, IFindUsagesContext context) { _solution = solution; _context = context; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _context.ProgressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _context.ProgressTracker.ItemCompletedAsync(cancellationToken); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); public async ValueTask OnDefinitionFoundAsync(SerializableDefinitionItem definition, CancellationToken cancellationToken) { var id = definition.Id; var rehydrated = await definition.RehydrateAsync(_solution, cancellationToken).ConfigureAwait(false); lock (_idToDefinition) { _idToDefinition.Add(id, rehydrated); } await _context.OnDefinitionFoundAsync(rehydrated, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync(SerializableSourceReferenceItem reference, CancellationToken cancellationToken) { var rehydrated = await reference.RehydrateAsync(_solution, GetDefinition(reference.DefinitionId), cancellationToken).ConfigureAwait(false); await _context.OnReferenceFoundAsync(rehydrated, cancellationToken).ConfigureAwait(false); } private DefinitionItem GetDefinition(int definitionId) { lock (_idToDefinition) { Contract.ThrowIfFalse(_idToDefinition.ContainsKey(definitionId)); return _idToDefinition[definitionId]; } } } [DataContract] internal readonly struct SerializableDocumentSpan { [DataMember(Order = 0)] public readonly DocumentId DocumentId; [DataMember(Order = 1)] public readonly TextSpan SourceSpan; public SerializableDocumentSpan(DocumentId documentId, TextSpan sourceSpan) { DocumentId = documentId; SourceSpan = sourceSpan; } public static SerializableDocumentSpan Dehydrate(DocumentSpan documentSpan) => new(documentSpan.Document.Id, documentSpan.SourceSpan); public async ValueTask<DocumentSpan> RehydrateAsync(Solution solution, CancellationToken cancellationToken) { var document = solution.GetDocument(DocumentId) ?? await solution.GetSourceGeneratedDocumentAsync(DocumentId, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(document); return new DocumentSpan(document, SourceSpan); } } [DataContract] internal readonly struct SerializableDefinitionItem { [DataMember(Order = 0)] public readonly int Id; [DataMember(Order = 1)] public readonly ImmutableArray<string> Tags; [DataMember(Order = 2)] public readonly ImmutableArray<TaggedText> DisplayParts; [DataMember(Order = 3)] public readonly ImmutableArray<TaggedText> NameDisplayParts; [DataMember(Order = 4)] public readonly ImmutableArray<TaggedText> OriginationParts; [DataMember(Order = 5)] public readonly ImmutableArray<SerializableDocumentSpan> SourceSpans; [DataMember(Order = 6)] public readonly ImmutableDictionary<string, string> Properties; [DataMember(Order = 7)] public readonly ImmutableDictionary<string, string> DisplayableProperties; [DataMember(Order = 8)] public readonly bool DisplayIfNoReferences; public SerializableDefinitionItem( int id, ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<SerializableDocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Id = id; Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts; OriginationParts = originationParts; SourceSpans = sourceSpans; Properties = properties; DisplayableProperties = displayableProperties; DisplayIfNoReferences = displayIfNoReferences; } public static SerializableDefinitionItem Dehydrate(int id, DefinitionItem item) => new(id, item.Tags, item.DisplayParts, item.NameDisplayParts, item.OriginationParts, item.SourceSpans.SelectAsArray(ss => SerializableDocumentSpan.Dehydrate(ss)), item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); public async ValueTask<DefinitionItem.DefaultDefinitionItem> RehydrateAsync(Solution solution, CancellationToken cancellationToken) { var sourceSpans = await SourceSpans.SelectAsArrayAsync((ss, cancellationToken) => ss.RehydrateAsync(solution, cancellationToken), cancellationToken).ConfigureAwait(false); return new DefinitionItem.DefaultDefinitionItem( Tags, DisplayParts, NameDisplayParts, OriginationParts, sourceSpans, Properties, DisplayableProperties, DisplayIfNoReferences); } } [DataContract] internal readonly struct SerializableSourceReferenceItem { [DataMember(Order = 0)] public readonly int DefinitionId; [DataMember(Order = 1)] public readonly SerializableDocumentSpan SourceSpan; [DataMember(Order = 2)] public readonly SymbolUsageInfo SymbolUsageInfo; [DataMember(Order = 3)] public readonly ImmutableDictionary<string, string> AdditionalProperties; public SerializableSourceReferenceItem( int definitionId, SerializableDocumentSpan sourceSpan, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> additionalProperties) { DefinitionId = definitionId; SourceSpan = sourceSpan; SymbolUsageInfo = symbolUsageInfo; AdditionalProperties = additionalProperties; } public static SerializableSourceReferenceItem Dehydrate(int definitionId, SourceReferenceItem item) => new(definitionId, SerializableDocumentSpan.Dehydrate(item.SourceSpan), item.SymbolUsageInfo, item.AdditionalProperties); public async Task<SourceReferenceItem> RehydrateAsync(Solution solution, DefinitionItem definition, CancellationToken cancellationToken) => new(definition, await SourceSpan.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false), SymbolUsageInfo, AdditionalProperties.ToImmutableDictionary(t => t.Key, t => t.Value)); } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/InheritanceGlyphFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Windows; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Formatting; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin { internal sealed class InheritanceGlyphFactory : IGlyphFactory { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly ClassificationTypeMap _classificationTypeMap; private readonly IClassificationFormatMap _classificationFormatMap; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly IWpfTextView _textView; public InheritanceGlyphFactory( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, IWpfTextView textView) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _classificationTypeMap = classificationTypeMap; _classificationFormatMap = classificationFormatMap; _operationExecutor = operationExecutor; _textView = textView; } public UIElement? GenerateGlyph(IWpfTextViewLine line, IGlyphTag tag) { if (tag is InheritanceMarginTag inheritanceMarginTag) { var membersOnLine = inheritanceMarginTag.MembersOnLine; Contract.ThrowIfTrue(membersOnLine.IsEmpty); return new MarginGlyph.InheritanceMargin( _threadingContext, _streamingFindUsagesPresenter, _classificationTypeMap, _classificationFormatMap, _operationExecutor, inheritanceMarginTag, _textView); } 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. using System.Windows; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Formatting; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin { internal sealed class InheritanceGlyphFactory : IGlyphFactory { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly ClassificationTypeMap _classificationTypeMap; private readonly IClassificationFormatMap _classificationFormatMap; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly IWpfTextView _textView; private readonly IAsynchronousOperationListener _listener; public InheritanceGlyphFactory( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, IWpfTextView textView, IAsynchronousOperationListener listener) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _classificationTypeMap = classificationTypeMap; _classificationFormatMap = classificationFormatMap; _operationExecutor = operationExecutor; _textView = textView; _listener = listener; } public UIElement? GenerateGlyph(IWpfTextViewLine line, IGlyphTag tag) { if (tag is not InheritanceMarginTag inheritanceMarginTag) return null; var membersOnLine = inheritanceMarginTag.MembersOnLine; Contract.ThrowIfTrue(membersOnLine.IsEmpty); return new MarginGlyph.InheritanceMargin( _threadingContext, _streamingFindUsagesPresenter, _classificationTypeMap, _classificationFormatMap, _operationExecutor, inheritanceMarginTag, _textView, _listener); } } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/InheritanceGlyphFactoryProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin { [Export(typeof(IGlyphFactoryProvider))] [Name(nameof(InheritanceGlyphFactoryProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [TagType(typeof(InheritanceMarginTag))] // This would ensure the margin is clickable. [Order(After = "VsTextMarker")] internal class InheritanceGlyphFactoryProvider : IGlyphFactoryProvider { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly ClassificationTypeMap _classificationTypeMap; private readonly IClassificationFormatMapService _classificationFormatMapService; private readonly IUIThreadOperationExecutor _operationExecutor; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InheritanceGlyphFactoryProvider( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMapService classificationFormatMapService, IUIThreadOperationExecutor operationExecutor) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _classificationTypeMap = classificationTypeMap; _classificationFormatMapService = classificationFormatMapService; _operationExecutor = operationExecutor; } public IGlyphFactory GetGlyphFactory(IWpfTextView view, IWpfTextViewMargin margin) { return new InheritanceGlyphFactory( _threadingContext, _streamingFindUsagesPresenter, _classificationTypeMap, _classificationFormatMapService.GetClassificationFormatMap("tooltip"), _operationExecutor, view); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin { [Export(typeof(IGlyphFactoryProvider))] [Name(nameof(InheritanceGlyphFactoryProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [TagType(typeof(InheritanceMarginTag))] // This would ensure the margin is clickable. [Order(After = "VsTextMarker")] internal class InheritanceGlyphFactoryProvider : IGlyphFactoryProvider { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly ClassificationTypeMap _classificationTypeMap; private readonly IClassificationFormatMapService _classificationFormatMapService; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly IAsynchronousOperationListener _listener; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InheritanceGlyphFactoryProvider( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMapService classificationFormatMapService, IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListenerProvider listenerProvider) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _classificationTypeMap = classificationTypeMap; _classificationFormatMapService = classificationFormatMapService; _operationExecutor = operationExecutor; _listener = listenerProvider.GetListener(FeatureAttribute.InheritanceMargin); } public IGlyphFactory GetGlyphFactory(IWpfTextView view, IWpfTextViewMargin margin) { return new InheritanceGlyphFactory( _threadingContext, _streamingFindUsagesPresenter, _classificationTypeMap, _classificationFormatMapService.GetClassificationFormatMap("tooltip"), _operationExecutor, view, _listener); } } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/InheritanceMargin.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.Collections.Immutable; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal partial class InheritanceMargin { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; private readonly IWpfTextView _textView; public InheritanceMargin( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, InheritanceMarginTag tag, IWpfTextView textView) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = tag.Workspace; _operationExecutor = operationExecutor; _textView = textView; InitializeComponent(); var viewModel = InheritanceMarginViewModel.Create(classificationTypeMap, classificationFormatMap, tag, textView.ZoomLevel); DataContext = viewModel; ContextMenu.DataContext = viewModel; ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource("ToolTipStyle") }; } private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e) { if (this.ContextMenu != null) { this.ContextMenu.IsOpen = true; e.Handled = true; } } private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel }) { Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction)); _operationExecutor.Execute( new UIThreadOperationExecutionOptions( title: EditorFeaturesResources.Navigating, defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent), allowCancellation: true, showProgress: false), context => GoToDefinitionHelpers.TryGoToDefinition( ImmutableArray.Create(viewModel.DefinitionItem), _workspace, string.Format(EditorFeaturesResources._0_declarations, viewModel.DisplayContent), _threadingContext, _streamingFindUsagesPresenter, context.UserCancellationToken)); } } private void ChangeBorderToHoveringColor() { SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey); SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey); } private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e) { ChangeBorderToHoveringColor(); } private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e) { // If the context menu is open, then don't reset the color of the button because we need // the margin looks like being pressed. if (!ContextMenu.IsOpen) { ResetBorderToInitialColor(); } } private void ContextMenu_OnClose(object sender, RoutedEventArgs e) { // If mouse is still hovering. Don't reset the color. The context menu might be closed because user clicks within the margin if (!IsMouseOver) { ResetBorderToInitialColor(); } // Move the focus back to textView when the context menu is closed. // It ensures the focus won't be left at the margin ResetFocus(); } private void ContextMenu_OnOpen(object sender, RoutedEventArgs e) { if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginViewModel inheritanceMarginViewModel } && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel)) { // We have two kinds of context menu. e.g. // 1. [margin] -> Header // Target1 // Target2 // Target3 // // 2. [margin] -> method Bar -> Header // -> Target1 // -> Target2 // -> method Foo -> Header // -> Target3 // -> Target4 // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1, // user is viewing the targets menu. Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e) { Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } private void ResetBorderToInitialColor() { this.Background = Brushes.Transparent; this.BorderBrush = Brushes.Transparent; } private void ResetFocus() { if (!_textView.HasAggregateFocus) { var visualElement = _textView.VisualElement; if (visualElement.Focusable) { Keyboard.Focus(visualElement); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.GoToDefinition; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal partial class InheritanceMargin { private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingFindUsagesPresenter; private readonly IUIThreadOperationExecutor _operationExecutor; private readonly Workspace _workspace; private readonly IWpfTextView _textView; private readonly IAsynchronousOperationListener _listener; public InheritanceMargin( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingFindUsagesPresenter, ClassificationTypeMap classificationTypeMap, IClassificationFormatMap classificationFormatMap, IUIThreadOperationExecutor operationExecutor, InheritanceMarginTag tag, IWpfTextView textView, IAsynchronousOperationListener listener) { _threadingContext = threadingContext; _streamingFindUsagesPresenter = streamingFindUsagesPresenter; _workspace = tag.Workspace; _operationExecutor = operationExecutor; _textView = textView; _listener = listener; InitializeComponent(); var viewModel = InheritanceMarginViewModel.Create(classificationTypeMap, classificationFormatMap, tag, textView.ZoomLevel); DataContext = viewModel; ContextMenu.DataContext = viewModel; ToolTip = new ToolTip { Content = viewModel.ToolTipTextBlock, Style = (Style)FindResource("ToolTipStyle") }; } private void InheritanceMargin_OnClick(object sender, RoutedEventArgs e) { if (this.ContextMenu != null) { this.ContextMenu.IsOpen = true; e.Handled = true; } } private void TargetMenuItem_OnClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is MenuItem { DataContext: TargetMenuItemViewModel viewModel }) { Logger.Log(FunctionId.InheritanceMargin_NavigateToTarget, KeyValueLogMessage.Create(LogType.UserAction)); var token = _listener.BeginAsyncOperation(nameof(TargetMenuItem_OnClick)); TargetMenuItem_OnClickAsync(viewModel).CompletesAsyncOperation(token); } } private async Task TargetMenuItem_OnClickAsync(TargetMenuItemViewModel viewModel) { using var context = _operationExecutor.BeginExecute( title: EditorFeaturesResources.Navigating, defaultDescription: string.Format(ServicesVSResources.Navigate_to_0, viewModel.DisplayContent), allowCancellation: true, showProgress: false); var cancellationToken = context.UserCancellationToken; var rehydrated = await viewModel.DefinitionItem.TryRehydrateAsync(cancellationToken).ConfigureAwait(false); if (rehydrated == null) return; await _streamingFindUsagesPresenter.TryNavigateToOrPresentItemsAsync( _threadingContext, _workspace, string.Format(EditorFeaturesResources._0_declarations, viewModel.DisplayContent), ImmutableArray.Create<DefinitionItem>(rehydrated), cancellationToken).ConfigureAwait(false); } private void ChangeBorderToHoveringColor() { SetResourceReference(BackgroundProperty, VsBrushes.CommandBarMenuBackgroundGradientKey); SetResourceReference(BorderBrushProperty, VsBrushes.CommandBarMenuBorderKey); } private void InheritanceMargin_OnMouseEnter(object sender, MouseEventArgs e) { ChangeBorderToHoveringColor(); } private void InheritanceMargin_OnMouseLeave(object sender, MouseEventArgs e) { // If the context menu is open, then don't reset the color of the button because we need // the margin looks like being pressed. if (!ContextMenu.IsOpen) { ResetBorderToInitialColor(); } } private void ContextMenu_OnClose(object sender, RoutedEventArgs e) { // If mouse is still hovering. Don't reset the color. The context menu might be closed because user clicks within the margin if (!IsMouseOver) { ResetBorderToInitialColor(); } // Move the focus back to textView when the context menu is closed. // It ensures the focus won't be left at the margin ResetFocus(); } private void ContextMenu_OnOpen(object sender, RoutedEventArgs e) { if (e.OriginalSource is ContextMenu { DataContext: InheritanceMarginViewModel inheritanceMarginViewModel } && inheritanceMarginViewModel.MenuItemViewModels.Any(vm => vm is TargetMenuItemViewModel)) { // We have two kinds of context menu. e.g. // 1. [margin] -> Header // Target1 // Target2 // Target3 // // 2. [margin] -> method Bar -> Header // -> Target1 // -> Target2 // -> method Foo -> Header // -> Target3 // -> Target4 // If the first level of the context menu contains a TargetMenuItemViewModel, it means here it is case 1, // user is viewing the targets menu. Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } } private void TargetsSubmenu_OnOpen(object sender, RoutedEventArgs e) { Logger.Log(FunctionId.InheritanceMargin_TargetsMenuOpen, KeyValueLogMessage.Create(LogType.UserAction)); } private void ResetBorderToInitialColor() { this.Background = Brushes.Transparent; this.BorderBrush = Brushes.Transparent; } private void ResetFocus() { if (!_textView.HasAggregateFocus) { var visualElement = _textView.VisualElement; if (visualElement.Focusable) { Keyboard.Focus(visualElement); } } } } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/TargetMenuItemViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// View model used to show the MenuItem for inheritance target. /// </summary> internal class TargetMenuItemViewModel : InheritanceMenuItemViewModel { /// <summary> /// DefinitionItem used for navigation. /// </summary> public DefinitionItem DefinitionItem { get; } // Internal for testing purpose internal TargetMenuItemViewModel( string displayContent, ImageMoniker imageMoniker, string automationName, DefinitionItem definitionItem) : base(displayContent, imageMoniker, automationName) { DefinitionItem = definitionItem; } public static TargetMenuItemViewModel Create(InheritanceTargetItem target) { var displayContent = target.DisplayName; var imageMoniker = target.Glyph.GetImageMoniker(); return new TargetMenuItemViewModel( displayContent, imageMoniker, displayContent, target.DefinitionItem); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// View model used to show the MenuItem for inheritance target. /// </summary> internal class TargetMenuItemViewModel : InheritanceMenuItemViewModel { /// <summary> /// DefinitionItem used for navigation. /// </summary> public DefinitionItem.DetachedDefinitionItem DefinitionItem { get; } // Internal for testing purpose internal TargetMenuItemViewModel( string displayContent, ImageMoniker imageMoniker, string automationName, DefinitionItem.DetachedDefinitionItem definitionItem) : base(displayContent, imageMoniker, automationName) { DefinitionItem = definitionItem; } public static TargetMenuItemViewModel Create(InheritanceTargetItem target) { var displayContent = target.DisplayName; var imageMoniker = target.Glyph.GetImageMoniker(); return new TargetMenuItemViewModel( displayContent, imageMoniker, displayContent, target.DefinitionItem); } } }
1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenImplicitImplementationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenImplicitImplementationTests : CSharpTestBase { [Fact] public void TestImplicitImplementation() { var source = @" interface Interface { void Method(int i); int Property { set; } } class Class : Interface { public void Method(int i) { System.Console.WriteLine(""Class.Method({0})"", i); } public int Property { set { System.Console.WriteLine(""Class.Property.set({0})"", value); } } } class E { public static void Main() { Class c = new Class(); Interface ic = c; c.Method(1); ic.Method(2); c.Property = 3; ic.Property = 4; } } "; CompileAndVerify(source, expectedOutput: @" Class.Method(1) Class.Method(2) Class.Property.set(3) Class.Property.set(4) "); } [Fact] public void TestImplicitImplementationGenericType() { var source = @" interface Interface<T> { void Method(T i); T Property { set; } } class Class<T> : Interface<T> { public void Method(T i) { System.Console.WriteLine(""Class.Method({0})"", i); } public T Property { set { System.Console.WriteLine(""Class.Property.set({0})"", value); } } } class E { public static void Main() { Class<int> c = new Class<int>(); Interface<int> ic = c; c.Method(1); ic.Method(2); c.Property = 3; ic.Property = 4; } } "; CompileAndVerify(source, expectedOutput: @" Class.Method(1) Class.Method(2) Class.Property.set(3) Class.Property.set(4) "); } [Fact] public void TestImplicitImplementationGenericMethod() { var source = @" interface Interface { void Method<U>(U u); } class Class : Interface { public void Method<V>(V v) { System.Console.WriteLine(""Class.Method({0})"", v); } } class E { public static void Main() { Class c = new Class(); Interface ic = c; c.Method<ulong>(1); ic.Method<ushort>(2); } } "; CompileAndVerify(source, expectedOutput: @" Class.Method(1) Class.Method(2) "); } [Fact] public void TestImplicitImplementationGenericMethodAndType() { var source = @" interface Interface<T> { void Method<U>(T i, U u); void Method<U>(U u); } class Class<T> : Interface<T> { public void Method<V>(T i, V v) { System.Console.WriteLine(""Class.Method({0}, {1})"", i, v); } public void Method<V>(V v) { System.Console.WriteLine(""Class.Method({0})"", v); } } class E { public static void Main() { Class<int> c = new Class<int>(); Interface<int> ic = c; c.Method<long>(1, 2); c.Method<ulong>(3); ic.Method<short>(4, 5); ic.Method<ushort>(6); } } "; CompileAndVerify(source, expectedOutput: @" Class.Method(1, 2) Class.Method(3) Class.Method(4, 5) Class.Method(6) "); } [Fact] public void TestImplicitImplementationInBase() { var source = @" interface Interface { void Method(int i); int Property { set; } } class Base { public void Method(int i) { System.Console.WriteLine(""Base.Method({0})"", i); } public int Property { set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } } class Derived : Base, Interface { } class E { public static void Main() { Derived d = new Derived(); Base bd = d; Interface id = d; d.Method(1); bd.Method(2); id.Method(3); d.Property = 4; bd.Property = 5; id.Property = 6; } } "; CompileAndVerify(source, expectedOutput: @" Base.Method(1) Base.Method(2) Base.Method(3) Base.Property.set(4) Base.Property.set(5) Base.Property.set(6) "); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType() { var source = @" interface Interface<T> { void Method(T i); T Property { set; } } class Base<S> { public void Method(S i) { System.Console.WriteLine(""Base.Method({0})"", i); } public S Property { set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } } class Derived : Base<uint>, Interface<uint> { } class E { public static void Main() { Derived d = new Derived(); Base<uint> bd = d; Interface<uint> id = d; d.Method(1); bd.Method(2); id.Method(3); d.Property = 4; bd.Property = 5; id.Property = 6; } } "; CompileAndVerify(source, expectedOutput: @" Base.Method(1) Base.Method(2) Base.Method(3) Base.Property.set(4) Base.Property.set(5) Base.Property.set(6) "); } [Fact] public void TestImplicitImplementationInBaseGenericMethod() { var source = @" interface Interface { void Method<U>(U u); } class Base : Interface { public void Method<V>(V v) { System.Console.WriteLine(""Base.Method({0})"", v); } } class Derived : Base, Interface { } class E { public static void Main() { Derived d = new Derived(); Base bd = d; Interface id = d; d.Method(1); bd.Method(2); id.Method(3); } } "; CompileAndVerify(source, expectedOutput: @" Base.Method(1) Base.Method(2) Base.Method(3) "); } [Fact] public void TestImplicitImplementationInBaseGenericMethodAndType() { var source = @" interface Interface<T> { void Method<U>(T i, U u); void Method<U>(U u); } class Base<T> : Interface<T> { public void Method<V>(T i, V v) { System.Console.WriteLine(""Base.Method({0}, {1})"", i, v); } public void Method<V>(V v) { System.Console.WriteLine(""Base.Method({0})"", v); } } class Derived : Base<int>, Interface<int> { } class E { public static void Main() { Derived d = new Derived(); Base<int> bd = d; Interface<int> id = d; d.Method<long>(1, 2); d.Method<ulong>(3); bd.Method<short>(4, 5); bd.Method<ushort>(6); id.Method<short>(7, 8); id.Method<ushort>(9); } } "; CompileAndVerify(source, expectedOutput: @" Base.Method(1, 2) Base.Method(3) Base.Method(4, 5) Base.Method(6) Base.Method(7, 8) Base.Method(9) "); } [Fact] public void TestImplicitImplementationInBaseOutsideAssembly() { var libSource = @" public interface Interface { void Method(int i); int Property { set; } } public class Base { public void Method(int i) { System.Console.WriteLine(""Base.Method({0})"", i); } public int Property { set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } } "; var exeSource = @" public class Derived : Base, Interface { } class E { public static void Main() { Derived d = new Derived(); Base bd = d; Interface id = d; d.Method(1); bd.Method(2); id.Method(3); d.Property = 4; bd.Property = 5; id.Property = 6; } } "; string expectedOutput = @" Base.Method(1) Base.Method(2) Base.Method(3) Base.Property.set(4) Base.Property.set(5) Base.Property.set(6) ".TrimStart(); CompileAndVerify( CreateCompilationWithMscorlibAndReference(libSource, exeSource), expectedOutput: expectedOutput); } [Fact] public void TestImplicitImplementationInBaseOutsideAssemblyGenericType() { var libSource = @" public interface Interface<T> { void Method(T i); T Property { set; } } public class Base<S> { public void Method(S i) { System.Console.WriteLine(""Base.Method({0})"", i); } public S Property { set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } }"; var exeSource = @" class Derived : Base<uint>, Interface<uint> { } class E { public static void Main() { Derived d = new Derived(); Base<uint> bd = d; Interface<uint> id = d; d.Method(1); bd.Method(2); id.Method(3); d.Property = 4; bd.Property = 5; id.Property = 6; } } "; string expectedOutput = @" Base.Method(1) Base.Method(2) Base.Method(3) Base.Property.set(4) Base.Property.set(5) Base.Property.set(6) ".TrimStart(); CompileAndVerify( CreateCompilationWithMscorlibAndReference(libSource, exeSource), expectedOutput: expectedOutput); } [Fact] public void TestImplicitImplementationInBaseOutsideAssemblyGenericMethod() { var libSource = @" public interface Interface { void Method<U>(U u); } public class Base : Interface { public void Method<V>(V v) { System.Console.WriteLine(""Base.Method({0})"", v); } }"; var exeSource = @" class Derived : Base, Interface { } class E { public static void Main() { Derived d = new Derived(); Base bd = d; Interface id = d; d.Method(1); bd.Method(2); id.Method(3); } } "; string expectedOutput = @" Base.Method(1) Base.Method(2) Base.Method(3) ".TrimStart(); CompileAndVerify( CreateCompilationWithMscorlibAndReference(libSource, exeSource), expectedOutput: expectedOutput); } [Fact] public void TestImplicitImplementationInBaseOutsideAssemblyGenericMethodAndType() { var libSource = @" public interface Interface<T> { void Method<U>(T i, U u); void Method<U>(U u); } public class Base<T> : Interface<T> { public void Method<V>(T i, V v) { System.Console.WriteLine(""Base.Method({0}, {1})"", i, v); } public void Method<V>(V v) { System.Console.WriteLine(""Base.Method({0})"", v); } }"; var exeSource = @" class Derived : Base<int>, Interface<int> { } class E { public static void Main() { Derived d = new Derived(); Base<int> bd = d; Interface<int> id = d; d.Method<long>(1, 2); d.Method<ulong>(3); bd.Method<short>(4, 5); bd.Method<ushort>(6); id.Method<short>(7, 8); id.Method<ushort>(9); } } "; string expectedOutput = @" Base.Method(1, 2) Base.Method(3) Base.Method(4, 5) Base.Method(6) Base.Method(7, 8) Base.Method(9) ".TrimStart(); CompileAndVerify( CreateCompilationWithMscorlibAndReference(libSource, exeSource), expectedOutput: expectedOutput); } /// <summary> /// In IL, list all declared interfaces *and their base interfaces*. If they don't, the /// runtime doesn't find implicit implementation of base interface methods. /// </summary> [Fact] public void TestBaseInterfaceMetadata() { var source = @" interface I1 { void goo(); } interface I2 : I1 { void bar(); } class X : I1 { void I1.goo() { System.Console.WriteLine(""X::I1.goo""); } } class Y : X, I2 { public virtual void goo() { System.Console.WriteLine(""Y.goo""); } void I2.bar() { } } class Program { static void Main() { I2 b = new Y(); b.goo(); } } "; CompileAndVerify(source, expectedOutput: "Y.goo"); } /// <summary> /// Override different accessors of a virtual property in different subtypes. /// </summary> [Fact] public void TestPartialPropertyOverriding() { var source = @" interface I { int P { get; set; } } class Base { public virtual int P { get { System.Console.WriteLine(""Base.P.get""); return 1; } set { System.Console.WriteLine(""Base.P.set""); } } } class Derived1 : Base { public override int P { get { System.Console.WriteLine(""Derived1.P.get""); return 1; } } } class Derived2 : Derived1 { public override int P { set { System.Console.WriteLine(""Derived2.P.set""); } } } class Derived3 : Derived2, I { } class Program { static void Main() { I id3 = new Derived3(); id3.P += 1; } } "; string expectedOutput = @" Derived1.P.get Derived2.P.set"; CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(540410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540410")] [Fact] public void ImplementMultipleInterfaceWithCommonBase() { var source = @" interface IBase { void PBase(); } interface IBase1 : IBase { void PBase1(); } interface IBase2 : IBase { void PBase2(); } class C1 : IBase1, IBase2 { void IBase1.PBase1() { } void IBase.PBase() {} public void PBase2() { } } "; Action<ModuleSymbol> validator = module => { var typeSymbol = module.GlobalNamespace.GetTypeMembers("C1").Single(); Assert.True(typeSymbol.Interfaces().All(iface => iface.Name == "IBase" || iface.Name == "IBase1" || iface.Name == "IBase2")); }; CompileAndVerify(source, sourceSymbolValidator: validator, symbolValidator: validator, expectedSignatures: new[] { Signature("C1", "IBase1.PBase1", ".method private hidebysig newslot virtual final instance System.Void IBase1.PBase1() cil managed"), Signature("C1", "IBase.PBase", ".method private hidebysig newslot virtual final instance System.Void IBase.PBase() cil managed"), Signature("C1", "PBase2", ".method public hidebysig newslot virtual final instance System.Void PBase2() cil managed") }); } [Fact] public void ImplementInterfaceWithMultipleBasesWithSameMethod() { var source = @" interface IBase1 { void BaseGoo(); } interface IBase2 { void BaseGoo(); } interface IInterface : IBase1, IBase2 { void InterfaceGoo(); } class C1 : IInterface { public void BaseGoo() { System.Console.Write(""BaseGoo "");} public void InterfaceGoo() { System.Console.Write(""InterfaceGoo ""); } public void Test() { C1 c = new C1(); c.BaseGoo(); c.InterfaceGoo(); ((IBase1)c).BaseGoo(); ((IBase2)c).BaseGoo(); ((IInterface)c).InterfaceGoo(); ((IInterface)c).BaseGoo(); } } "; CreateCompilation(source) .VerifyDiagnostics( // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'IBase1.BaseGoo()' and 'IBase2.BaseGoo()' // ((IInterface)c).BaseGoo(); Diagnostic(ErrorCode.ERR_AmbigCall, "BaseGoo").WithArguments("IBase1.BaseGoo()", "IBase2.BaseGoo()")); } [WorkItem(540410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540410")] [Fact] public void InterfaceDiamondInheritanceWithNewMember() { var source = @" interface IBase { void Goo(); } interface ILeft : IBase { new void Goo(); } interface IRight : IBase { void Bar(); } interface IDerived : ILeft, IRight { } class C1 : IDerived { public void Bar() { } void IBase.Goo() { System.Console.Write(""IBase "");} void ILeft.Goo() { System.Console.Write(""ILeft ""); } } public static class MainClass { static void Test(IDerived d) { d.Goo(); // Invokes ileft.goo() ((IBase)d).Goo(); // Invokes ibase.goo() ((ILeft)d).Goo(); // Invokes ileft.goo() ((IRight)d).Goo(); // Invokes ibase.goo() } public static void Main() { C1 c = new C1(); Test(c); } } "; CompileAndVerify(source, expectedOutput: "ILeft IBase ILeft IBase") .VerifyIL("MainClass.Test", @" { // Code size 25 (0x19) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""void ILeft.Goo()"" IL_0006: ldarg.0 IL_0007: callvirt ""void IBase.Goo()"" IL_000c: ldarg.0 IL_000d: callvirt ""void ILeft.Goo()"" IL_0012: ldarg.0 IL_0013: callvirt ""void IBase.Goo()"" IL_0018: ret }"); } [Fact] public void TestImplicitImplSignatureMismatches_ParamsAndOptionals() { // Tests: // Replace params with non-params in signature of implemented member (and vice-versa) // Replace optional parameter with non-optional parameter var source = @" using System; using System.Collections.Generic; interface I1<T> { void Method(int a, long b = 2, string c = null, params List<T>[] d); } interface I2 : I1<string> { void Method<T>(out int a, ref T[] b, List<T>[] c); } class Base { // Change default value of optional parameter public void Method(int a, long b = 3, string c = """", params List<string>[] d) { Console.WriteLine(""Base.Method({0}, {1}, {2})"", a, b, c); } } class Derived : Base, I1<string> // Implicit implementation in base { } class Class : I1<string> // Implicit implementation { // Replace optional with non-optional - OK public void Method(int a, long b, string c = """", params List<string>[] d) { Console.WriteLine(""Class.Method({0}, {1}, {2})"", a, b, c); } } class Class2 : I2 // Implicit implementation { // Replace non-optional with optional - OK // Omit params and replace with optional - OK public void Method(int a = 4, long b = 3, string c = """", List<string>[] d = null) { Console.WriteLine(""Class2.Method({0}, {1}, {2})"", a, b, c); } // Additional params - OK public void Method<U>(out int a, ref U[] b, params List<U>[] c) { a = 0; Console.WriteLine(""Class2.Method<U>({0}, {1})"", a, b[0]); } } class Test { public static void Main() { string[] s1 = new string[]{""a""}; List<string>[] l1 = new List<string>[]{}; I1<string> i1 = new Derived(); i1.Method(1, 2, ""b"", l1); i1 = new Class(); i1.Method(2, 3, ""c"", l1); I2 i2 = new Class2(); i2.Method(1, 2, ""b"", l1); int i = 1; i2.Method<string>(out i, ref s1, l1); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base.Method(1, 2, b) Class.Method(2, 3, c) Class2.Method(1, 2, b) Class2.Method<U>(0, a)", expectedSignatures: new[] { Signature("Base", "Method", ".method public hidebysig newslot virtual final instance System.Void Method(System.Int32 a, [opt] System.Int64 b = 3, [opt] System.String c = \"\", [System.ParamArrayAttribute()] System.Collections.Generic.List`1[System.String][] d) cil managed"), Signature("Class", "Method", ".method public hidebysig newslot virtual final instance System.Void Method(System.Int32 a, System.Int64 b, [opt] System.String c = \"\", [System.ParamArrayAttribute()] System.Collections.Generic.List`1[System.String][] d) cil managed"), Signature("Class2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method([opt] System.Int32 a = 4, [opt] System.Int64 b = 3, [opt] System.String c = \"\", [opt] System.Collections.Generic.List`1[System.String][] d) cil managed"), Signature("Class2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<U>([out] System.Int32& a, U[]& b, [System.ParamArrayAttribute()] System.Collections.Generic.List`1[U][] c) cil managed") }); } [Fact] public void ReImplementInterfaceInGrandChild() { var source = @" interface I1 { void bar(); } class C1 : I1 { void I1.bar() { System.Console.Write(""C1"");} } class C2 : C1 { } class C3 : C2, I1 { public void bar() { System.Console.Write(""C3""); } } static class Program { static void Main() { C3 c3 = new C3(); C2 c2 = c3; C1 c1 = c3; c3.bar(); ((I1)c3).bar(); ((I1)c2).bar(); ((I1)c1).bar(); } } "; CompileAndVerify(source, expectedOutput: "C3C3C3C3"); } [Fact] public void OverrideBaseClassImplementation() { var source = @" interface I1 { void Bar(); } abstract class C1 : I1 { abstract public void Bar(); } class C2 : C1 { public override void Bar() { System.Console.Write(""C2""); } } class C3 : C2 { public override void Bar() { System.Console.Write(""C3""); } } static class Program { static void Main() { I1 i = new C3(); i.Bar(); } } "; CompileAndVerify(source, expectedOutput: "C3"); } [Fact] public void TestImplementingWithVirtualMembers() { // Tests: // Implement interface member with virtual / abstract / override member // Test that appropriate (derived) member is called when invoking through interface var source = @" using System; using System.Collections.Generic; interface I1 { int Property { get; set; } void Method<T>(int a, T[] b, List<T> c); void Method(int a, System.Exception[] b); void Method(); } class Base1 { public virtual void Method() { Console.WriteLine(""Base1.Method()""); } } abstract class Class1 : Base1, I1 // Implementing with abstract / virtual / override members from current type { public abstract void Method(int b, System.Exception[] c); public abstract int Property { get; set; } public virtual void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Class1.Method<U>({0}, {1})"", i, j[0]); } public override void Method() { Console.WriteLine(""Class1.Method()""); } } class Class2 : Class1 { public override void Method(int i, System.Exception[] c) { System.Console.WriteLine(""Class2.Method({0})"", i); } public override int Property { get { System.Console.WriteLine(""Class2.Property.get()""); return 1; } set { System.Console.WriteLine(""Class2.Property.set({0})"", value); } } } abstract class Base2 : Base1 { public abstract void Method(int b, System.Exception[] c); public abstract int Property { get; set; } public virtual void Method<U>(int i, U[] j, List<U> k) { Console.WriteLine(""Base2.Method<U>({0}, {1})"", i, j[0]); } public override void Method() { Console.WriteLine(""Base2.Method()""); } } abstract class Derived : Base2, I1 // Implementing with abstract / virtual / override members from base type { public override int Property { set { System.Console.WriteLine(""Derived.Property.set()""); } } } class Derived2 : Derived, I1 { public override void Method(int i, System.Exception[] c) { System.Console.WriteLine(""Derived2.Method({0})"", i); } public override void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Derived2.Method<U>({0}, {1})"", i, j[0]); } public override int Property { get { System.Console.WriteLine(""Derived2.Property.get()""); return 1; } } } class Derived3 : Derived2, I1 { public override int Property { set { System.Console.WriteLine(""Derived3.Property.set({0})"", value); } } int I1.Property { get { System.Console.WriteLine(""Derived3.I1.Property.get()""); return 1; } set { System.Console.WriteLine(""Derived3.I1.Property.set({0})"", value); } } } class Derived4 : Derived3 { public override int Property { get { System.Console.WriteLine(""Derived4.Property.get()""); return 1; } set { System.Console.WriteLine(""Derived4.Property.set({0})"", value); } } public override void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Derived4.Method<U>({0}, {1})"", i, j[0]); } } class Test { public static void Main() { I1 i = new Derived4(); int x = 0; i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 0 }, new List<int>()); x = i.Property; i.Property = x; i = new Derived3(); i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 1 }, new List<int>()); x = i.Property; i.Property = x; i = new Derived2(); i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 2 }, new List<int>()); x = i.Property; i.Property = x; i = new Class2(); i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 3 }, new List<int>()); x = i.Property; i.Property = x; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base2.Method() Derived2.Method(1) Derived4.Method<U>(1, 0) Derived3.I1.Property.get() Derived3.I1.Property.set(1) Base2.Method() Derived2.Method(1) Derived2.Method<U>(1, 1) Derived3.I1.Property.get() Derived3.I1.Property.set(1) Base2.Method() Derived2.Method(1) Derived2.Method<U>(1, 2) Derived2.Property.get() Derived.Property.set() Class1.Method() Class2.Method(1) Class1.Method<U>(1, 3) Class2.Property.get() Class2.Property.set(1)"); } [Fact] public void TestImplementingWithSpecialVirtualMembers() { // Tests: // Implement interface member with abstract override / sealed / new member // Test that appropriate (derived) member is called when invoking through interface var source = @" using System; using System.Collections.Generic; interface I1 { int Property { set; } void Method<T>(int a, T[] b, List<T> c); void Method(int a, System.Exception[] b); void Method(); } abstract class Base1 { public virtual void Method() { Console.WriteLine(""Base1.Method()""); } public abstract void Method(int b, System.Exception[] c); public virtual void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Base1.Method<U>({0}, {1})"", i, j[0]); } public virtual int Property { get { System.Console.WriteLine(""Base1.Property.get()""); return 1; } set { System.Console.WriteLine(""Base1.Property.set({0})"", value); } } } abstract class Class1 : Base1, I1 // Implementing with abstract override / sealed override / new members from current type { public abstract override void Method(); public sealed override void Method(int i, System.Exception[] c) { System.Console.WriteLine(""Class1.Method({0})"", i); } public new int Property { get { System.Console.WriteLine(""Class1.Property.get()""); return 1; } set { System.Console.WriteLine(""Class1.Property.set({0})"", value); } } } class Class2 : Class1 { public override void Method() { Console.WriteLine(""Class2.Method()""); } } abstract class Base2 : Base1 { public abstract override void Method(); public new virtual void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Base2.Method<U>({0}, {1})"", i, j[0]); } public sealed override int Property { get { System.Console.WriteLine(""Base2.Property.get()""); return 1; } // Synthesized setter implements interface } } abstract class Derived : Base2, I1 // Implementing with abstract override / sealed override / new members from base type { } class Derived2 : Derived { public sealed override void Method(int i, System.Exception[] c) { System.Console.WriteLine(""Derived2.Method({0})"", i); } public new void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Derived2.Method<U>({0}, {1})"", i, j[0]); } public override void Method() { Console.WriteLine(""Derived2.Method()""); } } class Test { public static void Main() { I1 i = new Derived2(); int x = 0; i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 0 }, new List<int>()); i.Property = x; i = new Class2(); i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 3 }, new List<int>()); i.Property = x; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived2.Method() Derived2.Method(1) Base2.Method<U>(1, 0) Base1.Property.set(0) Class2.Method() Class1.Method(1) Base1.Method<U>(1, 3) Class1.Property.set(0)"); } [Fact] public void TestImplementingGenericNestedInterfaces_Implicit() { // Tests: // Sanity check – use open (T) and closed (C<String>) generic types in the signature of implemented methods // Implement members of generic interface nested inside other generic classes var source = @" using System; using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<K>(T a, U[] b, List<V> c, Dictionary<W, K> d); } internal class Base<X, Y> { public X Property { set { Console.WriteLine(""Derived1.set_Property""); } } public void Method<V>(X A, int[] b, List<long> C, Dictionary<Y, V> d) { Console.WriteLine(""Derived1.Method""); } } } } internal class Derived1<U, T> : Outer<U>.Inner<T>.Base<U, T>, Outer<U>.Inner<int>.Interface<long, T> { public class Derived2 : Outer<string>.Inner<int>.Interface<long, string> { public string Property { get { return null; } set { Console.WriteLine(""Derived2.set_Property""); } } public void Method<Z>(string A, int[] B, List<long> C, Dictionary<string, Z> D) { Console.WriteLine(""Derived2.Method""); } } } public class Test { public static void Main() { Outer<string>.Inner<int>.Interface<long, string> i = new Derived1<string, string>(); i.Property = """"; i.Method<string>("""", new int[]{}, new List<long>(), new Dictionary<string,string>()); i = new Derived1<string, string>.Derived2(); i.Property = """"; i.Method<string>("""", new int[] { }, new List<long>(), new Dictionary<string, string>()); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived1.set_Property Derived1.Method Derived2.set_Property Derived2.Method", expectedSignatures: new[] { Signature("Outer`1+Inner`1+Base`2", "set_Property", ".method public hidebysig newslot specialname virtual final instance System.Void set_Property(X value) cil managed"), Signature("Outer`1+Inner`1+Base`2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<V>(X A, System.Int32[] b, System.Collections.Generic.List`1[System.Int64] C, System.Collections.Generic.Dictionary`2[Y,V] d) cil managed"), Signature("Derived1`2+Derived2", "get_Property", ".method public hidebysig specialname instance System.String get_Property() cil managed"), Signature("Derived1`2+Derived2", "set_Property", ".method public hidebysig newslot specialname virtual final instance System.Void set_Property(System.String value) cil managed"), Signature("Derived1`2+Derived2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<Z>(System.String A, System.Int32[] B, System.Collections.Generic.List`1[System.Int64] C, System.Collections.Generic.Dictionary`2[System.String,Z] D) cil managed"), }); comp.VerifyDiagnostics(); } [Fact] public void TestImplementingGenericNestedInterfaces_Implicit_HideTypeParameter() { // Tests: // Implicitly implement generic methods on generic interfaces – test case where type parameter // on method hides the type parameter on class (both in interface and in implementing type) var source = @" using System; using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<long>.Inner<int>.Interface<long, Y> { public void Method<X>(long A, int[] b, List<long> C, Dictionary<Y, X> d) { Console.WriteLine(""Derived1.Method`1""); } public void Method<X, Y>(long A, int[] b, List<X> C, Dictionary<Y, Y> d) { Console.WriteLine(""Derived1.Method`2""); } } } } class Test { public static void Main() { Outer<long>.Inner<int>.Interface<long, string> i = new Outer<long>.Inner<int>.Derived1<string, string>(); i.Method<string>(1, new int[]{}, new List<long>(), new Dictionary<string, string>()); i.Method<string, int>(1, new int[]{}, new List<string>(), new Dictionary<int, int>()); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived1.Method`1 Derived1.Method`2", expectedSignatures: new[] { Signature("Outer`1+Inner`1+Derived1`2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<X>(System.Int64 A, System.Int32[] b, System.Collections.Generic.List`1[System.Int64] C, System.Collections.Generic.Dictionary`2[Y,X] d) cil managed"), Signature("Outer`1+Inner`1+Derived1`2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<X, Y>(System.Int64 A, System.Int32[] b, System.Collections.Generic.List`1[X] C, System.Collections.Generic.Dictionary`2[Y,Y] d) cil managed") }); comp.VerifyDiagnostics( // (11,25): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Interface<V, W>"), // (11,28): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Interface<V, W>"), // (15,32): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (19,32): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (19,35): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>")); } [Fact] public void TestImplementationInBaseGenericType() { // Tests: // Implicitly implement interface member in base generic type – the method that implements interface member // should depend on type parameter of base type to satisfy signature (return type / parameter type) equality // Also test variation of above case where implementing member in base generic type does not depend // on any type parameters var source = @" using System; interface Interface { void Method(int x); void Method(); } class Base<T> { public void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Base2<T> : Base<T> { public void Method() { Console.WriteLine(""Base.Method()""); } } class Derived : Base2<int>, Interface { } class Test { public static void Main() { Interface i = new Derived(); i.Method(1); i.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base.Method(T) Base.Method()"); comp.VerifyDiagnostics(); // No errors } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType2() { // Tests: // Implement I<string> implicitly in base class and I<int> implicitly in derived class – // assuming I<string> and I<int> have members with same signature (i.e. members // that don't depend on generic-ness of the interface) test which (base / derived class) // members are invoked when calling through each interface var source = @" using System; interface Interface<T> { void Method(T x); void Method(); } class Base<T> : Interface<T> { public void Method() { Console.WriteLine(""Base.Method()""); } public void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Derived<U, V> : Base<int>, Interface<U> { new public void Method() { Console.WriteLine(""Derived`2.Method()""); } public new void Method(int x) { Console.WriteLine(""Derived`2.Method(int)""); } public void Method(U x) { Console.WriteLine(""Derived`2.Method(U)""); } public void Method(V x) { Console.WriteLine(""Derived`2.Method(V)""); } } class Derived : Derived<int, string>, Interface<string> { new public void Method() { Console.WriteLine(""Derived.Method()""); } public new void Method(string x) { Console.WriteLine(""Derived.Method(string)""); } } class Test { public static void Main() { Interface<string> i = new Derived<string, int>(); i.Method(""""); i.Method(); Interface<int> j = new Derived<string, int>(); j.Method(1); j.Method(); i = new Derived(); i.Method(""""); i.Method(); j = new Derived(); j.Method(1); j.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived`2.Method(U) Derived`2.Method() Base.Method(T) Base.Method() Derived.Method(string) Derived.Method() Derived`2.Method(U) Derived`2.Method()"); comp.VerifyDiagnostics(); // No errors } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType3() { // Tests: // Variation of TestImplicitImplementationInBaseGenericType2 with overriding var source = @" using System; interface Interface<T> { void Method(T x); void Method(); } class Base<T> : Interface<T> { public virtual void Method() { Console.WriteLine(""Base.Method()""); } public virtual void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Derived<U, V> : Base<int>, Interface<U> { public override void Method() { Console.WriteLine(""Derived`2.Method()""); } public override void Method(int x) { Console.WriteLine(""Derived`2.Method(int)""); } public virtual void Method(U x) { Console.WriteLine(""Derived`2.Method(U)""); } public virtual void Method(V x) { Console.WriteLine(""Derived`2.Method(V)""); } } class Derived : Derived<int, string>, Interface<string> { public override void Method() { Console.WriteLine(""Derived.Method()""); } public override void Method(string x) { Console.WriteLine(""Derived.Method(string)""); } } class Test { public static void Main() { Interface<string> i = new Derived<string, int>(); i.Method(""""); i.Method(); Interface<int> j = new Derived<string, int>(); j.Method(1); j.Method(); i = new Derived(); i.Method(""""); i.Method(); j = new Derived(); j.Method(1); j.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived`2.Method(U) Derived`2.Method() Derived`2.Method(int) Derived`2.Method() Derived.Method(string) Derived.Method() Derived`2.Method(U) Derived.Method()"); comp.VerifyDiagnostics(); // No errors } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType4() { // Tests: // Variation of TestImplicitImplementationInBaseGenericType2 with re-implementation var source = @" using System; interface Interface<T> { void Method(T x); void Method(); } class Base<T> : Interface<T> { public void Method() { Console.WriteLine(""Base.Method()""); } public void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Derived<U, V> : Base<int>, Interface<U> { new public void Method() { Console.WriteLine(""Derived`2.Method()""); } public new void Method(int x) { Console.WriteLine(""Derived`2.Method(int)""); } public void Method(U x) { Console.WriteLine(""Derived`2.Method(U)""); } public void Method(V x) { Console.WriteLine(""Derived`2.Method(V)""); } } class Derived : Derived<int, string>, Interface<string>, Interface<int> { new public void Method() { Console.WriteLine(""Derived.Method()""); } public new void Method(string x) { Console.WriteLine(""Derived.Method(string)""); } } class Test { public static void Main() { Interface<string> i = new Derived<string, int>(); i.Method(""""); i.Method(); Interface<int> j = new Derived<string, int>(); j.Method(1); j.Method(); i = new Derived(); i.Method(""""); i.Method(); j = new Derived(); j.Method(1); j.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived`2.Method(U) Derived`2.Method() Base.Method(T) Base.Method() Derived.Method(string) Derived.Method() Derived`2.Method(U) Derived.Method()"); comp.VerifyDiagnostics( // (20,58): warning CS1956: Member 'Derived<int, string>.Method(int)' implements interface member 'Interface<int>.Method(int)' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // class Derived : Derived<int, string>, Interface<string>, Interface<int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int>").WithArguments("Derived<int, string>.Method(int)", "Interface<int>.Method(int)", "Derived").WithLocation(20, 58)); // No errors } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType5() { // Tests: // Variation of TestImplicitImplementationInBaseGenericType3 with re-implementation var source = @" using System; interface Interface<T> { void Method(T x); void Method(); } class Base<T> : Interface<T> { public virtual void Method() { Console.WriteLine(""Base.Method()""); } public virtual void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Derived<U, V> : Base<int>, Interface<U> { public override void Method() { Console.WriteLine(""Derived`2.Method()""); } public virtual void Method(U x) { Console.WriteLine(""Derived`2.Method(U)""); } public virtual void Method(V x) { Console.WriteLine(""Derived`2.Method(V)""); } } class Derived : Derived<int, string>, Interface<string>, Interface<int> { public override void Method() { Console.WriteLine(""Derived.Method()""); } public override void Method(string x) { Console.WriteLine(""Derived.Method(string)""); } public override void Method(int x) { Console.WriteLine(""Derived.Method(int)""); } } class Test { public static void Main() { Interface<string> i = new Derived<string, int>(); i.Method(""""); i.Method(); Interface<int> j = new Derived<string, int>(); j.Method(1); j.Method(); i = new Derived(); i.Method(""""); i.Method(); j = new Derived(); j.Method(1); j.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived`2.Method(U) Derived`2.Method() Base.Method(T) Derived`2.Method() Derived.Method(string) Derived.Method() Derived.Method(int) Derived.Method()"); comp.VerifyDiagnostics(); // No errors } [Fact] public void ImplementInterfaceUsingSynthesizedSealedProperty() { // Tests: // Implicitly implement a property / indexer with a sealed property / indexer in base class – // test case where only one accessor is implemented by this sealed property / indexer in base class var text = @" using System; interface I1 { int Bar { get; } } class C1 { public virtual int Bar { get { return 23123;} set { }} } class C2 : C1, I1 { sealed public override int Bar { set { } } // Getter will be synthesized by compiler } class Test { public static void Main() { I1 i = new C2(); Console.WriteLine(i.Bar); } } "; // TODO: Will need to update once CompilerGeneratedAttribute is emitted on synthesized accessor var comp = CompileAndVerify(text, expectedOutput: "23123", expectedSignatures: new[] { Signature("C2", "get_Bar", ".method public hidebysig specialname virtual final instance System.Int32 get_Bar() cil managed"), Signature("C2", "set_Bar", ".method public hidebysig specialname virtual final instance System.Void set_Bar(System.Int32 value) cil managed") }); } [Fact] public void TestImplementAmbiguousSignaturesImplicitly() { var source = @" using System; interface I1 { int P { set; } void M1(long x); void M2(long x); void M3(long x); void M4(ref long x); void M5(out long x); void M6(ref long x); void M7(out long x); void M8(params long[] x); void M9(long[] x); } interface I2 : I1 { } interface I3 : I2 { new long P { set; } new int M1(long x); // Return type void M2(ref long x); // Add ref void M3(out long x); // Add out void M4(long x); // Omit ref void M5(long x); // Omit out void M6(out long x); // Toggle ref to out void M7(ref long x); // Toggle out to ref new void M8(long[] x); // Omit params new void M9(params long[] x); // Add params } class Test : I3 { int I1.P { set { Console.WriteLine(""I1.P""); } } // Not possible to implement both I3.P and I1.P implicitly public long P { get { return 0; } set { Console.WriteLine(""I3.P""); } } public void M1(long x) { Console.WriteLine(""I1.M1""); } // Not possible to implement both I3.M1 and I1.M1 implicitly int I3.M1(long x) { Console.WriteLine(""I3.M1""); return 0; } public void M2(ref long x) { Console.WriteLine(""I3.M2""); } public void M2(long x) { Console.WriteLine(""I1.M2""); } public void M3(long x) { Console.WriteLine(""I1.M3""); } public void M3(out long x) { x = 0; Console.WriteLine(""I3.M3""); } public void M4(long x) { Console.WriteLine(""I3.M4""); } public void M4(ref long x) { Console.WriteLine(""I1.M4""); } public void M5(out long x) { x = 0; Console.WriteLine(""I3.M5""); } public void M5(long x) { Console.WriteLine(""I1.M5""); } void I1.M6(ref long x) { x = 0; Console.WriteLine(""I1.M6""); } // Not possible to implement both I3.M6 and I1.M6 implicitly public void M6(out long x) { x = 0; Console.WriteLine(""I3.M6""); } void I3.M7(ref long x) { Console.WriteLine(""I3.M7""); } public void M7(out long x) { x = 0; Console.WriteLine(""I1.M7""); } // Not possible to implement both I3.M7 and I1.M7 implicitly public void M8(long[] x) { Console.WriteLine(""I3.M8+I1.M8""); } // Implements both I3.M8 and I1.M8 public void M9(params long[] x) { Console.WriteLine(""I3.M9+I1.M9""); } // Implements both I3.M9 and I1.M9 public static void Main() { I3 i = new Test(); long x = 1; i.M1(x); i.M2(x); i.M2(ref x); i.M3(x); i.M3(out x); i.M4(x); i.M4(ref x); i.M5(x); i.M5(out x); i.M6(out x); i.M6(ref x); i.M7(ref x); i.M7(out x); i.M8(new long[] { x, x, x }); i.M8(x, x, x); i.M9(new long[] { x, x, x }); i.M9(x, x, x); i.P = 1; I1 j = i; j.M1(x); j.M2(x); j.M3(x); j.M4(ref x); j.M5(out x); j.M6(ref x); j.M7(out x); j.M8(new long[] { x, x, x }); j.M8(x, x, x); j.M9(new long[] { x, x, x }); j.P = 1; } }"; CompileAndVerify(source, expectedOutput: @" I3.M1 I1.M2 I3.M2 I1.M3 I3.M3 I3.M4 I1.M4 I1.M5 I3.M5 I3.M6 I1.M6 I3.M7 I1.M7 I3.M8+I1.M8 I3.M8+I1.M8 I3.M9+I1.M9 I3.M9+I1.M9 I3.P I1.M1 I1.M2 I1.M3 I1.M4 I3.M5 I1.M6 I1.M7 I3.M8+I1.M8 I3.M8+I1.M8 I3.M9+I1.M9 I1.P").VerifyDiagnostics(); // No errors } [Fact] public void TestImplementAmbiguousSignaturesImplicitlyInBase() { var source = @" using System; interface I1 { int P { set; } void M1(long x); void M2(long x); void M3(long x); void M4(ref long x); void M5(out long x); void M6(ref long x); void M7(out long x); void M8(params long[] x); void M9(long[] x); } interface I2 : I1 { } interface I3 : I2 { new long P { set; } new int M1(long x); // Return type void M2(ref long x); // Add ref void M3(out long x); // Add out void M4(long x); // Omit ref void M5(long x); // Omit out void M6(out long x); // Toggle ref to out void M7(ref long x); // Toggle out to ref new void M8(long[] x); // Omit params new void M9(params long[] x); // Add params } class Base { public long P { get { return 0; } set { Console.WriteLine(""I3.P""); } } public void M1(long x) { Console.WriteLine(""I1.M1""); } public void M2(ref long x) { Console.WriteLine(""I3.M2""); } public void M2(long x) { Console.WriteLine(""I1.M2""); } public void M3(long x) { Console.WriteLine(""I1.M3""); } public void M3(out long x) { x = 0; Console.WriteLine(""I3.M3""); } public void M4(long x) { Console.WriteLine(""I3.M4""); } public void M4(ref long x) { Console.WriteLine(""I1.M4""); } public void M5(out long x) { x = 0; Console.WriteLine(""I3.M5""); } public void M5(long x) { Console.WriteLine(""I1.M5""); } public void M6(out long x) { x = 0; Console.WriteLine(""I3.M6""); } public void M7(out long x) { x = 0; Console.WriteLine(""I1.M7""); } public void M8(long[] x) { Console.WriteLine(""Base:I3.M8+I1.M8""); } public void M9(params long[] x) { Console.WriteLine(""Base:I3.M9+I1.M9""); } } class Test : Base, I3 { int I1.P { set { Console.WriteLine(""I1.P""); } } // Not possible to implement both I3.P and I1.P implicitly int I3.M1(long x) { Console.WriteLine(""I3.M1""); return 0; } // Not possible to implement both I3.M1 and I1.M1 implicitly public void M6(ref long x) { x = 0; Console.WriteLine(""I1.M6""); } // Not possible to implement both I3.M6 and I1.M6 implicitly in same class public void M7(ref long x) { Console.WriteLine(""I3.M7""); } // Not possible to implement both I3.M7 and I1.M7 implicitly in same class public void M8(params long[] x) { Console.WriteLine(""Derived:I3.M8+I1.M8""); } // Implements both I3.M8 and I1.M8 public void M9(long[] x) { Console.WriteLine(""Derived:I3.M9+I1.M9""); } // Implements both I3.M9 and I1.M9 public static void Main() { I3 i = new Test(); long x = 1; i.M1(x); i.M2(x); i.M2(ref x); i.M3(x); i.M3(out x); i.M4(x); i.M4(ref x); i.M5(x); i.M5(out x); i.M6(out x); i.M6(ref x); i.M7(ref x); i.M7(out x); i.M8(new long[] { x, x, x }); i.M8(x, x, x); i.M9(new long[] { x, x, x }); i.M9(x, x, x); i.P = 1; I1 j = i; j.M1(x); j.M2(x); j.M3(x); j.M4(ref x); j.M5(out x); j.M6(ref x); j.M7(out x); j.M8(new long[] { x, x, x }); j.M8(x, x, x); j.M9(new long[] { x, x, x }); j.P = 1; } }"; var comp = CompileAndVerify(source, expectedOutput: @" I3.M1 I1.M2 I3.M2 I1.M3 I3.M3 I3.M4 I1.M4 I1.M5 I3.M5 I1.M6 I1.M6 I3.M7 I3.M7 Derived:I3.M8+I1.M8 Derived:I3.M8+I1.M8 Derived:I3.M9+I1.M9 Derived:I3.M9+I1.M9 I3.P I1.M1 I1.M2 I1.M3 I1.M4 I3.M5 I1.M6 I3.M7 Derived:I3.M8+I1.M8 Derived:I3.M8+I1.M8 Derived:I3.M9+I1.M9 I1.P"); comp.VerifyDiagnostics( // (55,17): warning CS0108: 'Test.M8(params long[])' hides inherited member 'Base.M8(long[])'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M8").WithArguments("Test.M8(params long[])", "Base.M8(long[])"), // (56,17): warning CS0108: 'Test.M9(long[])' hides inherited member 'Base.M9(params long[])'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M9").WithArguments("Test.M9(long[])", "Base.M9(params long[])")); } [Fact] public void TestImplementingWithObjectMembers() { var source = @" using System; interface I { string ToString(); int GetHashCode(); } class C : I { } class Base { public override string ToString() { return ""Base.ToString""; } } class Derived : Base, I { } class Test { public static void Main() { I i = new C(); i = new Derived(); Console.WriteLine(i.ToString()); } }"; CompileAndVerify(source, expectedOutput: "Base.ToString").VerifyDiagnostics(); // No errors } [Fact] public void TestImplementHiddenMemberImplicitly() { var source = @" using System; interface I1 { void Method(int i); int P { set; } } interface I2 : I1 { new void Method(int i); new int P { set; } } class B { public int P { set { Console.WriteLine(""B.set_Property""); } } } class C : B, I2 { public void Method(int j) { Console.WriteLine(""C.Method""); } } class Test { public static void Main() { I2 i = new C(); I1 j = i; i.Method(1); i.P = 0; j.Method(1); j.P = 0; } }"; CompileAndVerify(source, expectedOutput: @" C.Method B.set_Property C.Method B.set_Property").VerifyDiagnostics(); // No errors } [Fact] public void TestImplementHiddenMemberImplicitly2() { var source = @" using System; interface I1 { void Method(int i); long P { set; } } interface I2 : I1 { new int Method(int i); new int P { set; } } class B { public int P { set { Console.WriteLine(""B.set_Property""); } } public int Method(int j) { Console.WriteLine(""B.Method""); return 0; } } class C : B, I2 { public new long P { set { Console.WriteLine(""C.set_Property""); } } public new void Method(int j) { Console.WriteLine(""C.Method""); } } class Test { public static void Main() { I2 i = new C(); I1 j = i; i.Method(1); i.P = 0; j.Method(1); j.P = 0; } }"; CompileAndVerify(source, expectedOutput: @" B.Method B.set_Property C.Method C.set_Property").VerifyDiagnostics(); // No errors } [Fact] public void TestImplicitImplementationWithHidingAcrossBaseTypes() { var source = @"using System; interface I { void Method(int i); long P { set; } } class B1 { public void Method(int j) { Console.WriteLine(""B1.Method""); } public int P { get { return 0; } set { Console.WriteLine(""B1.set_Property""); } } } class B2 : B1 { } class B3 : B2 { public new void Method(int j) { Console.WriteLine(""B3.Method""); } public new long P { set { Console.WriteLine(""B3.set_Property""); } } } class B4 : B3 { } class D : B4, I { public new int Method(int j) { Console.WriteLine(""D.Method""); return 0; } public new long P { get { return 0; } set { Console.WriteLine(""D.set_Property""); } } } class Test { public static void Main() { I i = new D(); i.Method(1); i.P = 0; } }"; CompileAndVerify(source, expectedOutput: @" B3.Method D.set_Property").VerifyDiagnostics(); // No errors } [Fact] public void TestImplicitImplementationAcrossBaseTypes() { var source = @"using System; interface I { void Method(int i); long P { set; } void M(); } class B1 { public void Method(int j) { Console.WriteLine(""B1.Method""); } public long P { get { return 0; } set { Console.WriteLine(""B1.set_Property""); } } } class B2 : B1 { protected new void Method(int j) { Console.WriteLine(""B2.Method""); } // non-public members should be ignored public void M() { Console.WriteLine(""B2.M""); } } class B3 : B2 { internal new void Method(int j) { Console.WriteLine(""B3.Method""); } // non-public members should be ignored } class D : B3, I { public static new long P { set { Console.WriteLine(""D.set_Property""); } } // static members should be ignored public new void M() { Console.WriteLine(""D.M""); } // should pick the member in most derived class } class Test { public static void Main() { I i = new D(); i.Method(1); i.P = 0; i.M(); } }"; CompileAndVerify(source, expectedOutput: @" B1.Method B1.set_Property D.M").VerifyDiagnostics(); // No errors } /// <summary> /// Compile libSource into a dll and then compile exeSource with that DLL as a reference. /// Assert that neither compilation has errors. Return the exe compilation. /// </summary> private static CSharpCompilation CreateCompilationWithMscorlibAndReference(string libSource, string exeSource) { var libComp = CreateCompilation(libSource, options: TestOptions.ReleaseDll, assemblyName: "OtherAssembly"); libComp.VerifyDiagnostics(); var exeComp = CreateCompilation(exeSource, options: TestOptions.ReleaseExe, references: new[] { new CSharpCompilationReference(libComp) }); exeComp.VerifyDiagnostics(); return exeComp; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenImplicitImplementationTests : CSharpTestBase { [Fact] public void TestImplicitImplementation() { var source = @" interface Interface { void Method(int i); int Property { set; } } class Class : Interface { public void Method(int i) { System.Console.WriteLine(""Class.Method({0})"", i); } public int Property { set { System.Console.WriteLine(""Class.Property.set({0})"", value); } } } class E { public static void Main() { Class c = new Class(); Interface ic = c; c.Method(1); ic.Method(2); c.Property = 3; ic.Property = 4; } } "; CompileAndVerify(source, expectedOutput: @" Class.Method(1) Class.Method(2) Class.Property.set(3) Class.Property.set(4) "); } [Fact] public void TestImplicitImplementationGenericType() { var source = @" interface Interface<T> { void Method(T i); T Property { set; } } class Class<T> : Interface<T> { public void Method(T i) { System.Console.WriteLine(""Class.Method({0})"", i); } public T Property { set { System.Console.WriteLine(""Class.Property.set({0})"", value); } } } class E { public static void Main() { Class<int> c = new Class<int>(); Interface<int> ic = c; c.Method(1); ic.Method(2); c.Property = 3; ic.Property = 4; } } "; CompileAndVerify(source, expectedOutput: @" Class.Method(1) Class.Method(2) Class.Property.set(3) Class.Property.set(4) "); } [Fact] public void TestImplicitImplementationGenericMethod() { var source = @" interface Interface { void Method<U>(U u); } class Class : Interface { public void Method<V>(V v) { System.Console.WriteLine(""Class.Method({0})"", v); } } class E { public static void Main() { Class c = new Class(); Interface ic = c; c.Method<ulong>(1); ic.Method<ushort>(2); } } "; CompileAndVerify(source, expectedOutput: @" Class.Method(1) Class.Method(2) "); } [Fact] public void TestImplicitImplementationGenericMethodAndType() { var source = @" interface Interface<T> { void Method<U>(T i, U u); void Method<U>(U u); } class Class<T> : Interface<T> { public void Method<V>(T i, V v) { System.Console.WriteLine(""Class.Method({0}, {1})"", i, v); } public void Method<V>(V v) { System.Console.WriteLine(""Class.Method({0})"", v); } } class E { public static void Main() { Class<int> c = new Class<int>(); Interface<int> ic = c; c.Method<long>(1, 2); c.Method<ulong>(3); ic.Method<short>(4, 5); ic.Method<ushort>(6); } } "; CompileAndVerify(source, expectedOutput: @" Class.Method(1, 2) Class.Method(3) Class.Method(4, 5) Class.Method(6) "); } [Fact] public void TestImplicitImplementationInBase() { var source = @" interface Interface { void Method(int i); int Property { set; } } class Base { public void Method(int i) { System.Console.WriteLine(""Base.Method({0})"", i); } public int Property { set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } } class Derived : Base, Interface { } class E { public static void Main() { Derived d = new Derived(); Base bd = d; Interface id = d; d.Method(1); bd.Method(2); id.Method(3); d.Property = 4; bd.Property = 5; id.Property = 6; } } "; CompileAndVerify(source, expectedOutput: @" Base.Method(1) Base.Method(2) Base.Method(3) Base.Property.set(4) Base.Property.set(5) Base.Property.set(6) "); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType() { var source = @" interface Interface<T> { void Method(T i); T Property { set; } } class Base<S> { public void Method(S i) { System.Console.WriteLine(""Base.Method({0})"", i); } public S Property { set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } } class Derived : Base<uint>, Interface<uint> { } class E { public static void Main() { Derived d = new Derived(); Base<uint> bd = d; Interface<uint> id = d; d.Method(1); bd.Method(2); id.Method(3); d.Property = 4; bd.Property = 5; id.Property = 6; } } "; CompileAndVerify(source, expectedOutput: @" Base.Method(1) Base.Method(2) Base.Method(3) Base.Property.set(4) Base.Property.set(5) Base.Property.set(6) "); } [Fact] public void TestImplicitImplementationInBaseGenericMethod() { var source = @" interface Interface { void Method<U>(U u); } class Base : Interface { public void Method<V>(V v) { System.Console.WriteLine(""Base.Method({0})"", v); } } class Derived : Base, Interface { } class E { public static void Main() { Derived d = new Derived(); Base bd = d; Interface id = d; d.Method(1); bd.Method(2); id.Method(3); } } "; CompileAndVerify(source, expectedOutput: @" Base.Method(1) Base.Method(2) Base.Method(3) "); } [Fact] public void TestImplicitImplementationInBaseGenericMethodAndType() { var source = @" interface Interface<T> { void Method<U>(T i, U u); void Method<U>(U u); } class Base<T> : Interface<T> { public void Method<V>(T i, V v) { System.Console.WriteLine(""Base.Method({0}, {1})"", i, v); } public void Method<V>(V v) { System.Console.WriteLine(""Base.Method({0})"", v); } } class Derived : Base<int>, Interface<int> { } class E { public static void Main() { Derived d = new Derived(); Base<int> bd = d; Interface<int> id = d; d.Method<long>(1, 2); d.Method<ulong>(3); bd.Method<short>(4, 5); bd.Method<ushort>(6); id.Method<short>(7, 8); id.Method<ushort>(9); } } "; CompileAndVerify(source, expectedOutput: @" Base.Method(1, 2) Base.Method(3) Base.Method(4, 5) Base.Method(6) Base.Method(7, 8) Base.Method(9) "); } [Fact] public void TestImplicitImplementationInBaseOutsideAssembly() { var libSource = @" public interface Interface { void Method(int i); int Property { set; } } public class Base { public void Method(int i) { System.Console.WriteLine(""Base.Method({0})"", i); } public int Property { set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } } "; var exeSource = @" public class Derived : Base, Interface { } class E { public static void Main() { Derived d = new Derived(); Base bd = d; Interface id = d; d.Method(1); bd.Method(2); id.Method(3); d.Property = 4; bd.Property = 5; id.Property = 6; } } "; string expectedOutput = @" Base.Method(1) Base.Method(2) Base.Method(3) Base.Property.set(4) Base.Property.set(5) Base.Property.set(6) ".TrimStart(); CompileAndVerify( CreateCompilationWithMscorlibAndReference(libSource, exeSource), expectedOutput: expectedOutput); } [Fact] public void TestImplicitImplementationInBaseOutsideAssemblyGenericType() { var libSource = @" public interface Interface<T> { void Method(T i); T Property { set; } } public class Base<S> { public void Method(S i) { System.Console.WriteLine(""Base.Method({0})"", i); } public S Property { set { System.Console.WriteLine(""Base.Property.set({0})"", value); } } }"; var exeSource = @" class Derived : Base<uint>, Interface<uint> { } class E { public static void Main() { Derived d = new Derived(); Base<uint> bd = d; Interface<uint> id = d; d.Method(1); bd.Method(2); id.Method(3); d.Property = 4; bd.Property = 5; id.Property = 6; } } "; string expectedOutput = @" Base.Method(1) Base.Method(2) Base.Method(3) Base.Property.set(4) Base.Property.set(5) Base.Property.set(6) ".TrimStart(); CompileAndVerify( CreateCompilationWithMscorlibAndReference(libSource, exeSource), expectedOutput: expectedOutput); } [Fact] public void TestImplicitImplementationInBaseOutsideAssemblyGenericMethod() { var libSource = @" public interface Interface { void Method<U>(U u); } public class Base : Interface { public void Method<V>(V v) { System.Console.WriteLine(""Base.Method({0})"", v); } }"; var exeSource = @" class Derived : Base, Interface { } class E { public static void Main() { Derived d = new Derived(); Base bd = d; Interface id = d; d.Method(1); bd.Method(2); id.Method(3); } } "; string expectedOutput = @" Base.Method(1) Base.Method(2) Base.Method(3) ".TrimStart(); CompileAndVerify( CreateCompilationWithMscorlibAndReference(libSource, exeSource), expectedOutput: expectedOutput); } [Fact] public void TestImplicitImplementationInBaseOutsideAssemblyGenericMethodAndType() { var libSource = @" public interface Interface<T> { void Method<U>(T i, U u); void Method<U>(U u); } public class Base<T> : Interface<T> { public void Method<V>(T i, V v) { System.Console.WriteLine(""Base.Method({0}, {1})"", i, v); } public void Method<V>(V v) { System.Console.WriteLine(""Base.Method({0})"", v); } }"; var exeSource = @" class Derived : Base<int>, Interface<int> { } class E { public static void Main() { Derived d = new Derived(); Base<int> bd = d; Interface<int> id = d; d.Method<long>(1, 2); d.Method<ulong>(3); bd.Method<short>(4, 5); bd.Method<ushort>(6); id.Method<short>(7, 8); id.Method<ushort>(9); } } "; string expectedOutput = @" Base.Method(1, 2) Base.Method(3) Base.Method(4, 5) Base.Method(6) Base.Method(7, 8) Base.Method(9) ".TrimStart(); CompileAndVerify( CreateCompilationWithMscorlibAndReference(libSource, exeSource), expectedOutput: expectedOutput); } /// <summary> /// In IL, list all declared interfaces *and their base interfaces*. If they don't, the /// runtime doesn't find implicit implementation of base interface methods. /// </summary> [Fact] public void TestBaseInterfaceMetadata() { var source = @" interface I1 { void goo(); } interface I2 : I1 { void bar(); } class X : I1 { void I1.goo() { System.Console.WriteLine(""X::I1.goo""); } } class Y : X, I2 { public virtual void goo() { System.Console.WriteLine(""Y.goo""); } void I2.bar() { } } class Program { static void Main() { I2 b = new Y(); b.goo(); } } "; CompileAndVerify(source, expectedOutput: "Y.goo"); } /// <summary> /// Override different accessors of a virtual property in different subtypes. /// </summary> [Fact] public void TestPartialPropertyOverriding() { var source = @" interface I { int P { get; set; } } class Base { public virtual int P { get { System.Console.WriteLine(""Base.P.get""); return 1; } set { System.Console.WriteLine(""Base.P.set""); } } } class Derived1 : Base { public override int P { get { System.Console.WriteLine(""Derived1.P.get""); return 1; } } } class Derived2 : Derived1 { public override int P { set { System.Console.WriteLine(""Derived2.P.set""); } } } class Derived3 : Derived2, I { } class Program { static void Main() { I id3 = new Derived3(); id3.P += 1; } } "; string expectedOutput = @" Derived1.P.get Derived2.P.set"; CompileAndVerify(source, expectedOutput: expectedOutput); } [WorkItem(540410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540410")] [Fact] public void ImplementMultipleInterfaceWithCommonBase() { var source = @" interface IBase { void PBase(); } interface IBase1 : IBase { void PBase1(); } interface IBase2 : IBase { void PBase2(); } class C1 : IBase1, IBase2 { void IBase1.PBase1() { } void IBase.PBase() {} public void PBase2() { } } "; Action<ModuleSymbol> validator = module => { var typeSymbol = module.GlobalNamespace.GetTypeMembers("C1").Single(); Assert.True(typeSymbol.Interfaces().All(iface => iface.Name == "IBase" || iface.Name == "IBase1" || iface.Name == "IBase2")); }; CompileAndVerify(source, sourceSymbolValidator: validator, symbolValidator: validator, expectedSignatures: new[] { Signature("C1", "IBase1.PBase1", ".method private hidebysig newslot virtual final instance System.Void IBase1.PBase1() cil managed"), Signature("C1", "IBase.PBase", ".method private hidebysig newslot virtual final instance System.Void IBase.PBase() cil managed"), Signature("C1", "PBase2", ".method public hidebysig newslot virtual final instance System.Void PBase2() cil managed") }); } [Fact] public void ImplementInterfaceWithMultipleBasesWithSameMethod() { var source = @" interface IBase1 { void BaseGoo(); } interface IBase2 { void BaseGoo(); } interface IInterface : IBase1, IBase2 { void InterfaceGoo(); } class C1 : IInterface { public void BaseGoo() { System.Console.Write(""BaseGoo "");} public void InterfaceGoo() { System.Console.Write(""InterfaceGoo ""); } public void Test() { C1 c = new C1(); c.BaseGoo(); c.InterfaceGoo(); ((IBase1)c).BaseGoo(); ((IBase2)c).BaseGoo(); ((IInterface)c).InterfaceGoo(); ((IInterface)c).BaseGoo(); } } "; CreateCompilation(source) .VerifyDiagnostics( // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'IBase1.BaseGoo()' and 'IBase2.BaseGoo()' // ((IInterface)c).BaseGoo(); Diagnostic(ErrorCode.ERR_AmbigCall, "BaseGoo").WithArguments("IBase1.BaseGoo()", "IBase2.BaseGoo()")); } [WorkItem(540410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540410")] [Fact] public void InterfaceDiamondInheritanceWithNewMember() { var source = @" interface IBase { void Goo(); } interface ILeft : IBase { new void Goo(); } interface IRight : IBase { void Bar(); } interface IDerived : ILeft, IRight { } class C1 : IDerived { public void Bar() { } void IBase.Goo() { System.Console.Write(""IBase "");} void ILeft.Goo() { System.Console.Write(""ILeft ""); } } public static class MainClass { static void Test(IDerived d) { d.Goo(); // Invokes ileft.goo() ((IBase)d).Goo(); // Invokes ibase.goo() ((ILeft)d).Goo(); // Invokes ileft.goo() ((IRight)d).Goo(); // Invokes ibase.goo() } public static void Main() { C1 c = new C1(); Test(c); } } "; CompileAndVerify(source, expectedOutput: "ILeft IBase ILeft IBase") .VerifyIL("MainClass.Test", @" { // Code size 25 (0x19) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""void ILeft.Goo()"" IL_0006: ldarg.0 IL_0007: callvirt ""void IBase.Goo()"" IL_000c: ldarg.0 IL_000d: callvirt ""void ILeft.Goo()"" IL_0012: ldarg.0 IL_0013: callvirt ""void IBase.Goo()"" IL_0018: ret }"); } [Fact] public void TestImplicitImplSignatureMismatches_ParamsAndOptionals() { // Tests: // Replace params with non-params in signature of implemented member (and vice-versa) // Replace optional parameter with non-optional parameter var source = @" using System; using System.Collections.Generic; interface I1<T> { void Method(int a, long b = 2, string c = null, params List<T>[] d); } interface I2 : I1<string> { void Method<T>(out int a, ref T[] b, List<T>[] c); } class Base { // Change default value of optional parameter public void Method(int a, long b = 3, string c = """", params List<string>[] d) { Console.WriteLine(""Base.Method({0}, {1}, {2})"", a, b, c); } } class Derived : Base, I1<string> // Implicit implementation in base { } class Class : I1<string> // Implicit implementation { // Replace optional with non-optional - OK public void Method(int a, long b, string c = """", params List<string>[] d) { Console.WriteLine(""Class.Method({0}, {1}, {2})"", a, b, c); } } class Class2 : I2 // Implicit implementation { // Replace non-optional with optional - OK // Omit params and replace with optional - OK public void Method(int a = 4, long b = 3, string c = """", List<string>[] d = null) { Console.WriteLine(""Class2.Method({0}, {1}, {2})"", a, b, c); } // Additional params - OK public void Method<U>(out int a, ref U[] b, params List<U>[] c) { a = 0; Console.WriteLine(""Class2.Method<U>({0}, {1})"", a, b[0]); } } class Test { public static void Main() { string[] s1 = new string[]{""a""}; List<string>[] l1 = new List<string>[]{}; I1<string> i1 = new Derived(); i1.Method(1, 2, ""b"", l1); i1 = new Class(); i1.Method(2, 3, ""c"", l1); I2 i2 = new Class2(); i2.Method(1, 2, ""b"", l1); int i = 1; i2.Method<string>(out i, ref s1, l1); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base.Method(1, 2, b) Class.Method(2, 3, c) Class2.Method(1, 2, b) Class2.Method<U>(0, a)", expectedSignatures: new[] { Signature("Base", "Method", ".method public hidebysig newslot virtual final instance System.Void Method(System.Int32 a, [opt] System.Int64 b = 3, [opt] System.String c = \"\", [System.ParamArrayAttribute()] System.Collections.Generic.List`1[System.String][] d) cil managed"), Signature("Class", "Method", ".method public hidebysig newslot virtual final instance System.Void Method(System.Int32 a, System.Int64 b, [opt] System.String c = \"\", [System.ParamArrayAttribute()] System.Collections.Generic.List`1[System.String][] d) cil managed"), Signature("Class2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method([opt] System.Int32 a = 4, [opt] System.Int64 b = 3, [opt] System.String c = \"\", [opt] System.Collections.Generic.List`1[System.String][] d) cil managed"), Signature("Class2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<U>([out] System.Int32& a, U[]& b, [System.ParamArrayAttribute()] System.Collections.Generic.List`1[U][] c) cil managed") }); } [Fact] public void ReImplementInterfaceInGrandChild() { var source = @" interface I1 { void bar(); } class C1 : I1 { void I1.bar() { System.Console.Write(""C1"");} } class C2 : C1 { } class C3 : C2, I1 { public void bar() { System.Console.Write(""C3""); } } static class Program { static void Main() { C3 c3 = new C3(); C2 c2 = c3; C1 c1 = c3; c3.bar(); ((I1)c3).bar(); ((I1)c2).bar(); ((I1)c1).bar(); } } "; CompileAndVerify(source, expectedOutput: "C3C3C3C3"); } [Fact] public void OverrideBaseClassImplementation() { var source = @" interface I1 { void Bar(); } abstract class C1 : I1 { abstract public void Bar(); } class C2 : C1 { public override void Bar() { System.Console.Write(""C2""); } } class C3 : C2 { public override void Bar() { System.Console.Write(""C3""); } } static class Program { static void Main() { I1 i = new C3(); i.Bar(); } } "; CompileAndVerify(source, expectedOutput: "C3"); } [Fact] public void TestImplementingWithVirtualMembers() { // Tests: // Implement interface member with virtual / abstract / override member // Test that appropriate (derived) member is called when invoking through interface var source = @" using System; using System.Collections.Generic; interface I1 { int Property { get; set; } void Method<T>(int a, T[] b, List<T> c); void Method(int a, System.Exception[] b); void Method(); } class Base1 { public virtual void Method() { Console.WriteLine(""Base1.Method()""); } } abstract class Class1 : Base1, I1 // Implementing with abstract / virtual / override members from current type { public abstract void Method(int b, System.Exception[] c); public abstract int Property { get; set; } public virtual void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Class1.Method<U>({0}, {1})"", i, j[0]); } public override void Method() { Console.WriteLine(""Class1.Method()""); } } class Class2 : Class1 { public override void Method(int i, System.Exception[] c) { System.Console.WriteLine(""Class2.Method({0})"", i); } public override int Property { get { System.Console.WriteLine(""Class2.Property.get()""); return 1; } set { System.Console.WriteLine(""Class2.Property.set({0})"", value); } } } abstract class Base2 : Base1 { public abstract void Method(int b, System.Exception[] c); public abstract int Property { get; set; } public virtual void Method<U>(int i, U[] j, List<U> k) { Console.WriteLine(""Base2.Method<U>({0}, {1})"", i, j[0]); } public override void Method() { Console.WriteLine(""Base2.Method()""); } } abstract class Derived : Base2, I1 // Implementing with abstract / virtual / override members from base type { public override int Property { set { System.Console.WriteLine(""Derived.Property.set()""); } } } class Derived2 : Derived, I1 { public override void Method(int i, System.Exception[] c) { System.Console.WriteLine(""Derived2.Method({0})"", i); } public override void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Derived2.Method<U>({0}, {1})"", i, j[0]); } public override int Property { get { System.Console.WriteLine(""Derived2.Property.get()""); return 1; } } } class Derived3 : Derived2, I1 { public override int Property { set { System.Console.WriteLine(""Derived3.Property.set({0})"", value); } } int I1.Property { get { System.Console.WriteLine(""Derived3.I1.Property.get()""); return 1; } set { System.Console.WriteLine(""Derived3.I1.Property.set({0})"", value); } } } class Derived4 : Derived3 { public override int Property { get { System.Console.WriteLine(""Derived4.Property.get()""); return 1; } set { System.Console.WriteLine(""Derived4.Property.set({0})"", value); } } public override void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Derived4.Method<U>({0}, {1})"", i, j[0]); } } class Test { public static void Main() { I1 i = new Derived4(); int x = 0; i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 0 }, new List<int>()); x = i.Property; i.Property = x; i = new Derived3(); i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 1 }, new List<int>()); x = i.Property; i.Property = x; i = new Derived2(); i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 2 }, new List<int>()); x = i.Property; i.Property = x; i = new Class2(); i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 3 }, new List<int>()); x = i.Property; i.Property = x; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base2.Method() Derived2.Method(1) Derived4.Method<U>(1, 0) Derived3.I1.Property.get() Derived3.I1.Property.set(1) Base2.Method() Derived2.Method(1) Derived2.Method<U>(1, 1) Derived3.I1.Property.get() Derived3.I1.Property.set(1) Base2.Method() Derived2.Method(1) Derived2.Method<U>(1, 2) Derived2.Property.get() Derived.Property.set() Class1.Method() Class2.Method(1) Class1.Method<U>(1, 3) Class2.Property.get() Class2.Property.set(1)"); } [Fact] public void TestImplementingWithSpecialVirtualMembers() { // Tests: // Implement interface member with abstract override / sealed / new member // Test that appropriate (derived) member is called when invoking through interface var source = @" using System; using System.Collections.Generic; interface I1 { int Property { set; } void Method<T>(int a, T[] b, List<T> c); void Method(int a, System.Exception[] b); void Method(); } abstract class Base1 { public virtual void Method() { Console.WriteLine(""Base1.Method()""); } public abstract void Method(int b, System.Exception[] c); public virtual void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Base1.Method<U>({0}, {1})"", i, j[0]); } public virtual int Property { get { System.Console.WriteLine(""Base1.Property.get()""); return 1; } set { System.Console.WriteLine(""Base1.Property.set({0})"", value); } } } abstract class Class1 : Base1, I1 // Implementing with abstract override / sealed override / new members from current type { public abstract override void Method(); public sealed override void Method(int i, System.Exception[] c) { System.Console.WriteLine(""Class1.Method({0})"", i); } public new int Property { get { System.Console.WriteLine(""Class1.Property.get()""); return 1; } set { System.Console.WriteLine(""Class1.Property.set({0})"", value); } } } class Class2 : Class1 { public override void Method() { Console.WriteLine(""Class2.Method()""); } } abstract class Base2 : Base1 { public abstract override void Method(); public new virtual void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Base2.Method<U>({0}, {1})"", i, j[0]); } public sealed override int Property { get { System.Console.WriteLine(""Base2.Property.get()""); return 1; } // Synthesized setter implements interface } } abstract class Derived : Base2, I1 // Implementing with abstract override / sealed override / new members from base type { } class Derived2 : Derived { public sealed override void Method(int i, System.Exception[] c) { System.Console.WriteLine(""Derived2.Method({0})"", i); } public new void Method<U>(int i, U[] j, List<U> k) { System.Console.WriteLine(""Derived2.Method<U>({0}, {1})"", i, j[0]); } public override void Method() { Console.WriteLine(""Derived2.Method()""); } } class Test { public static void Main() { I1 i = new Derived2(); int x = 0; i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 0 }, new List<int>()); i.Property = x; i = new Class2(); i.Method(); i.Method(1, new Exception[] { }); i.Method<int>(1, new int[] { 3 }, new List<int>()); i.Property = x; } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived2.Method() Derived2.Method(1) Base2.Method<U>(1, 0) Base1.Property.set(0) Class2.Method() Class1.Method(1) Base1.Method<U>(1, 3) Class1.Property.set(0)"); } [Fact] public void TestImplementingGenericNestedInterfaces_Implicit() { // Tests: // Sanity check – use open (T) and closed (C<String>) generic types in the signature of implemented methods // Implement members of generic interface nested inside other generic classes var source = @" using System; using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<K>(T a, U[] b, List<V> c, Dictionary<W, K> d); } internal class Base<X, Y> { public X Property { set { Console.WriteLine(""Derived1.set_Property""); } } public void Method<V>(X A, int[] b, List<long> C, Dictionary<Y, V> d) { Console.WriteLine(""Derived1.Method""); } } } } internal class Derived1<U, T> : Outer<U>.Inner<T>.Base<U, T>, Outer<U>.Inner<int>.Interface<long, T> { public class Derived2 : Outer<string>.Inner<int>.Interface<long, string> { public string Property { get { return null; } set { Console.WriteLine(""Derived2.set_Property""); } } public void Method<Z>(string A, int[] B, List<long> C, Dictionary<string, Z> D) { Console.WriteLine(""Derived2.Method""); } } } public class Test { public static void Main() { Outer<string>.Inner<int>.Interface<long, string> i = new Derived1<string, string>(); i.Property = """"; i.Method<string>("""", new int[]{}, new List<long>(), new Dictionary<string,string>()); i = new Derived1<string, string>.Derived2(); i.Property = """"; i.Method<string>("""", new int[] { }, new List<long>(), new Dictionary<string, string>()); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived1.set_Property Derived1.Method Derived2.set_Property Derived2.Method", expectedSignatures: new[] { Signature("Outer`1+Inner`1+Base`2", "set_Property", ".method public hidebysig newslot specialname virtual final instance System.Void set_Property(X value) cil managed"), Signature("Outer`1+Inner`1+Base`2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<V>(X A, System.Int32[] b, System.Collections.Generic.List`1[System.Int64] C, System.Collections.Generic.Dictionary`2[Y,V] d) cil managed"), Signature("Derived1`2+Derived2", "get_Property", ".method public hidebysig specialname instance System.String get_Property() cil managed"), Signature("Derived1`2+Derived2", "set_Property", ".method public hidebysig newslot specialname virtual final instance System.Void set_Property(System.String value) cil managed"), Signature("Derived1`2+Derived2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<Z>(System.String A, System.Int32[] B, System.Collections.Generic.List`1[System.Int64] C, System.Collections.Generic.Dictionary`2[System.String,Z] D) cil managed"), }); comp.VerifyDiagnostics(); } [Fact] public void TestImplementingGenericNestedInterfaces_Implicit_HideTypeParameter() { // Tests: // Implicitly implement generic methods on generic interfaces – test case where type parameter // on method hides the type parameter on class (both in interface and in implementing type) var source = @" using System; using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); void Method<V, W>(T a, U[] b, List<V> c, Dictionary<W, W> d); } internal class Derived1<X, Y> : Outer<long>.Inner<int>.Interface<long, Y> { public void Method<X>(long A, int[] b, List<long> C, Dictionary<Y, X> d) { Console.WriteLine(""Derived1.Method`1""); } public void Method<X, Y>(long A, int[] b, List<X> C, Dictionary<Y, Y> d) { Console.WriteLine(""Derived1.Method`2""); } } } } class Test { public static void Main() { Outer<long>.Inner<int>.Interface<long, string> i = new Outer<long>.Inner<int>.Derived1<string, string>(); i.Method<string>(1, new int[]{}, new List<long>(), new Dictionary<string, string>()); i.Method<string, int>(1, new int[]{}, new List<string>(), new Dictionary<int, int>()); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived1.Method`1 Derived1.Method`2", expectedSignatures: new[] { Signature("Outer`1+Inner`1+Derived1`2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<X>(System.Int64 A, System.Int32[] b, System.Collections.Generic.List`1[System.Int64] C, System.Collections.Generic.Dictionary`2[Y,X] d) cil managed"), Signature("Outer`1+Inner`1+Derived1`2", "Method", ".method public hidebysig newslot virtual final instance System.Void Method<X, Y>(System.Int64 A, System.Int32[] b, System.Collections.Generic.List`1[X] C, System.Collections.Generic.Dictionary`2[Y,Y] d) cil managed") }); comp.VerifyDiagnostics( // (11,25): warning CS0693: Type parameter 'V' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "V").WithArguments("V", "Outer<T>.Inner<U>.Interface<V, W>"), // (11,28): warning CS0693: Type parameter 'W' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Interface<V, W>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "W").WithArguments("W", "Outer<T>.Inner<U>.Interface<V, W>"), // (15,32): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (19,32): warning CS0693: Type parameter 'X' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "X").WithArguments("X", "Outer<T>.Inner<U>.Derived1<X, Y>"), // (19,35): warning CS0693: Type parameter 'Y' has the same name as the type parameter from outer type 'Outer<T>.Inner<U>.Derived1<X, Y>' Diagnostic(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, "Y").WithArguments("Y", "Outer<T>.Inner<U>.Derived1<X, Y>")); } [Fact] public void TestImplementationInBaseGenericType() { // Tests: // Implicitly implement interface member in base generic type – the method that implements interface member // should depend on type parameter of base type to satisfy signature (return type / parameter type) equality // Also test variation of above case where implementing member in base generic type does not depend // on any type parameters var source = @" using System; interface Interface { void Method(int x); void Method(); } class Base<T> { public void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Base2<T> : Base<T> { public void Method() { Console.WriteLine(""Base.Method()""); } } class Derived : Base2<int>, Interface { } class Test { public static void Main() { Interface i = new Derived(); i.Method(1); i.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Base.Method(T) Base.Method()"); comp.VerifyDiagnostics(); // No errors } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType2() { // Tests: // Implement I<string> implicitly in base class and I<int> implicitly in derived class – // assuming I<string> and I<int> have members with same signature (i.e. members // that don't depend on generic-ness of the interface) test which (base / derived class) // members are invoked when calling through each interface var source = @" using System; interface Interface<T> { void Method(T x); void Method(); } class Base<T> : Interface<T> { public void Method() { Console.WriteLine(""Base.Method()""); } public void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Derived<U, V> : Base<int>, Interface<U> { new public void Method() { Console.WriteLine(""Derived`2.Method()""); } public new void Method(int x) { Console.WriteLine(""Derived`2.Method(int)""); } public void Method(U x) { Console.WriteLine(""Derived`2.Method(U)""); } public void Method(V x) { Console.WriteLine(""Derived`2.Method(V)""); } } class Derived : Derived<int, string>, Interface<string> { new public void Method() { Console.WriteLine(""Derived.Method()""); } public new void Method(string x) { Console.WriteLine(""Derived.Method(string)""); } } class Test { public static void Main() { Interface<string> i = new Derived<string, int>(); i.Method(""""); i.Method(); Interface<int> j = new Derived<string, int>(); j.Method(1); j.Method(); i = new Derived(); i.Method(""""); i.Method(); j = new Derived(); j.Method(1); j.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived`2.Method(U) Derived`2.Method() Base.Method(T) Base.Method() Derived.Method(string) Derived.Method() Derived`2.Method(U) Derived`2.Method()"); comp.VerifyDiagnostics(); // No errors } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType3() { // Tests: // Variation of TestImplicitImplementationInBaseGenericType2 with overriding var source = @" using System; interface Interface<T> { void Method(T x); void Method(); } class Base<T> : Interface<T> { public virtual void Method() { Console.WriteLine(""Base.Method()""); } public virtual void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Derived<U, V> : Base<int>, Interface<U> { public override void Method() { Console.WriteLine(""Derived`2.Method()""); } public override void Method(int x) { Console.WriteLine(""Derived`2.Method(int)""); } public virtual void Method(U x) { Console.WriteLine(""Derived`2.Method(U)""); } public virtual void Method(V x) { Console.WriteLine(""Derived`2.Method(V)""); } } class Derived : Derived<int, string>, Interface<string> { public override void Method() { Console.WriteLine(""Derived.Method()""); } public override void Method(string x) { Console.WriteLine(""Derived.Method(string)""); } } class Test { public static void Main() { Interface<string> i = new Derived<string, int>(); i.Method(""""); i.Method(); Interface<int> j = new Derived<string, int>(); j.Method(1); j.Method(); i = new Derived(); i.Method(""""); i.Method(); j = new Derived(); j.Method(1); j.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived`2.Method(U) Derived`2.Method() Derived`2.Method(int) Derived`2.Method() Derived.Method(string) Derived.Method() Derived`2.Method(U) Derived.Method()"); comp.VerifyDiagnostics(); // No errors } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType4() { // Tests: // Variation of TestImplicitImplementationInBaseGenericType2 with re-implementation var source = @" using System; interface Interface<T> { void Method(T x); void Method(); } class Base<T> : Interface<T> { public void Method() { Console.WriteLine(""Base.Method()""); } public void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Derived<U, V> : Base<int>, Interface<U> { new public void Method() { Console.WriteLine(""Derived`2.Method()""); } public new void Method(int x) { Console.WriteLine(""Derived`2.Method(int)""); } public void Method(U x) { Console.WriteLine(""Derived`2.Method(U)""); } public void Method(V x) { Console.WriteLine(""Derived`2.Method(V)""); } } class Derived : Derived<int, string>, Interface<string>, Interface<int> { new public void Method() { Console.WriteLine(""Derived.Method()""); } public new void Method(string x) { Console.WriteLine(""Derived.Method(string)""); } } class Test { public static void Main() { Interface<string> i = new Derived<string, int>(); i.Method(""""); i.Method(); Interface<int> j = new Derived<string, int>(); j.Method(1); j.Method(); i = new Derived(); i.Method(""""); i.Method(); j = new Derived(); j.Method(1); j.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived`2.Method(U) Derived`2.Method() Base.Method(T) Base.Method() Derived.Method(string) Derived.Method() Derived`2.Method(U) Derived.Method()"); comp.VerifyDiagnostics( // (20,58): warning CS1956: Member 'Derived<int, string>.Method(int)' implements interface member 'Interface<int>.Method(int)' in type 'Derived'. There are multiple matches for the interface member at run-time. It is implementation dependent which method will be called. // class Derived : Derived<int, string>, Interface<string>, Interface<int> Diagnostic(ErrorCode.WRN_MultipleRuntimeImplementationMatches, "Interface<int>").WithArguments("Derived<int, string>.Method(int)", "Interface<int>.Method(int)", "Derived").WithLocation(20, 58)); // No errors } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10837")] public void TestImplicitImplementationInBaseGenericType5() { // Tests: // Variation of TestImplicitImplementationInBaseGenericType3 with re-implementation var source = @" using System; interface Interface<T> { void Method(T x); void Method(); } class Base<T> : Interface<T> { public virtual void Method() { Console.WriteLine(""Base.Method()""); } public virtual void Method(T x) { Console.WriteLine(""Base.Method(T)""); } } class Derived<U, V> : Base<int>, Interface<U> { public override void Method() { Console.WriteLine(""Derived`2.Method()""); } public virtual void Method(U x) { Console.WriteLine(""Derived`2.Method(U)""); } public virtual void Method(V x) { Console.WriteLine(""Derived`2.Method(V)""); } } class Derived : Derived<int, string>, Interface<string>, Interface<int> { public override void Method() { Console.WriteLine(""Derived.Method()""); } public override void Method(string x) { Console.WriteLine(""Derived.Method(string)""); } public override void Method(int x) { Console.WriteLine(""Derived.Method(int)""); } } class Test { public static void Main() { Interface<string> i = new Derived<string, int>(); i.Method(""""); i.Method(); Interface<int> j = new Derived<string, int>(); j.Method(1); j.Method(); i = new Derived(); i.Method(""""); i.Method(); j = new Derived(); j.Method(1); j.Method(); } }"; var comp = CompileAndVerify(source, expectedOutput: @" Derived`2.Method(U) Derived`2.Method() Base.Method(T) Derived`2.Method() Derived.Method(string) Derived.Method() Derived.Method(int) Derived.Method()"); comp.VerifyDiagnostics(); // No errors } [Fact] public void ImplementInterfaceUsingSynthesizedSealedProperty() { // Tests: // Implicitly implement a property / indexer with a sealed property / indexer in base class – // test case where only one accessor is implemented by this sealed property / indexer in base class var text = @" using System; interface I1 { int Bar { get; } } class C1 { public virtual int Bar { get { return 23123;} set { }} } class C2 : C1, I1 { sealed public override int Bar { set { } } // Getter will be synthesized by compiler } class Test { public static void Main() { I1 i = new C2(); Console.WriteLine(i.Bar); } } "; // TODO: Will need to update once CompilerGeneratedAttribute is emitted on synthesized accessor var comp = CompileAndVerify(text, expectedOutput: "23123", expectedSignatures: new[] { Signature("C2", "get_Bar", ".method public hidebysig specialname virtual final instance System.Int32 get_Bar() cil managed"), Signature("C2", "set_Bar", ".method public hidebysig specialname virtual final instance System.Void set_Bar(System.Int32 value) cil managed") }); } [Fact] public void TestImplementAmbiguousSignaturesImplicitly() { var source = @" using System; interface I1 { int P { set; } void M1(long x); void M2(long x); void M3(long x); void M4(ref long x); void M5(out long x); void M6(ref long x); void M7(out long x); void M8(params long[] x); void M9(long[] x); } interface I2 : I1 { } interface I3 : I2 { new long P { set; } new int M1(long x); // Return type void M2(ref long x); // Add ref void M3(out long x); // Add out void M4(long x); // Omit ref void M5(long x); // Omit out void M6(out long x); // Toggle ref to out void M7(ref long x); // Toggle out to ref new void M8(long[] x); // Omit params new void M9(params long[] x); // Add params } class Test : I3 { int I1.P { set { Console.WriteLine(""I1.P""); } } // Not possible to implement both I3.P and I1.P implicitly public long P { get { return 0; } set { Console.WriteLine(""I3.P""); } } public void M1(long x) { Console.WriteLine(""I1.M1""); } // Not possible to implement both I3.M1 and I1.M1 implicitly int I3.M1(long x) { Console.WriteLine(""I3.M1""); return 0; } public void M2(ref long x) { Console.WriteLine(""I3.M2""); } public void M2(long x) { Console.WriteLine(""I1.M2""); } public void M3(long x) { Console.WriteLine(""I1.M3""); } public void M3(out long x) { x = 0; Console.WriteLine(""I3.M3""); } public void M4(long x) { Console.WriteLine(""I3.M4""); } public void M4(ref long x) { Console.WriteLine(""I1.M4""); } public void M5(out long x) { x = 0; Console.WriteLine(""I3.M5""); } public void M5(long x) { Console.WriteLine(""I1.M5""); } void I1.M6(ref long x) { x = 0; Console.WriteLine(""I1.M6""); } // Not possible to implement both I3.M6 and I1.M6 implicitly public void M6(out long x) { x = 0; Console.WriteLine(""I3.M6""); } void I3.M7(ref long x) { Console.WriteLine(""I3.M7""); } public void M7(out long x) { x = 0; Console.WriteLine(""I1.M7""); } // Not possible to implement both I3.M7 and I1.M7 implicitly public void M8(long[] x) { Console.WriteLine(""I3.M8+I1.M8""); } // Implements both I3.M8 and I1.M8 public void M9(params long[] x) { Console.WriteLine(""I3.M9+I1.M9""); } // Implements both I3.M9 and I1.M9 public static void Main() { I3 i = new Test(); long x = 1; i.M1(x); i.M2(x); i.M2(ref x); i.M3(x); i.M3(out x); i.M4(x); i.M4(ref x); i.M5(x); i.M5(out x); i.M6(out x); i.M6(ref x); i.M7(ref x); i.M7(out x); i.M8(new long[] { x, x, x }); i.M8(x, x, x); i.M9(new long[] { x, x, x }); i.M9(x, x, x); i.P = 1; I1 j = i; j.M1(x); j.M2(x); j.M3(x); j.M4(ref x); j.M5(out x); j.M6(ref x); j.M7(out x); j.M8(new long[] { x, x, x }); j.M8(x, x, x); j.M9(new long[] { x, x, x }); j.P = 1; } }"; CompileAndVerify(source, expectedOutput: @" I3.M1 I1.M2 I3.M2 I1.M3 I3.M3 I3.M4 I1.M4 I1.M5 I3.M5 I3.M6 I1.M6 I3.M7 I1.M7 I3.M8+I1.M8 I3.M8+I1.M8 I3.M9+I1.M9 I3.M9+I1.M9 I3.P I1.M1 I1.M2 I1.M3 I1.M4 I3.M5 I1.M6 I1.M7 I3.M8+I1.M8 I3.M8+I1.M8 I3.M9+I1.M9 I1.P").VerifyDiagnostics(); // No errors } [Fact] public void TestImplementAmbiguousSignaturesImplicitlyInBase() { var source = @" using System; interface I1 { int P { set; } void M1(long x); void M2(long x); void M3(long x); void M4(ref long x); void M5(out long x); void M6(ref long x); void M7(out long x); void M8(params long[] x); void M9(long[] x); } interface I2 : I1 { } interface I3 : I2 { new long P { set; } new int M1(long x); // Return type void M2(ref long x); // Add ref void M3(out long x); // Add out void M4(long x); // Omit ref void M5(long x); // Omit out void M6(out long x); // Toggle ref to out void M7(ref long x); // Toggle out to ref new void M8(long[] x); // Omit params new void M9(params long[] x); // Add params } class Base { public long P { get { return 0; } set { Console.WriteLine(""I3.P""); } } public void M1(long x) { Console.WriteLine(""I1.M1""); } public void M2(ref long x) { Console.WriteLine(""I3.M2""); } public void M2(long x) { Console.WriteLine(""I1.M2""); } public void M3(long x) { Console.WriteLine(""I1.M3""); } public void M3(out long x) { x = 0; Console.WriteLine(""I3.M3""); } public void M4(long x) { Console.WriteLine(""I3.M4""); } public void M4(ref long x) { Console.WriteLine(""I1.M4""); } public void M5(out long x) { x = 0; Console.WriteLine(""I3.M5""); } public void M5(long x) { Console.WriteLine(""I1.M5""); } public void M6(out long x) { x = 0; Console.WriteLine(""I3.M6""); } public void M7(out long x) { x = 0; Console.WriteLine(""I1.M7""); } public void M8(long[] x) { Console.WriteLine(""Base:I3.M8+I1.M8""); } public void M9(params long[] x) { Console.WriteLine(""Base:I3.M9+I1.M9""); } } class Test : Base, I3 { int I1.P { set { Console.WriteLine(""I1.P""); } } // Not possible to implement both I3.P and I1.P implicitly int I3.M1(long x) { Console.WriteLine(""I3.M1""); return 0; } // Not possible to implement both I3.M1 and I1.M1 implicitly public void M6(ref long x) { x = 0; Console.WriteLine(""I1.M6""); } // Not possible to implement both I3.M6 and I1.M6 implicitly in same class public void M7(ref long x) { Console.WriteLine(""I3.M7""); } // Not possible to implement both I3.M7 and I1.M7 implicitly in same class public void M8(params long[] x) { Console.WriteLine(""Derived:I3.M8+I1.M8""); } // Implements both I3.M8 and I1.M8 public void M9(long[] x) { Console.WriteLine(""Derived:I3.M9+I1.M9""); } // Implements both I3.M9 and I1.M9 public static void Main() { I3 i = new Test(); long x = 1; i.M1(x); i.M2(x); i.M2(ref x); i.M3(x); i.M3(out x); i.M4(x); i.M4(ref x); i.M5(x); i.M5(out x); i.M6(out x); i.M6(ref x); i.M7(ref x); i.M7(out x); i.M8(new long[] { x, x, x }); i.M8(x, x, x); i.M9(new long[] { x, x, x }); i.M9(x, x, x); i.P = 1; I1 j = i; j.M1(x); j.M2(x); j.M3(x); j.M4(ref x); j.M5(out x); j.M6(ref x); j.M7(out x); j.M8(new long[] { x, x, x }); j.M8(x, x, x); j.M9(new long[] { x, x, x }); j.P = 1; } }"; var comp = CompileAndVerify(source, expectedOutput: @" I3.M1 I1.M2 I3.M2 I1.M3 I3.M3 I3.M4 I1.M4 I1.M5 I3.M5 I1.M6 I1.M6 I3.M7 I3.M7 Derived:I3.M8+I1.M8 Derived:I3.M8+I1.M8 Derived:I3.M9+I1.M9 Derived:I3.M9+I1.M9 I3.P I1.M1 I1.M2 I1.M3 I1.M4 I3.M5 I1.M6 I3.M7 Derived:I3.M8+I1.M8 Derived:I3.M8+I1.M8 Derived:I3.M9+I1.M9 I1.P"); comp.VerifyDiagnostics( // (55,17): warning CS0108: 'Test.M8(params long[])' hides inherited member 'Base.M8(long[])'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M8").WithArguments("Test.M8(params long[])", "Base.M8(long[])"), // (56,17): warning CS0108: 'Test.M9(long[])' hides inherited member 'Base.M9(params long[])'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M9").WithArguments("Test.M9(long[])", "Base.M9(params long[])")); } [Fact] public void TestImplementingWithObjectMembers() { var source = @" using System; interface I { string ToString(); int GetHashCode(); } class C : I { } class Base { public override string ToString() { return ""Base.ToString""; } } class Derived : Base, I { } class Test { public static void Main() { I i = new C(); i = new Derived(); Console.WriteLine(i.ToString()); } }"; CompileAndVerify(source, expectedOutput: "Base.ToString").VerifyDiagnostics(); // No errors } [Fact] public void TestImplementHiddenMemberImplicitly() { var source = @" using System; interface I1 { void Method(int i); int P { set; } } interface I2 : I1 { new void Method(int i); new int P { set; } } class B { public int P { set { Console.WriteLine(""B.set_Property""); } } } class C : B, I2 { public void Method(int j) { Console.WriteLine(""C.Method""); } } class Test { public static void Main() { I2 i = new C(); I1 j = i; i.Method(1); i.P = 0; j.Method(1); j.P = 0; } }"; CompileAndVerify(source, expectedOutput: @" C.Method B.set_Property C.Method B.set_Property").VerifyDiagnostics(); // No errors } [Fact] public void TestImplementHiddenMemberImplicitly2() { var source = @" using System; interface I1 { void Method(int i); long P { set; } } interface I2 : I1 { new int Method(int i); new int P { set; } } class B { public int P { set { Console.WriteLine(""B.set_Property""); } } public int Method(int j) { Console.WriteLine(""B.Method""); return 0; } } class C : B, I2 { public new long P { set { Console.WriteLine(""C.set_Property""); } } public new void Method(int j) { Console.WriteLine(""C.Method""); } } class Test { public static void Main() { I2 i = new C(); I1 j = i; i.Method(1); i.P = 0; j.Method(1); j.P = 0; } }"; CompileAndVerify(source, expectedOutput: @" B.Method B.set_Property C.Method C.set_Property").VerifyDiagnostics(); // No errors } [Fact] public void TestImplicitImplementationWithHidingAcrossBaseTypes() { var source = @"using System; interface I { void Method(int i); long P { set; } } class B1 { public void Method(int j) { Console.WriteLine(""B1.Method""); } public int P { get { return 0; } set { Console.WriteLine(""B1.set_Property""); } } } class B2 : B1 { } class B3 : B2 { public new void Method(int j) { Console.WriteLine(""B3.Method""); } public new long P { set { Console.WriteLine(""B3.set_Property""); } } } class B4 : B3 { } class D : B4, I { public new int Method(int j) { Console.WriteLine(""D.Method""); return 0; } public new long P { get { return 0; } set { Console.WriteLine(""D.set_Property""); } } } class Test { public static void Main() { I i = new D(); i.Method(1); i.P = 0; } }"; CompileAndVerify(source, expectedOutput: @" B3.Method D.set_Property").VerifyDiagnostics(); // No errors } [Fact] public void TestImplicitImplementationAcrossBaseTypes() { var source = @"using System; interface I { void Method(int i); long P { set; } void M(); } class B1 { public void Method(int j) { Console.WriteLine(""B1.Method""); } public long P { get { return 0; } set { Console.WriteLine(""B1.set_Property""); } } } class B2 : B1 { protected new void Method(int j) { Console.WriteLine(""B2.Method""); } // non-public members should be ignored public void M() { Console.WriteLine(""B2.M""); } } class B3 : B2 { internal new void Method(int j) { Console.WriteLine(""B3.Method""); } // non-public members should be ignored } class D : B3, I { public static new long P { set { Console.WriteLine(""D.set_Property""); } } // static members should be ignored public new void M() { Console.WriteLine(""D.M""); } // should pick the member in most derived class } class Test { public static void Main() { I i = new D(); i.Method(1); i.P = 0; i.M(); } }"; CompileAndVerify(source, expectedOutput: @" B1.Method B1.set_Property D.M").VerifyDiagnostics(); // No errors } /// <summary> /// Compile libSource into a dll and then compile exeSource with that DLL as a reference. /// Assert that neither compilation has errors. Return the exe compilation. /// </summary> private static CSharpCompilation CreateCompilationWithMscorlibAndReference(string libSource, string exeSource) { var libComp = CreateCompilation(libSource, options: TestOptions.ReleaseDll, assemblyName: "OtherAssembly"); libComp.VerifyDiagnostics(); var exeComp = CreateCompilation(exeSource, options: TestOptions.ReleaseExe, references: new[] { new CSharpCompilationReference(libComp) }); exeComp.VerifyDiagnostics(); return exeComp; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/ExternalAccess/Razor/Api/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Api { internal static class Extensions { private const string RazorCSharp = "RazorCSharp"; public static bool IsRazorDocument(this Document document) { var documentPropertiesService = document.Services.GetService<DocumentPropertiesService>(); if (documentPropertiesService != null && documentPropertiesService.DiagnosticsLspClientName == RazorCSharp) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor.Api { internal static class Extensions { private const string RazorCSharp = "RazorCSharp"; public static bool IsRazorDocument(this Document document) { var documentPropertiesService = document.Services.GetService<DocumentPropertiesService>(); if (documentPropertiesService != null && documentPropertiesService.DiagnosticsLspClientName == RazorCSharp) { return true; } return false; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_OptionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionOrUserDiagnosticTest { internal static (OptionKey2, object?) SingleOption<T>(Option2<T> option, T enabled) => (new OptionKey2(option), enabled); internal (OptionKey2, object?) SingleOption<T>(PerLanguageOption2<T> option, T value) => (new OptionKey2(option, this.GetLanguage()), value); internal static (OptionKey2, object) SingleOption<T>(Option2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => (new OptionKey2(option), new CodeStyleOption2<T>(enabled, notification)); internal static (OptionKey2, object) SingleOption<T>(Option2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => (new OptionKey2(option), codeStyle); internal (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => (new OptionKey2(option, this.GetLanguage()), new CodeStyleOption2<T>(enabled, notification)); internal (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => (new OptionKey2(option, this.GetLanguage()), codeStyle); internal static (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle, string language) => (new OptionKey2(option, language), codeStyle); internal OptionsCollection Option<T>(Option2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => new OptionsCollection(GetLanguage()) { { option, enabled, notification } }; internal OptionsCollection Option<T>(Option2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => new OptionsCollection(GetLanguage()) { { option, codeStyle } }; internal OptionsCollection Option<T>(PerLanguageOption2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => new OptionsCollection(GetLanguage()) { { option, enabled, notification } }; internal OptionsCollection Option<T>(Option2<T> option, T value) => new OptionsCollection(GetLanguage()) { { option, value } }; internal OptionsCollection Option<T>(PerLanguageOption2<T> option, T value) => new OptionsCollection(GetLanguage()) { { option, value } }; internal OptionsCollection Option<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => new OptionsCollection(GetLanguage()) { { option, codeStyle } }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeStyle; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionOrUserDiagnosticTest { internal static (OptionKey2, object?) SingleOption<T>(Option2<T> option, T enabled) => (new OptionKey2(option), enabled); internal (OptionKey2, object?) SingleOption<T>(PerLanguageOption2<T> option, T value) => (new OptionKey2(option, this.GetLanguage()), value); internal static (OptionKey2, object) SingleOption<T>(Option2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => (new OptionKey2(option), new CodeStyleOption2<T>(enabled, notification)); internal static (OptionKey2, object) SingleOption<T>(Option2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => (new OptionKey2(option), codeStyle); internal (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => (new OptionKey2(option, this.GetLanguage()), new CodeStyleOption2<T>(enabled, notification)); internal (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => (new OptionKey2(option, this.GetLanguage()), codeStyle); internal static (OptionKey2, object) SingleOption<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle, string language) => (new OptionKey2(option, language), codeStyle); internal OptionsCollection Option<T>(Option2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => new OptionsCollection(GetLanguage()) { { option, enabled, notification } }; internal OptionsCollection Option<T>(Option2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => new OptionsCollection(GetLanguage()) { { option, codeStyle } }; internal OptionsCollection Option<T>(PerLanguageOption2<CodeStyleOption2<T>> option, T enabled, NotificationOption2 notification) => new OptionsCollection(GetLanguage()) { { option, enabled, notification } }; internal OptionsCollection Option<T>(Option2<T> option, T value) => new OptionsCollection(GetLanguage()) { { option, value } }; internal OptionsCollection Option<T>(PerLanguageOption2<T> option, T value) => new OptionsCollection(GetLanguage()) { { option, value } }; internal OptionsCollection Option<T>(PerLanguageOption2<CodeStyleOption2<T>> option, CodeStyleOption2<T> codeStyle) => new OptionsCollection(GetLanguage()) { { option, codeStyle } }; } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Analyzers/Core/CodeFixes/UseCompoundAssignment/AbstractUseCompoundAssignmentCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.UseCompoundAssignment { internal abstract class AbstractUseCompoundAssignmentCodeFixProvider< TSyntaxKind, TAssignmentSyntax, TExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TSyntaxKind : struct where TAssignmentSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseCompoundAssignmentDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; // See comments in the analyzer for what these maps are for. private readonly ImmutableDictionary<TSyntaxKind, TSyntaxKind> _binaryToAssignmentMap; private readonly ImmutableDictionary<TSyntaxKind, TSyntaxKind> _assignmentToTokenMap; protected AbstractUseCompoundAssignmentCodeFixProvider( ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds) { UseCompoundAssignmentUtilities.GenerateMaps(kinds, out _binaryToAssignmentMap, out _assignmentToTokenMap); } protected abstract SyntaxToken Token(TSyntaxKind kind); protected abstract TAssignmentSyntax Assignment( TSyntaxKind assignmentOpKind, TExpressionSyntax left, SyntaxToken syntaxToken, TExpressionSyntax right); protected abstract TExpressionSyntax Increment(TExpressionSyntax left, bool postfix); protected abstract TExpressionSyntax Decrement(TExpressionSyntax left, bool postfix); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics[0]; context.RegisterCodeFix(new MyCodeAction( c => FixAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = syntaxFacts.SyntaxKinds; foreach (var diagnostic in diagnostics) { var assignment = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); editor.ReplaceNode(assignment, (current, generator) => { if (current is not TAssignmentSyntax currentAssignment) return current; syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(currentAssignment, out var leftOfAssign, out var equalsToken, out var rightOfAssign); while (syntaxFacts.IsParenthesizedExpression(rightOfAssign)) rightOfAssign = syntaxFacts.Unparenthesize(rightOfAssign); syntaxFacts.GetPartsOfBinaryExpression(rightOfAssign, out _, out var opToken, out var rightExpr); if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Increment)) return Increment((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment); if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Decrement)) return Decrement((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment); var assignmentOpKind = _binaryToAssignmentMap[syntaxKinds.Convert<TSyntaxKind>(rightOfAssign.RawKind)]; var compoundOperator = Token(_assignmentToTokenMap[assignmentOpKind]); return Assignment( assignmentOpKind, (TExpressionSyntax)leftOfAssign, compoundOperator.WithTriviaFrom(equalsToken), (TExpressionSyntax)rightExpr); }); } return Task.CompletedTask; } protected virtual bool PreferPostfix(ISyntaxFactsService syntaxFacts, TAssignmentSyntax currentAssignment) { // If we have `x = x + 1;` on it's own, then we prefer `x++` as idiomatic. if (syntaxFacts.IsSimpleAssignmentStatement(currentAssignment.Parent)) return true; // In any other circumstance, the value of the assignment might be read, so we need to transform to // ++x to ensure that we preserve semantics. return false; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_compound_assignment, createChangedDocument, AnalyzersResources.Use_compound_assignment) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.UseCompoundAssignment { internal abstract class AbstractUseCompoundAssignmentCodeFixProvider< TSyntaxKind, TAssignmentSyntax, TExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TSyntaxKind : struct where TAssignmentSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseCompoundAssignmentDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; // See comments in the analyzer for what these maps are for. private readonly ImmutableDictionary<TSyntaxKind, TSyntaxKind> _binaryToAssignmentMap; private readonly ImmutableDictionary<TSyntaxKind, TSyntaxKind> _assignmentToTokenMap; protected AbstractUseCompoundAssignmentCodeFixProvider( ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds) { UseCompoundAssignmentUtilities.GenerateMaps(kinds, out _binaryToAssignmentMap, out _assignmentToTokenMap); } protected abstract SyntaxToken Token(TSyntaxKind kind); protected abstract TAssignmentSyntax Assignment( TSyntaxKind assignmentOpKind, TExpressionSyntax left, SyntaxToken syntaxToken, TExpressionSyntax right); protected abstract TExpressionSyntax Increment(TExpressionSyntax left, bool postfix); protected abstract TExpressionSyntax Decrement(TExpressionSyntax left, bool postfix); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics[0]; context.RegisterCodeFix(new MyCodeAction( c => FixAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var syntaxKinds = syntaxFacts.SyntaxKinds; foreach (var diagnostic in diagnostics) { var assignment = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); editor.ReplaceNode(assignment, (current, generator) => { if (current is not TAssignmentSyntax currentAssignment) return current; syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(currentAssignment, out var leftOfAssign, out var equalsToken, out var rightOfAssign); while (syntaxFacts.IsParenthesizedExpression(rightOfAssign)) rightOfAssign = syntaxFacts.Unparenthesize(rightOfAssign); syntaxFacts.GetPartsOfBinaryExpression(rightOfAssign, out _, out var opToken, out var rightExpr); if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Increment)) return Increment((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment); if (diagnostic.Properties.ContainsKey(UseCompoundAssignmentUtilities.Decrement)) return Decrement((TExpressionSyntax)leftOfAssign, PreferPostfix(syntaxFacts, currentAssignment)).WithTriviaFrom(currentAssignment); var assignmentOpKind = _binaryToAssignmentMap[syntaxKinds.Convert<TSyntaxKind>(rightOfAssign.RawKind)]; var compoundOperator = Token(_assignmentToTokenMap[assignmentOpKind]); return Assignment( assignmentOpKind, (TExpressionSyntax)leftOfAssign, compoundOperator.WithTriviaFrom(equalsToken), (TExpressionSyntax)rightExpr); }); } return Task.CompletedTask; } protected virtual bool PreferPostfix(ISyntaxFactsService syntaxFacts, TAssignmentSyntax currentAssignment) { // If we have `x = x + 1;` on it's own, then we prefer `x++` as idiomatic. if (syntaxFacts.IsSimpleAssignmentStatement(currentAssignment.Parent)) return true; // In any other circumstance, the value of the assignment might be read, so we need to transform to // ++x to ensure that we preserve semantics. return false; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Use_compound_assignment, createChangedDocument, AnalyzersResources.Use_compound_assignment) { } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Remote/Core/ExternalAccess/UnitTesting/Api/UnitTestingRemoteHostClient.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly UnitTestingServiceDescriptorsWrapper _serviceDescriptors; private readonly UnitTestingRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal UnitTestingRemoteHostClient(ServiceHubRemoteHostClient client, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<UnitTestingRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new UnitTestingRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } public UnitTestingRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal readonly struct UnitTestingRemoteHostClient { private readonly ServiceHubRemoteHostClient _client; private readonly UnitTestingServiceDescriptorsWrapper _serviceDescriptors; private readonly UnitTestingRemoteServiceCallbackDispatcherRegistry _callbackDispatchers; internal UnitTestingRemoteHostClient(ServiceHubRemoteHostClient client, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers) { _client = client; _serviceDescriptors = serviceDescriptors; _callbackDispatchers = callbackDispatchers; } public static async Task<UnitTestingRemoteHostClient?> TryGetClientAsync(HostWorkspaceServices services, UnitTestingServiceDescriptorsWrapper serviceDescriptors, UnitTestingRemoteServiceCallbackDispatcherRegistry callbackDispatchers, CancellationToken cancellationToken = default) { var client = await RemoteHostClient.TryGetClientAsync(services, cancellationToken).ConfigureAwait(false); if (client is null) return null; return new UnitTestingRemoteHostClient((ServiceHubRemoteHostClient)client, serviceDescriptors, callbackDispatchers); } public UnitTestingRemoteServiceConnectionWrapper<TService> CreateConnection<TService>(object? callbackTarget) where TService : class => new(_client.CreateConnection<TService>(_serviceDescriptors.UnderlyingObject, _callbackDispatchers, callbackTarget)); // no solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // no solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Func<TService, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(invocation, cancellationToken).ConfigureAwait(false); } // solution, no callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, CancellationToken, ValueTask<TResult>> invocation, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget: null); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } // solution, callback: public async ValueTask<bool> TryInvokeAsync<TService>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } public async ValueTask<Optional<TResult>> TryInvokeAsync<TService, TResult>(Solution solution, Func<TService, UnitTestingPinnedSolutionInfoWrapper, UnitTestingRemoteServiceCallbackIdWrapper, CancellationToken, ValueTask<TResult>> invocation, object callbackTarget, CancellationToken cancellationToken) where TService : class { using var connection = CreateConnection<TService>(callbackTarget); return await connection.TryInvokeAsync(solution, invocation, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Server/VBCSCompilerTests/XunitCompilerServerLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CommandLine; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal sealed class XunitCompilerServerLogger : ICompilerServerLogger { public ITestOutputHelper TestOutputHelper { get; } public bool IsLogging => true; public XunitCompilerServerLogger(ITestOutputHelper testOutputHelper) { TestOutputHelper = testOutputHelper; } public void Log(string message) { TestOutputHelper.WriteLine(message); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CommandLine; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { internal sealed class XunitCompilerServerLogger : ICompilerServerLogger { public ITestOutputHelper TestOutputHelper { get; } public bool IsLogging => true; public XunitCompilerServerLogger(ITestOutputHelper testOutputHelper) { TestOutputHelper = testOutputHelper; } public void Log(string message) { TestOutputHelper.WriteLine(message); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Test/Utilities/CSharp/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal static partial class Extensions { public static AssemblySymbol GetReferencedAssemblySymbol(this CSharpCompilation compilation, MetadataReference reference) { return (AssemblySymbol)compilation.GetAssemblyOrModuleSymbol(reference); } public static ModuleSymbol GetReferencedModuleSymbol(this CSharpCompilation compilation, MetadataReference reference) { return (ModuleSymbol)compilation.GetAssemblyOrModuleSymbol(reference); } public static TypeDeclarationSyntax AsTypeDeclarationSyntax(this SyntaxNode node) { return node as TypeDeclarationSyntax; } public static MethodDeclarationSyntax AsMethodDeclarationSyntax(this SyntaxNode node) { return node as MethodDeclarationSyntax; } public static SyntaxNodeOrToken FindNodeOrTokenByKind(this SyntaxTree syntaxTree, SyntaxKind kind, int occurrence = 1) { if (!(occurrence > 0)) { throw new ArgumentException("Specified value must be greater than zero.", nameof(occurrence)); } SyntaxNodeOrToken foundNode = default(SyntaxNodeOrToken); if (TryFindNodeOrToken(syntaxTree.GetCompilationUnitRoot(), kind, ref occurrence, ref foundNode)) { return foundNode; } return default(SyntaxNodeOrToken); } private static bool TryFindNodeOrToken(SyntaxNodeOrToken node, SyntaxKind kind, ref int occurrence, ref SyntaxNodeOrToken foundNode) { if (node.IsKind(kind)) { occurrence--; if (occurrence == 0) { foundNode = node; return true; } } // we should probably did into trivia if this is a Token, but we won't foreach (var child in node.ChildNodesAndTokens()) { if (TryFindNodeOrToken(child, kind, ref occurrence, ref foundNode)) { return true; } } return false; } public static AssemblySymbol[] BoundReferences(this AssemblySymbol @this) { return (from m in @this.Modules from @ref in m.GetReferencedAssemblySymbols() select @ref).ToArray(); } public static SourceAssemblySymbol SourceAssembly(this CSharpCompilation @this) { return (SourceAssemblySymbol)@this.Assembly; } public static bool HasUnresolvedReferencesByComparisonTo(this AssemblySymbol @this, AssemblySymbol that) { var thisRefs = @this.BoundReferences(); var thatRefs = that.BoundReferences(); for (int i = 0; i < Math.Max(thisRefs.Length, thatRefs.Length); i++) { if (thisRefs[i].IsMissing && !thatRefs[i].IsMissing) { return true; } } return false; } public static bool RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(this AssemblySymbol @this, AssemblySymbol that) { var thisPEAssembly = @this as Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol; if (thisPEAssembly != null) { var thatPEAssembly = that as Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol; return thatPEAssembly != null && ReferenceEquals(thisPEAssembly.Assembly, thatPEAssembly.Assembly) && @this.HasUnresolvedReferencesByComparisonTo(that); } var thisRetargetingAssembly = @this as Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingAssemblySymbol; if (thisRetargetingAssembly != null) { var thatRetargetingAssembly = that as Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingAssemblySymbol; if (thatRetargetingAssembly != null) { return ReferenceEquals(thisRetargetingAssembly.UnderlyingAssembly, thatRetargetingAssembly.UnderlyingAssembly) && @this.HasUnresolvedReferencesByComparisonTo(that); } var thatSourceAssembly = that as SourceAssemblySymbol; return thatSourceAssembly != null && ReferenceEquals(thisRetargetingAssembly.UnderlyingAssembly, thatSourceAssembly) && @this.HasUnresolvedReferencesByComparisonTo(that); } return false; } private static ImmutableArray<string> SplitMemberName(string name) { if (name.StartsWith(".", StringComparison.Ordinal)) { return ImmutableArray.Create(name); } var builder = ArrayBuilder<string>.GetInstance(); string part = name; while (part.Length > 0) { builder.Add(MetadataHelpers.SplitQualifiedName(part, out part)); } builder.ReverseContents(); return builder.ToImmutableAndFree(); } public static Symbol GetMember(this CSharpCompilation compilation, string qualifiedName) { return compilation.GlobalNamespace.GetMember(qualifiedName); } public static ISymbol GetMember(this Compilation compilation, string qualifiedName) { return compilation.GlobalNamespace.GetMember(qualifiedName); } public static T GetMember<T>(this CSharpCompilation compilation, string qualifiedName) where T : Symbol { return (T)compilation.GlobalNamespace.GetMember(qualifiedName); } public static T GetMember<T>(this Compilation compilation, string qualifiedName) where T : ISymbol { return (T)compilation.GlobalNamespace.GetMember(qualifiedName); } public static ImmutableArray<Symbol> GetMembers(this Compilation compilation, string qualifiedName) { NamespaceOrTypeSymbol lastContainer; var members = GetMembers(((CSharpCompilation)compilation).GlobalNamespace, qualifiedName, out lastContainer); if (members.IsEmpty) { Assert.True(false, string.Format("Could not find member named '{0}'. Available members:\r\n{1}", qualifiedName, string.Join("\r\n", lastContainer.GetMembers().Select(m => "\t\t" + m.Name)))); } return members; } private static ImmutableArray<Symbol> GetMembers(NamespaceOrTypeSymbol container, string qualifiedName, out NamespaceOrTypeSymbol lastContainer) { var parts = SplitMemberName(qualifiedName); lastContainer = container; for (int i = 0; i < parts.Length - 1; i++) { var nestedContainer = (NamespaceOrTypeSymbol)lastContainer.GetMember(parts[i]); if (nestedContainer == null) { // If there wasn't a nested namespace or type with that name, assume it's a // member name that includes dots (e.g. explicit interface implementation). return lastContainer.GetMembers(string.Join(".", parts.Skip(i))); } else { lastContainer = nestedContainer; } } return lastContainer.GetMembers(parts[parts.Length - 1]); } private static ImmutableArray<ISymbol> GetMembers(INamespaceOrTypeSymbol container, string qualifiedName, out INamespaceOrTypeSymbol lastContainer) { var parts = SplitMemberName(qualifiedName); lastContainer = container; for (int i = 0; i < parts.Length - 1; i++) { var nestedContainer = (INamespaceOrTypeSymbol)lastContainer.GetMember(parts[i]); if (nestedContainer == null) { // If there wasn't a nested namespace or type with that name, assume it's a // member name that includes dots (e.g. explicit interface implementation). return lastContainer.GetMembers(string.Join(".", parts.Skip(i))); } else { lastContainer = nestedContainer; } } return lastContainer.GetMembers(parts[parts.Length - 1]); } public static Symbol GetMember(this NamespaceOrTypeSymbol container, string qualifiedName) { NamespaceOrTypeSymbol lastContainer; var members = GetMembers(container, qualifiedName, out lastContainer); if (members.Length == 0) { return null; } else if (members.Length > 1) { Assert.True(false, "Found multiple members of specified name:\r\n" + string.Join("\r\n", members)); } return members.Single(); } public static ISymbol GetMember(this INamespaceOrTypeSymbol container, string qualifiedName) { INamespaceOrTypeSymbol lastContainer; var members = GetMembers(container, qualifiedName, out lastContainer); if (members.Length == 0) { return null; } else if (members.Length > 1) { Assert.True(false, "Found multiple members of specified name:\r\n" + string.Join("\r\n", members)); } return members.Single(); } public static T GetMember<T>(this NamespaceOrTypeSymbol symbol, string qualifiedName) where T : Symbol { return (T)symbol.GetMember(qualifiedName); } public static T GetMember<T>(this INamespaceOrTypeSymbol symbol, string qualifiedName) where T : ISymbol { return (T)symbol.GetMember(qualifiedName); } public static PropertySymbol GetProperty(this NamedTypeSymbol symbol, string name) { return (PropertySymbol)symbol.GetMembers(name).Single(); } public static EventSymbol GetEvent(this NamedTypeSymbol symbol, string name) { return (EventSymbol)symbol.GetMembers(name).Single(); } public static MethodSymbol GetMethod(this NamedTypeSymbol symbol, string name) { return (MethodSymbol)symbol.GetMembers(name).Single(); } public static FieldSymbol GetField(this NamedTypeSymbol symbol, string name) { return (FieldSymbol)symbol.GetMembers(name).Single(); } public static NamedTypeSymbol GetTypeMember(this NamespaceOrTypeSymbol symbol, string name) { return symbol.GetTypeMembers(name).Single(); } public static INamedTypeSymbol GetTypeMember(this INamespaceOrTypeSymbol symbol, string name) { return symbol.GetTypeMembers(name).Single(); } public static string[] GetFieldNames(this ModuleSymbol module, string qualifiedTypeName) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember(qualifiedTypeName); return type.GetMembers().OfType<FieldSymbol>().Select(f => f.Name).ToArray(); } public static string[] GetFieldNamesAndTypes(this ModuleSymbol module, string qualifiedTypeName) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember(qualifiedTypeName); return type.GetMembers().OfType<FieldSymbol>().Select(f => f.Name + ": " + f.TypeWithAnnotations).ToArray(); } public static IEnumerable<CSharpAttributeData> GetAttributes(this Symbol @this, NamedTypeSymbol c) { return @this.GetAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, c, TypeCompareKind.ConsiderEverything2)); } public static IEnumerable<CSharpAttributeData> GetAttributes(this Symbol @this, string namespaceName, string typeName) { return @this.GetAttributes().Where(a => a.IsTargetAttribute(namespaceName, typeName)); } public static IEnumerable<CSharpAttributeData> GetAttributes(this Symbol @this, AttributeDescription description) { return @this.GetAttributes().Where(a => a.IsTargetAttribute(@this, description)); } public static CSharpAttributeData GetAttribute(this Symbol @this, NamedTypeSymbol c) { return @this.GetAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, c, TypeCompareKind.ConsiderEverything2)).First(); } public static CSharpAttributeData GetAttribute(this Symbol @this, string namespaceName, string typeName) { return @this.GetAttributes().Where(a => a.IsTargetAttribute(namespaceName, typeName)).First(); } public static CSharpAttributeData GetAttribute(this Symbol @this, MethodSymbol m) { return (from a in @this.GetAttributes() where a.AttributeConstructor.Equals(m) select a).ToList().First(); } public static bool HasAttribute(this Symbol @this, MethodSymbol m) { return (from a in @this.GetAttributes() where a.AttributeConstructor.Equals(m) select a).ToList().FirstOrDefault() != null; } public static void VerifyValue<T>(this CSharpAttributeData attr, int i, TypedConstantKind kind, T v) { var arg = attr.CommonConstructorArguments[i]; Assert.Equal(kind, arg.Kind); Assert.True(IsEqual(arg, v)); } public static void VerifyNamedArgumentValue<T>(this CSharpAttributeData attr, int i, string name, TypedConstantKind kind, T v) { var namedArg = attr.CommonNamedArguments[i]; Assert.Equal(namedArg.Key, name); var arg = namedArg.Value; Assert.Equal(arg.Kind, kind); Assert.True(IsEqual(arg, v)); } internal static bool IsEqual(TypedConstant arg, object expected) { switch (arg.Kind) { case TypedConstantKind.Array: return AreEqual(arg.Values, expected); case TypedConstantKind.Enum: return expected.Equals(arg.Value); case TypedConstantKind.Type: var typeSym = arg.ValueInternal as TypeSymbol; if ((object)typeSym == null) { return false; } var expTypeSym = expected as TypeSymbol; if (typeSym.Equals(expTypeSym)) { return true; } // TODO: improve the comparison mechanism for generic types. if (typeSym.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)typeSym).IsGenericType) { var s1 = typeSym.ToDisplayString(SymbolDisplayFormat.TestFormat); var s2 = expected.ToString(); if ((s1 == s2)) { return true; } } var expType = expected as Type; if (expType == null) { return false; } //Can't always simply compare string as <T>.ToString() is IL format return IsEqual(typeSym, expType); default: //Assert.Equal(expected, CType(arg.Value, T)) return expected == null ? arg.Value == null : expected.Equals(arg.Value); } } /// For argument is not simple 'Type' (generic or array) private static bool IsEqual(TypeSymbol typeSym, Type expType) { // namedType if ((typeSym.TypeKind == TypeKind.Interface || typeSym.TypeKind == TypeKind.Class || typeSym.TypeKind == TypeKind.Struct || typeSym.TypeKind == TypeKind.Delegate)) { NamedTypeSymbol namedType = (NamedTypeSymbol)typeSym; // name should be same if it's not generic (NO ByRef in attribute) if ((namedType.Arity == 0)) { return typeSym.Name == expType.Name; } // generic if (!(expType.GetTypeInfo().IsGenericType)) { return false; } var nameOnly = expType.Name; //generic <Name>'1 var idx = expType.Name.LastIndexOfAny(new char[] { '`' }); if ((idx > 0)) { nameOnly = expType.Name.Substring(0, idx); } if (!(typeSym.Name == nameOnly)) { return false; } var expArgs = expType.GetGenericArguments(); var actArgs = namedType.TypeArguments(); if (!(expArgs.Count() == actArgs.Length)) { return false; } for (var i = 0; i <= expArgs.Count() - 1; i++) { if (!IsEqual(actArgs[i], expArgs[i])) { return false; } } return true; // array type } else if (typeSym.TypeKind == TypeKind.Array) { if (!expType.IsArray) { return false; } var arySym = (ArrayTypeSymbol)typeSym; if (!IsEqual(arySym.ElementType, expType.GetElementType())) { return false; } if (!IsEqual(arySym.BaseType(), expType.GetTypeInfo().BaseType)) { return false; } return arySym.Rank == expType.GetArrayRank(); } return false; } // Compare an Object with a TypedConstant. This compares the TypeConstant's value and ignores the TypeConstant's type. private static bool AreEqual(ImmutableArray<TypedConstant> tc, object o) { if (o == null) { return tc.IsDefault; } else if (tc.IsDefault) { return false; } if (!o.GetType().IsArray) { return false; } var a = (Array)o; bool ret = true; for (var i = 0; i <= a.Length - 1; i++) { var v = a.GetValue(i); var c = tc[i]; ret = ret & IsEqual(c, v); } return ret; } public static void CheckAccessorShape(this MethodSymbol accessor, Symbol propertyOrEvent) { Assert.Same(propertyOrEvent, accessor.AssociatedSymbol); CheckAccessorModifiers(accessor, propertyOrEvent); Assert.Contains(accessor, propertyOrEvent.ContainingType.GetMembers(accessor.Name)); var propertyOrEventType = propertyOrEvent.GetTypeOrReturnType().Type; switch (accessor.MethodKind) { case MethodKind.EventAdd: case MethodKind.EventRemove: Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType); Assert.Equal(propertyOrEventType, accessor.Parameters.Single().Type); break; case MethodKind.PropertyGet: case MethodKind.PropertySet: var property = (PropertySymbol)propertyOrEvent; var isSetter = accessor.MethodKind == MethodKind.PropertySet; if (isSetter) { Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType); } else { Assert.Equal(propertyOrEventType, accessor.ReturnType); } var propertyParameters = property.Parameters; var accessorParameters = accessor.Parameters; Assert.Equal(propertyParameters.Length, accessorParameters.Length - (isSetter ? 1 : 0)); for (int i = 0; i < propertyParameters.Length; i++) { var propertyParam = propertyParameters[i]; var accessorParam = accessorParameters[i]; Assert.Equal(propertyParam.Type, accessorParam.Type); Assert.Equal(propertyParam.RefKind, accessorParam.RefKind); Assert.Equal(propertyParam.Name, accessorParam.Name); } if (isSetter) { var valueParameter = accessorParameters[propertyParameters.Length]; Assert.Equal(propertyOrEventType, valueParameter.Type); Assert.Equal(RefKind.None, valueParameter.RefKind); Assert.Equal(ParameterSymbol.ValueParameterName, valueParameter.Name); } break; default: Assert.False(true, "Unexpected accessor kind " + accessor.MethodKind); break; } } internal static void CheckAccessorModifiers(this MethodSymbol accessor, Symbol propertyOrEvent) { Assert.Equal(propertyOrEvent.DeclaredAccessibility, accessor.DeclaredAccessibility); Assert.Equal(propertyOrEvent.IsAbstract, accessor.IsAbstract); Assert.Equal(propertyOrEvent.IsOverride, accessor.IsOverride); Assert.Equal(propertyOrEvent.IsVirtual, accessor.IsVirtual); Assert.Equal(propertyOrEvent.IsSealed, accessor.IsSealed); Assert.Equal(propertyOrEvent.IsExtern, accessor.IsExtern); Assert.Equal(propertyOrEvent.IsStatic, accessor.IsStatic); } } } // This is deliberately declared in the global namespace so that it will always be discoverable (regardless of usings). internal static class Extensions { /// <summary> /// This method is provided as a convenience for testing the SemanticModel.GetDeclaredSymbol implementation. /// </summary> /// <param name="declaration">This parameter will be type checked, and a NotSupportedException will be thrown if the type is not currently supported by an overload of GetDeclaredSymbol.</param> internal static Symbol GetDeclaredSymbolFromSyntaxNode(this CSharpSemanticModel model, Microsoft.CodeAnalysis.SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) { // NOTE: Do not add types to this condition unless you have verified that there is an overload of SemanticModel.GetDeclaredSymbol // that supports the type you're adding. if (!( declaration is AnonymousObjectCreationExpressionSyntax || declaration is AnonymousObjectMemberDeclaratorSyntax || declaration is BaseTypeDeclarationSyntax || declaration is CatchDeclarationSyntax || declaration is ExternAliasDirectiveSyntax || declaration is ForEachStatementSyntax || declaration is JoinIntoClauseSyntax || declaration is LabeledStatementSyntax || declaration is MemberDeclarationSyntax || declaration is BaseNamespaceDeclarationSyntax || declaration is ParameterSyntax || declaration is QueryClauseSyntax || declaration is QueryContinuationSyntax || declaration is SwitchLabelSyntax || declaration is TypeParameterSyntax || declaration is UsingDirectiveSyntax || declaration is VariableDeclaratorSyntax)) { throw new NotSupportedException("This node type is not supported."); } return (Symbol)model.GetDeclaredSymbol(declaration, cancellationToken); } public static NamedTypeSymbol BaseType(this TypeSymbol symbol) { return symbol.BaseTypeNoUseSiteDiagnostics; } public static ImmutableArray<NamedTypeSymbol> Interfaces(this TypeSymbol symbol) { return symbol.InterfacesNoUseSiteDiagnostics(); } public static ImmutableArray<NamedTypeSymbol> AllInterfaces(this TypeSymbol symbol) { return symbol.AllInterfacesNoUseSiteDiagnostics; } public static ImmutableArray<TypeSymbol> TypeArguments(this NamedTypeSymbol symbol) { return TypeMap.AsTypeSymbols(symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } public static ImmutableArray<TypeSymbol> ConstraintTypes(this TypeParameterSymbol symbol) { return TypeMap.AsTypeSymbols(symbol.ConstraintTypesNoUseSiteDiagnostics); } public static ImmutableArray<INamedTypeSymbol> AllEffectiveInterfacesNoUseSiteDiagnostics(this ITypeParameterSymbol symbol) { return ((Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.TypeParameterSymbol)symbol).UnderlyingTypeParameterSymbol.AllEffectiveInterfacesNoUseSiteDiagnostics.GetPublicSymbols(); } public static ITypeSymbol GetParameterType(this IMethodSymbol method, int index) => method.Parameters[index].Type; public static bool IsNullableType(this ITypeSymbol typeOpt) { return ITypeSymbolHelpers.IsNullableType(typeOpt); } public static ITypeSymbol GetNullableUnderlyingType(this ITypeSymbol type) { return ITypeSymbolHelpers.GetNullableUnderlyingType(type); } public static bool IsDynamic(this ITypeSymbol type) { return type.TypeKind == TypeKind.Dynamic; } public static bool IsDelegateType(this ITypeSymbol type) { return type.TypeKind == TypeKind.Delegate; } public static bool IsErrorType(this ITypeSymbol type) { return type.Kind == SymbolKind.ErrorType; } public static ITypeSymbol StrippedType(this ITypeSymbol type) { return type.IsNullableType() ? type.GetNullableUnderlyingType() : type; } public static string ToTestDisplayString(this Symbol symbol) { return symbol.ToDisplayString(SymbolDisplayFormat.TestFormat); } public static ISymbol GetSpecialTypeMember(this Compilation compilation, SpecialMember specialMember) { return ((CSharpCompilation)compilation).GetSpecialTypeMember(specialMember).GetPublicSymbol(); } public static INamedTypeSymbol GetWellKnownType(this Compilation compilation, WellKnownType type) { return ((CSharpCompilation)compilation).GetWellKnownType(type).GetPublicSymbol(); } public static NamedTypeSymbol Modifier(this CustomModifier m) { return ((CSharpCustomModifier)m).ModifierSymbol; } public static ImmutableArray<IParameterSymbol> GetParameters(this ISymbol member) { switch (member.Kind) { case SymbolKind.Method: return ((IMethodSymbol)member).Parameters; case SymbolKind.Property: return ((IPropertySymbol)member).Parameters; case SymbolKind.Event: return ImmutableArray<IParameterSymbol>.Empty; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } public static bool IsUnboundGenericType(this ITypeSymbol type) { return type is INamedTypeSymbol namedType && namedType.IsUnboundGenericType; } public static bool GivesAccessTo(this AssemblySymbol first, AssemblySymbol second) { return first.GetPublicSymbol().GivesAccessTo(second.GetPublicSymbol()); } public static INamedTypeSymbol CreateTupleTypeSymbol( this CSharpCompilation comp, NamedTypeSymbol underlyingType, ImmutableArray<string> elementNames = default, ImmutableArray<Location> elementLocations = default) { return comp.CreateTupleTypeSymbol(underlyingType.GetPublicSymbol(), elementNames, elementLocations); } public static INamedTypeSymbol CreateTupleTypeSymbol( this CSharpCompilation comp, ImmutableArray<TypeSymbol> elementTypes, ImmutableArray<string> elementNames = default, ImmutableArray<Location> elementLocations = default, ImmutableArray<Microsoft.CodeAnalysis.NullableAnnotation> elementNullableAnnotations = default) { return comp.CreateTupleTypeSymbol(elementTypes.GetPublicSymbols(), elementNames, elementLocations, elementNullableAnnotations); } public static INamedTypeSymbol Construct(this INamedTypeSymbol definition, params TypeSymbol[] typeArguments) { return definition.Construct(typeArguments.Select(s => s.GetPublicSymbol()).ToArray()); } public static INamespaceSymbol CreateErrorNamespaceSymbol(this CSharpCompilation comp, NamespaceSymbol container, string name) { return comp.CreateErrorNamespaceSymbol(container.GetPublicSymbol(), name); } public static bool Equals(this ITypeSymbol first, ITypeSymbol second, TypeCompareKind typeCompareKind) { return first.Equals(second, new Microsoft.CodeAnalysis.SymbolEqualityComparer(typeCompareKind)); } public static ITypeSymbol GetTypeOrReturnType(this ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: return ((IFieldSymbol)symbol).Type; case SymbolKind.Method: return ((IMethodSymbol)symbol).ReturnType; case SymbolKind.Property: return ((IPropertySymbol)symbol).Type; case SymbolKind.Event: return ((IEventSymbol)symbol).Type; case SymbolKind.Local: return ((ILocalSymbol)symbol).Type; case SymbolKind.Parameter: return ((IParameterSymbol)symbol).Type; case SymbolKind.ErrorType: return (ITypeSymbol)symbol; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } public static ITypeSymbol EnumUnderlyingTypeOrSelf(this ITypeSymbol type) { return type.TypeKind == TypeKind.Enum ? ((INamedTypeSymbol)type).EnumUnderlyingType : type; } public static INamedTypeSymbol GetEnumUnderlyingType(this ITypeSymbol type) { var namedType = type as INamedTypeSymbol; return ((object)namedType != null) ? namedType.EnumUnderlyingType : null; } public static ISymbol ConstructedFrom(this ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.NamedType: return ((INamedTypeSymbol)symbol).ConstructedFrom; case SymbolKind.Method: return ((IMethodSymbol)symbol).ConstructedFrom; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } public static INamespaceSymbol GetNestedNamespace(this INamespaceSymbol ns, string name) { foreach (var sym in ns.GetMembers(name)) { if (sym.Kind == SymbolKind.Namespace) { return (INamespaceSymbol)sym; } } return null; } public static IEnumerable<Microsoft.CodeAnalysis.NullableAnnotation> TypeArgumentNullableAnnotations(this INamedTypeSymbol type) { return type.TypeArguments.Select(t => t.NullableAnnotation); } public static IEnumerable<Microsoft.CodeAnalysis.NullableAnnotation> TypeArgumentNullableAnnotations(this IMethodSymbol method) { return method.TypeArguments.Select(t => t.NullableAnnotation); } public static DiagnosticInfo GetUseSiteDiagnostic(this Symbol @this) { return @this.GetUseSiteInfo().DiagnosticInfo; } public static Conversion ClassifyConversionFromType(this ConversionsBase conversions, TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast = false) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = default; Conversion result = conversions.ClassifyConversionFromType(source, destination, ref useSiteInfo, forCast); AddDiagnosticInfos(ref useSiteDiagnostics, useSiteInfo); return result; } private static void AddDiagnosticInfos(ref HashSet<DiagnosticInfo> useSiteDiagnostics, CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (useSiteInfo.Diagnostics is object) { if (useSiteDiagnostics is null) { useSiteDiagnostics = (HashSet<DiagnosticInfo>)useSiteInfo.Diagnostics; } else { useSiteDiagnostics.AddAll(useSiteInfo.Diagnostics); } } } public static Conversion ClassifyConversionFromExpression(this ConversionsBase conversions, BoundExpression sourceExpression, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast = false) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = default; Conversion result = conversions.ClassifyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast); AddDiagnosticInfos(ref useSiteDiagnostics, useSiteInfo); return result; } public static void LookupSymbolsSimpleName( this Microsoft.CodeAnalysis.CSharp.Binder binder, LookupResult result, NamespaceOrTypeSymbol qualifierOpt, string plainName, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, bool diagnose, ref HashSet<DiagnosticInfo> useSiteDiagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = default; binder.LookupSymbolsSimpleName(result, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); AddDiagnosticInfos(ref useSiteDiagnostics, useSiteInfo); } public static ImmutableArray<Symbol> BindCref(this Microsoft.CodeAnalysis.CSharp.Binder binder, CrefSyntax syntax, out Symbol ambiguityWinner, DiagnosticBag diagnostics) { return binder.BindCref(syntax, out ambiguityWinner, new Microsoft.CodeAnalysis.CSharp.BindingDiagnosticBag(diagnostics)); } public static BoundBlock BindEmbeddedBlock(this Microsoft.CodeAnalysis.CSharp.Binder binder, BlockSyntax node, DiagnosticBag diagnostics) { return binder.BindEmbeddedBlock(node, new Microsoft.CodeAnalysis.CSharp.BindingDiagnosticBag(diagnostics)); } public static BoundExpression BindExpression(this Microsoft.CodeAnalysis.CSharp.Binder binder, ExpressionSyntax node, DiagnosticBag diagnostics) { return binder.BindExpression(node, new Microsoft.CodeAnalysis.CSharp.BindingDiagnosticBag(diagnostics)); } public static void Verify(this ImmutableBindingDiagnostic<AssemblySymbol> actual, params Microsoft.CodeAnalysis.Test.Utilities.DiagnosticDescription[] expected) { actual.Diagnostics.Verify(expected); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal static partial class Extensions { public static AssemblySymbol GetReferencedAssemblySymbol(this CSharpCompilation compilation, MetadataReference reference) { return (AssemblySymbol)compilation.GetAssemblyOrModuleSymbol(reference); } public static ModuleSymbol GetReferencedModuleSymbol(this CSharpCompilation compilation, MetadataReference reference) { return (ModuleSymbol)compilation.GetAssemblyOrModuleSymbol(reference); } public static TypeDeclarationSyntax AsTypeDeclarationSyntax(this SyntaxNode node) { return node as TypeDeclarationSyntax; } public static MethodDeclarationSyntax AsMethodDeclarationSyntax(this SyntaxNode node) { return node as MethodDeclarationSyntax; } public static SyntaxNodeOrToken FindNodeOrTokenByKind(this SyntaxTree syntaxTree, SyntaxKind kind, int occurrence = 1) { if (!(occurrence > 0)) { throw new ArgumentException("Specified value must be greater than zero.", nameof(occurrence)); } SyntaxNodeOrToken foundNode = default(SyntaxNodeOrToken); if (TryFindNodeOrToken(syntaxTree.GetCompilationUnitRoot(), kind, ref occurrence, ref foundNode)) { return foundNode; } return default(SyntaxNodeOrToken); } private static bool TryFindNodeOrToken(SyntaxNodeOrToken node, SyntaxKind kind, ref int occurrence, ref SyntaxNodeOrToken foundNode) { if (node.IsKind(kind)) { occurrence--; if (occurrence == 0) { foundNode = node; return true; } } // we should probably did into trivia if this is a Token, but we won't foreach (var child in node.ChildNodesAndTokens()) { if (TryFindNodeOrToken(child, kind, ref occurrence, ref foundNode)) { return true; } } return false; } public static AssemblySymbol[] BoundReferences(this AssemblySymbol @this) { return (from m in @this.Modules from @ref in m.GetReferencedAssemblySymbols() select @ref).ToArray(); } public static SourceAssemblySymbol SourceAssembly(this CSharpCompilation @this) { return (SourceAssemblySymbol)@this.Assembly; } public static bool HasUnresolvedReferencesByComparisonTo(this AssemblySymbol @this, AssemblySymbol that) { var thisRefs = @this.BoundReferences(); var thatRefs = that.BoundReferences(); for (int i = 0; i < Math.Max(thisRefs.Length, thatRefs.Length); i++) { if (thisRefs[i].IsMissing && !thatRefs[i].IsMissing) { return true; } } return false; } public static bool RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(this AssemblySymbol @this, AssemblySymbol that) { var thisPEAssembly = @this as Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol; if (thisPEAssembly != null) { var thatPEAssembly = that as Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE.PEAssemblySymbol; return thatPEAssembly != null && ReferenceEquals(thisPEAssembly.Assembly, thatPEAssembly.Assembly) && @this.HasUnresolvedReferencesByComparisonTo(that); } var thisRetargetingAssembly = @this as Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingAssemblySymbol; if (thisRetargetingAssembly != null) { var thatRetargetingAssembly = that as Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting.RetargetingAssemblySymbol; if (thatRetargetingAssembly != null) { return ReferenceEquals(thisRetargetingAssembly.UnderlyingAssembly, thatRetargetingAssembly.UnderlyingAssembly) && @this.HasUnresolvedReferencesByComparisonTo(that); } var thatSourceAssembly = that as SourceAssemblySymbol; return thatSourceAssembly != null && ReferenceEquals(thisRetargetingAssembly.UnderlyingAssembly, thatSourceAssembly) && @this.HasUnresolvedReferencesByComparisonTo(that); } return false; } private static ImmutableArray<string> SplitMemberName(string name) { if (name.StartsWith(".", StringComparison.Ordinal)) { return ImmutableArray.Create(name); } var builder = ArrayBuilder<string>.GetInstance(); string part = name; while (part.Length > 0) { builder.Add(MetadataHelpers.SplitQualifiedName(part, out part)); } builder.ReverseContents(); return builder.ToImmutableAndFree(); } public static Symbol GetMember(this CSharpCompilation compilation, string qualifiedName) { return compilation.GlobalNamespace.GetMember(qualifiedName); } public static ISymbol GetMember(this Compilation compilation, string qualifiedName) { return compilation.GlobalNamespace.GetMember(qualifiedName); } public static T GetMember<T>(this CSharpCompilation compilation, string qualifiedName) where T : Symbol { return (T)compilation.GlobalNamespace.GetMember(qualifiedName); } public static T GetMember<T>(this Compilation compilation, string qualifiedName) where T : ISymbol { return (T)compilation.GlobalNamespace.GetMember(qualifiedName); } public static ImmutableArray<Symbol> GetMembers(this Compilation compilation, string qualifiedName) { NamespaceOrTypeSymbol lastContainer; var members = GetMembers(((CSharpCompilation)compilation).GlobalNamespace, qualifiedName, out lastContainer); if (members.IsEmpty) { Assert.True(false, string.Format("Could not find member named '{0}'. Available members:\r\n{1}", qualifiedName, string.Join("\r\n", lastContainer.GetMembers().Select(m => "\t\t" + m.Name)))); } return members; } private static ImmutableArray<Symbol> GetMembers(NamespaceOrTypeSymbol container, string qualifiedName, out NamespaceOrTypeSymbol lastContainer) { var parts = SplitMemberName(qualifiedName); lastContainer = container; for (int i = 0; i < parts.Length - 1; i++) { var nestedContainer = (NamespaceOrTypeSymbol)lastContainer.GetMember(parts[i]); if (nestedContainer == null) { // If there wasn't a nested namespace or type with that name, assume it's a // member name that includes dots (e.g. explicit interface implementation). return lastContainer.GetMembers(string.Join(".", parts.Skip(i))); } else { lastContainer = nestedContainer; } } return lastContainer.GetMembers(parts[parts.Length - 1]); } private static ImmutableArray<ISymbol> GetMembers(INamespaceOrTypeSymbol container, string qualifiedName, out INamespaceOrTypeSymbol lastContainer) { var parts = SplitMemberName(qualifiedName); lastContainer = container; for (int i = 0; i < parts.Length - 1; i++) { var nestedContainer = (INamespaceOrTypeSymbol)lastContainer.GetMember(parts[i]); if (nestedContainer == null) { // If there wasn't a nested namespace or type with that name, assume it's a // member name that includes dots (e.g. explicit interface implementation). return lastContainer.GetMembers(string.Join(".", parts.Skip(i))); } else { lastContainer = nestedContainer; } } return lastContainer.GetMembers(parts[parts.Length - 1]); } public static Symbol GetMember(this NamespaceOrTypeSymbol container, string qualifiedName) { NamespaceOrTypeSymbol lastContainer; var members = GetMembers(container, qualifiedName, out lastContainer); if (members.Length == 0) { return null; } else if (members.Length > 1) { Assert.True(false, "Found multiple members of specified name:\r\n" + string.Join("\r\n", members)); } return members.Single(); } public static ISymbol GetMember(this INamespaceOrTypeSymbol container, string qualifiedName) { INamespaceOrTypeSymbol lastContainer; var members = GetMembers(container, qualifiedName, out lastContainer); if (members.Length == 0) { return null; } else if (members.Length > 1) { Assert.True(false, "Found multiple members of specified name:\r\n" + string.Join("\r\n", members)); } return members.Single(); } public static T GetMember<T>(this NamespaceOrTypeSymbol symbol, string qualifiedName) where T : Symbol { return (T)symbol.GetMember(qualifiedName); } public static T GetMember<T>(this INamespaceOrTypeSymbol symbol, string qualifiedName) where T : ISymbol { return (T)symbol.GetMember(qualifiedName); } public static PropertySymbol GetProperty(this NamedTypeSymbol symbol, string name) { return (PropertySymbol)symbol.GetMembers(name).Single(); } public static EventSymbol GetEvent(this NamedTypeSymbol symbol, string name) { return (EventSymbol)symbol.GetMembers(name).Single(); } public static MethodSymbol GetMethod(this NamedTypeSymbol symbol, string name) { return (MethodSymbol)symbol.GetMembers(name).Single(); } public static FieldSymbol GetField(this NamedTypeSymbol symbol, string name) { return (FieldSymbol)symbol.GetMembers(name).Single(); } public static NamedTypeSymbol GetTypeMember(this NamespaceOrTypeSymbol symbol, string name) { return symbol.GetTypeMembers(name).Single(); } public static INamedTypeSymbol GetTypeMember(this INamespaceOrTypeSymbol symbol, string name) { return symbol.GetTypeMembers(name).Single(); } public static string[] GetFieldNames(this ModuleSymbol module, string qualifiedTypeName) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember(qualifiedTypeName); return type.GetMembers().OfType<FieldSymbol>().Select(f => f.Name).ToArray(); } public static string[] GetFieldNamesAndTypes(this ModuleSymbol module, string qualifiedTypeName) { var type = (NamedTypeSymbol)module.GlobalNamespace.GetMember(qualifiedTypeName); return type.GetMembers().OfType<FieldSymbol>().Select(f => f.Name + ": " + f.TypeWithAnnotations).ToArray(); } public static IEnumerable<CSharpAttributeData> GetAttributes(this Symbol @this, NamedTypeSymbol c) { return @this.GetAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, c, TypeCompareKind.ConsiderEverything2)); } public static IEnumerable<CSharpAttributeData> GetAttributes(this Symbol @this, string namespaceName, string typeName) { return @this.GetAttributes().Where(a => a.IsTargetAttribute(namespaceName, typeName)); } public static IEnumerable<CSharpAttributeData> GetAttributes(this Symbol @this, AttributeDescription description) { return @this.GetAttributes().Where(a => a.IsTargetAttribute(@this, description)); } public static CSharpAttributeData GetAttribute(this Symbol @this, NamedTypeSymbol c) { return @this.GetAttributes().Where(a => TypeSymbol.Equals(a.AttributeClass, c, TypeCompareKind.ConsiderEverything2)).First(); } public static CSharpAttributeData GetAttribute(this Symbol @this, string namespaceName, string typeName) { return @this.GetAttributes().Where(a => a.IsTargetAttribute(namespaceName, typeName)).First(); } public static CSharpAttributeData GetAttribute(this Symbol @this, MethodSymbol m) { return (from a in @this.GetAttributes() where a.AttributeConstructor.Equals(m) select a).ToList().First(); } public static bool HasAttribute(this Symbol @this, MethodSymbol m) { return (from a in @this.GetAttributes() where a.AttributeConstructor.Equals(m) select a).ToList().FirstOrDefault() != null; } public static void VerifyValue<T>(this CSharpAttributeData attr, int i, TypedConstantKind kind, T v) { var arg = attr.CommonConstructorArguments[i]; Assert.Equal(kind, arg.Kind); Assert.True(IsEqual(arg, v)); } public static void VerifyNamedArgumentValue<T>(this CSharpAttributeData attr, int i, string name, TypedConstantKind kind, T v) { var namedArg = attr.CommonNamedArguments[i]; Assert.Equal(namedArg.Key, name); var arg = namedArg.Value; Assert.Equal(arg.Kind, kind); Assert.True(IsEqual(arg, v)); } internal static bool IsEqual(TypedConstant arg, object expected) { switch (arg.Kind) { case TypedConstantKind.Array: return AreEqual(arg.Values, expected); case TypedConstantKind.Enum: return expected.Equals(arg.Value); case TypedConstantKind.Type: var typeSym = arg.ValueInternal as TypeSymbol; if ((object)typeSym == null) { return false; } var expTypeSym = expected as TypeSymbol; if (typeSym.Equals(expTypeSym)) { return true; } // TODO: improve the comparison mechanism for generic types. if (typeSym.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)typeSym).IsGenericType) { var s1 = typeSym.ToDisplayString(SymbolDisplayFormat.TestFormat); var s2 = expected.ToString(); if ((s1 == s2)) { return true; } } var expType = expected as Type; if (expType == null) { return false; } //Can't always simply compare string as <T>.ToString() is IL format return IsEqual(typeSym, expType); default: //Assert.Equal(expected, CType(arg.Value, T)) return expected == null ? arg.Value == null : expected.Equals(arg.Value); } } /// For argument is not simple 'Type' (generic or array) private static bool IsEqual(TypeSymbol typeSym, Type expType) { // namedType if ((typeSym.TypeKind == TypeKind.Interface || typeSym.TypeKind == TypeKind.Class || typeSym.TypeKind == TypeKind.Struct || typeSym.TypeKind == TypeKind.Delegate)) { NamedTypeSymbol namedType = (NamedTypeSymbol)typeSym; // name should be same if it's not generic (NO ByRef in attribute) if ((namedType.Arity == 0)) { return typeSym.Name == expType.Name; } // generic if (!(expType.GetTypeInfo().IsGenericType)) { return false; } var nameOnly = expType.Name; //generic <Name>'1 var idx = expType.Name.LastIndexOfAny(new char[] { '`' }); if ((idx > 0)) { nameOnly = expType.Name.Substring(0, idx); } if (!(typeSym.Name == nameOnly)) { return false; } var expArgs = expType.GetGenericArguments(); var actArgs = namedType.TypeArguments(); if (!(expArgs.Count() == actArgs.Length)) { return false; } for (var i = 0; i <= expArgs.Count() - 1; i++) { if (!IsEqual(actArgs[i], expArgs[i])) { return false; } } return true; // array type } else if (typeSym.TypeKind == TypeKind.Array) { if (!expType.IsArray) { return false; } var arySym = (ArrayTypeSymbol)typeSym; if (!IsEqual(arySym.ElementType, expType.GetElementType())) { return false; } if (!IsEqual(arySym.BaseType(), expType.GetTypeInfo().BaseType)) { return false; } return arySym.Rank == expType.GetArrayRank(); } return false; } // Compare an Object with a TypedConstant. This compares the TypeConstant's value and ignores the TypeConstant's type. private static bool AreEqual(ImmutableArray<TypedConstant> tc, object o) { if (o == null) { return tc.IsDefault; } else if (tc.IsDefault) { return false; } if (!o.GetType().IsArray) { return false; } var a = (Array)o; bool ret = true; for (var i = 0; i <= a.Length - 1; i++) { var v = a.GetValue(i); var c = tc[i]; ret = ret & IsEqual(c, v); } return ret; } public static void CheckAccessorShape(this MethodSymbol accessor, Symbol propertyOrEvent) { Assert.Same(propertyOrEvent, accessor.AssociatedSymbol); CheckAccessorModifiers(accessor, propertyOrEvent); Assert.Contains(accessor, propertyOrEvent.ContainingType.GetMembers(accessor.Name)); var propertyOrEventType = propertyOrEvent.GetTypeOrReturnType().Type; switch (accessor.MethodKind) { case MethodKind.EventAdd: case MethodKind.EventRemove: Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType); Assert.Equal(propertyOrEventType, accessor.Parameters.Single().Type); break; case MethodKind.PropertyGet: case MethodKind.PropertySet: var property = (PropertySymbol)propertyOrEvent; var isSetter = accessor.MethodKind == MethodKind.PropertySet; if (isSetter) { Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType); } else { Assert.Equal(propertyOrEventType, accessor.ReturnType); } var propertyParameters = property.Parameters; var accessorParameters = accessor.Parameters; Assert.Equal(propertyParameters.Length, accessorParameters.Length - (isSetter ? 1 : 0)); for (int i = 0; i < propertyParameters.Length; i++) { var propertyParam = propertyParameters[i]; var accessorParam = accessorParameters[i]; Assert.Equal(propertyParam.Type, accessorParam.Type); Assert.Equal(propertyParam.RefKind, accessorParam.RefKind); Assert.Equal(propertyParam.Name, accessorParam.Name); } if (isSetter) { var valueParameter = accessorParameters[propertyParameters.Length]; Assert.Equal(propertyOrEventType, valueParameter.Type); Assert.Equal(RefKind.None, valueParameter.RefKind); Assert.Equal(ParameterSymbol.ValueParameterName, valueParameter.Name); } break; default: Assert.False(true, "Unexpected accessor kind " + accessor.MethodKind); break; } } internal static void CheckAccessorModifiers(this MethodSymbol accessor, Symbol propertyOrEvent) { Assert.Equal(propertyOrEvent.DeclaredAccessibility, accessor.DeclaredAccessibility); Assert.Equal(propertyOrEvent.IsAbstract, accessor.IsAbstract); Assert.Equal(propertyOrEvent.IsOverride, accessor.IsOverride); Assert.Equal(propertyOrEvent.IsVirtual, accessor.IsVirtual); Assert.Equal(propertyOrEvent.IsSealed, accessor.IsSealed); Assert.Equal(propertyOrEvent.IsExtern, accessor.IsExtern); Assert.Equal(propertyOrEvent.IsStatic, accessor.IsStatic); } } } // This is deliberately declared in the global namespace so that it will always be discoverable (regardless of usings). internal static class Extensions { /// <summary> /// This method is provided as a convenience for testing the SemanticModel.GetDeclaredSymbol implementation. /// </summary> /// <param name="declaration">This parameter will be type checked, and a NotSupportedException will be thrown if the type is not currently supported by an overload of GetDeclaredSymbol.</param> internal static Symbol GetDeclaredSymbolFromSyntaxNode(this CSharpSemanticModel model, Microsoft.CodeAnalysis.SyntaxNode declaration, CancellationToken cancellationToken = default(CancellationToken)) { // NOTE: Do not add types to this condition unless you have verified that there is an overload of SemanticModel.GetDeclaredSymbol // that supports the type you're adding. if (!( declaration is AnonymousObjectCreationExpressionSyntax || declaration is AnonymousObjectMemberDeclaratorSyntax || declaration is BaseTypeDeclarationSyntax || declaration is CatchDeclarationSyntax || declaration is ExternAliasDirectiveSyntax || declaration is ForEachStatementSyntax || declaration is JoinIntoClauseSyntax || declaration is LabeledStatementSyntax || declaration is MemberDeclarationSyntax || declaration is BaseNamespaceDeclarationSyntax || declaration is ParameterSyntax || declaration is QueryClauseSyntax || declaration is QueryContinuationSyntax || declaration is SwitchLabelSyntax || declaration is TypeParameterSyntax || declaration is UsingDirectiveSyntax || declaration is VariableDeclaratorSyntax)) { throw new NotSupportedException("This node type is not supported."); } return (Symbol)model.GetDeclaredSymbol(declaration, cancellationToken); } public static NamedTypeSymbol BaseType(this TypeSymbol symbol) { return symbol.BaseTypeNoUseSiteDiagnostics; } public static ImmutableArray<NamedTypeSymbol> Interfaces(this TypeSymbol symbol) { return symbol.InterfacesNoUseSiteDiagnostics(); } public static ImmutableArray<NamedTypeSymbol> AllInterfaces(this TypeSymbol symbol) { return symbol.AllInterfacesNoUseSiteDiagnostics; } public static ImmutableArray<TypeSymbol> TypeArguments(this NamedTypeSymbol symbol) { return TypeMap.AsTypeSymbols(symbol.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); } public static ImmutableArray<TypeSymbol> ConstraintTypes(this TypeParameterSymbol symbol) { return TypeMap.AsTypeSymbols(symbol.ConstraintTypesNoUseSiteDiagnostics); } public static ImmutableArray<INamedTypeSymbol> AllEffectiveInterfacesNoUseSiteDiagnostics(this ITypeParameterSymbol symbol) { return ((Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel.TypeParameterSymbol)symbol).UnderlyingTypeParameterSymbol.AllEffectiveInterfacesNoUseSiteDiagnostics.GetPublicSymbols(); } public static ITypeSymbol GetParameterType(this IMethodSymbol method, int index) => method.Parameters[index].Type; public static bool IsNullableType(this ITypeSymbol typeOpt) { return ITypeSymbolHelpers.IsNullableType(typeOpt); } public static ITypeSymbol GetNullableUnderlyingType(this ITypeSymbol type) { return ITypeSymbolHelpers.GetNullableUnderlyingType(type); } public static bool IsDynamic(this ITypeSymbol type) { return type.TypeKind == TypeKind.Dynamic; } public static bool IsDelegateType(this ITypeSymbol type) { return type.TypeKind == TypeKind.Delegate; } public static bool IsErrorType(this ITypeSymbol type) { return type.Kind == SymbolKind.ErrorType; } public static ITypeSymbol StrippedType(this ITypeSymbol type) { return type.IsNullableType() ? type.GetNullableUnderlyingType() : type; } public static string ToTestDisplayString(this Symbol symbol) { return symbol.ToDisplayString(SymbolDisplayFormat.TestFormat); } public static ISymbol GetSpecialTypeMember(this Compilation compilation, SpecialMember specialMember) { return ((CSharpCompilation)compilation).GetSpecialTypeMember(specialMember).GetPublicSymbol(); } public static INamedTypeSymbol GetWellKnownType(this Compilation compilation, WellKnownType type) { return ((CSharpCompilation)compilation).GetWellKnownType(type).GetPublicSymbol(); } public static NamedTypeSymbol Modifier(this CustomModifier m) { return ((CSharpCustomModifier)m).ModifierSymbol; } public static ImmutableArray<IParameterSymbol> GetParameters(this ISymbol member) { switch (member.Kind) { case SymbolKind.Method: return ((IMethodSymbol)member).Parameters; case SymbolKind.Property: return ((IPropertySymbol)member).Parameters; case SymbolKind.Event: return ImmutableArray<IParameterSymbol>.Empty; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } public static bool IsUnboundGenericType(this ITypeSymbol type) { return type is INamedTypeSymbol namedType && namedType.IsUnboundGenericType; } public static bool GivesAccessTo(this AssemblySymbol first, AssemblySymbol second) { return first.GetPublicSymbol().GivesAccessTo(second.GetPublicSymbol()); } public static INamedTypeSymbol CreateTupleTypeSymbol( this CSharpCompilation comp, NamedTypeSymbol underlyingType, ImmutableArray<string> elementNames = default, ImmutableArray<Location> elementLocations = default) { return comp.CreateTupleTypeSymbol(underlyingType.GetPublicSymbol(), elementNames, elementLocations); } public static INamedTypeSymbol CreateTupleTypeSymbol( this CSharpCompilation comp, ImmutableArray<TypeSymbol> elementTypes, ImmutableArray<string> elementNames = default, ImmutableArray<Location> elementLocations = default, ImmutableArray<Microsoft.CodeAnalysis.NullableAnnotation> elementNullableAnnotations = default) { return comp.CreateTupleTypeSymbol(elementTypes.GetPublicSymbols(), elementNames, elementLocations, elementNullableAnnotations); } public static INamedTypeSymbol Construct(this INamedTypeSymbol definition, params TypeSymbol[] typeArguments) { return definition.Construct(typeArguments.Select(s => s.GetPublicSymbol()).ToArray()); } public static INamespaceSymbol CreateErrorNamespaceSymbol(this CSharpCompilation comp, NamespaceSymbol container, string name) { return comp.CreateErrorNamespaceSymbol(container.GetPublicSymbol(), name); } public static bool Equals(this ITypeSymbol first, ITypeSymbol second, TypeCompareKind typeCompareKind) { return first.Equals(second, new Microsoft.CodeAnalysis.SymbolEqualityComparer(typeCompareKind)); } public static ITypeSymbol GetTypeOrReturnType(this ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: return ((IFieldSymbol)symbol).Type; case SymbolKind.Method: return ((IMethodSymbol)symbol).ReturnType; case SymbolKind.Property: return ((IPropertySymbol)symbol).Type; case SymbolKind.Event: return ((IEventSymbol)symbol).Type; case SymbolKind.Local: return ((ILocalSymbol)symbol).Type; case SymbolKind.Parameter: return ((IParameterSymbol)symbol).Type; case SymbolKind.ErrorType: return (ITypeSymbol)symbol; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } public static ITypeSymbol EnumUnderlyingTypeOrSelf(this ITypeSymbol type) { return type.TypeKind == TypeKind.Enum ? ((INamedTypeSymbol)type).EnumUnderlyingType : type; } public static INamedTypeSymbol GetEnumUnderlyingType(this ITypeSymbol type) { var namedType = type as INamedTypeSymbol; return ((object)namedType != null) ? namedType.EnumUnderlyingType : null; } public static ISymbol ConstructedFrom(this ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.NamedType: return ((INamedTypeSymbol)symbol).ConstructedFrom; case SymbolKind.Method: return ((IMethodSymbol)symbol).ConstructedFrom; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } public static INamespaceSymbol GetNestedNamespace(this INamespaceSymbol ns, string name) { foreach (var sym in ns.GetMembers(name)) { if (sym.Kind == SymbolKind.Namespace) { return (INamespaceSymbol)sym; } } return null; } public static IEnumerable<Microsoft.CodeAnalysis.NullableAnnotation> TypeArgumentNullableAnnotations(this INamedTypeSymbol type) { return type.TypeArguments.Select(t => t.NullableAnnotation); } public static IEnumerable<Microsoft.CodeAnalysis.NullableAnnotation> TypeArgumentNullableAnnotations(this IMethodSymbol method) { return method.TypeArguments.Select(t => t.NullableAnnotation); } public static DiagnosticInfo GetUseSiteDiagnostic(this Symbol @this) { return @this.GetUseSiteInfo().DiagnosticInfo; } public static Conversion ClassifyConversionFromType(this ConversionsBase conversions, TypeSymbol source, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast = false) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = default; Conversion result = conversions.ClassifyConversionFromType(source, destination, ref useSiteInfo, forCast); AddDiagnosticInfos(ref useSiteDiagnostics, useSiteInfo); return result; } private static void AddDiagnosticInfos(ref HashSet<DiagnosticInfo> useSiteDiagnostics, CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (useSiteInfo.Diagnostics is object) { if (useSiteDiagnostics is null) { useSiteDiagnostics = (HashSet<DiagnosticInfo>)useSiteInfo.Diagnostics; } else { useSiteDiagnostics.AddAll(useSiteInfo.Diagnostics); } } } public static Conversion ClassifyConversionFromExpression(this ConversionsBase conversions, BoundExpression sourceExpression, TypeSymbol destination, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool forCast = false) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = default; Conversion result = conversions.ClassifyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast); AddDiagnosticInfos(ref useSiteDiagnostics, useSiteInfo); return result; } public static void LookupSymbolsSimpleName( this Microsoft.CodeAnalysis.CSharp.Binder binder, LookupResult result, NamespaceOrTypeSymbol qualifierOpt, string plainName, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, bool diagnose, ref HashSet<DiagnosticInfo> useSiteDiagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = default; binder.LookupSymbolsSimpleName(result, qualifierOpt, plainName, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); AddDiagnosticInfos(ref useSiteDiagnostics, useSiteInfo); } public static ImmutableArray<Symbol> BindCref(this Microsoft.CodeAnalysis.CSharp.Binder binder, CrefSyntax syntax, out Symbol ambiguityWinner, DiagnosticBag diagnostics) { return binder.BindCref(syntax, out ambiguityWinner, new Microsoft.CodeAnalysis.CSharp.BindingDiagnosticBag(diagnostics)); } public static BoundBlock BindEmbeddedBlock(this Microsoft.CodeAnalysis.CSharp.Binder binder, BlockSyntax node, DiagnosticBag diagnostics) { return binder.BindEmbeddedBlock(node, new Microsoft.CodeAnalysis.CSharp.BindingDiagnosticBag(diagnostics)); } public static BoundExpression BindExpression(this Microsoft.CodeAnalysis.CSharp.Binder binder, ExpressionSyntax node, DiagnosticBag diagnostics) { return binder.BindExpression(node, new Microsoft.CodeAnalysis.CSharp.BindingDiagnosticBag(diagnostics)); } public static void Verify(this ImmutableBindingDiagnostic<AssemblySymbol> actual, params Microsoft.CodeAnalysis.Test.Utilities.DiagnosticDescription[] expected) { actual.Diagnostics.Verify(expected); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Def/Implementation/Utilities/IVsEnumDebugName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { [ComImport] [Guid("9AD7EC03-4157-45B4-A999-403D6DB94578")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsEnumDebugName { [PreserveSig] int Next(uint celt, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface)] IVsDebugName[] rgelt, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4)] uint[] pceltFetched); [PreserveSig] int Skip(uint celt); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IVsEnumDebugName ppEnum); [PreserveSig] int GetCount(out uint pceltCount); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { [ComImport] [Guid("9AD7EC03-4157-45B4-A999-403D6DB94578")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsEnumDebugName { [PreserveSig] int Next(uint celt, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface)] IVsDebugName[] rgelt, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4)] uint[] pceltFetched); [PreserveSig] int Skip(uint celt); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IVsEnumDebugName ppEnum); [PreserveSig] int GetCount(out uint pceltCount); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/DesignerAttribute/DesignerAttributeHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.DesignerAttribute { internal static class DesignerAttributeHelpers { public static async Task<string?> ComputeDesignerAttributeCategoryAsync( INamedTypeSymbol? designerCategoryType, Document document, CancellationToken cancellationToken) { // simple case. If there's no DesignerCategory type in this compilation, then there's // definitely no designable types. Just immediately bail out. if (designerCategoryType == null) return null; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Legacy behavior. We only register the designer info for the first non-nested class // in the file. var firstClass = FindFirstNonNestedClass( syntaxFacts, syntaxFacts.GetMembersOfCompilationUnit(root), cancellationToken); if (firstClass == null) return null; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var firstClassType = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(firstClass, cancellationToken); return TryGetDesignerCategory(firstClassType, designerCategoryType, cancellationToken); } private static string? TryGetDesignerCategory( INamedTypeSymbol classType, INamedTypeSymbol designerCategoryType, CancellationToken cancellationToken) { foreach (var type in classType.GetBaseTypesAndThis()) { cancellationToken.ThrowIfCancellationRequested(); // if it has designer attribute, set it var attribute = type.GetAttributes().FirstOrDefault(d => designerCategoryType.Equals(d.AttributeClass)); if (attribute?.ConstructorArguments.Length == 1) return GetArgumentString(attribute.ConstructorArguments[0]); } return null; } private static SyntaxNode? FindFirstNonNestedClass( ISyntaxFactsService syntaxFacts, SyntaxList<SyntaxNode> members, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxFacts.IsNamespaceDeclaration(member)) { var firstClass = FindFirstNonNestedClass( syntaxFacts, syntaxFacts.GetMembersOfNamespaceDeclaration(member), cancellationToken); if (firstClass != null) return firstClass; } else if (syntaxFacts.IsClassDeclaration(member)) { return member; } } return null; } private static string? GetArgumentString(TypedConstant argument) { if (argument.Type == null || argument.Type.SpecialType != SpecialType.System_String || argument.IsNull || !(argument.Value is string stringValue)) { return null; } return stringValue.Trim(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.DesignerAttribute { internal static class DesignerAttributeHelpers { public static async Task<string?> ComputeDesignerAttributeCategoryAsync( INamedTypeSymbol? designerCategoryType, Document document, CancellationToken cancellationToken) { // simple case. If there's no DesignerCategory type in this compilation, then there's // definitely no designable types. Just immediately bail out. if (designerCategoryType == null) return null; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Legacy behavior. We only register the designer info for the first non-nested class // in the file. var firstClass = FindFirstNonNestedClass( syntaxFacts, syntaxFacts.GetMembersOfCompilationUnit(root), cancellationToken); if (firstClass == null) return null; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var firstClassType = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(firstClass, cancellationToken); return TryGetDesignerCategory(firstClassType, designerCategoryType, cancellationToken); } private static string? TryGetDesignerCategory( INamedTypeSymbol classType, INamedTypeSymbol designerCategoryType, CancellationToken cancellationToken) { foreach (var type in classType.GetBaseTypesAndThis()) { cancellationToken.ThrowIfCancellationRequested(); // if it has designer attribute, set it var attribute = type.GetAttributes().FirstOrDefault(d => designerCategoryType.Equals(d.AttributeClass)); if (attribute?.ConstructorArguments.Length == 1) return GetArgumentString(attribute.ConstructorArguments[0]); } return null; } private static SyntaxNode? FindFirstNonNestedClass( ISyntaxFactsService syntaxFacts, SyntaxList<SyntaxNode> members, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxFacts.IsNamespaceDeclaration(member)) { var firstClass = FindFirstNonNestedClass( syntaxFacts, syntaxFacts.GetMembersOfNamespaceDeclaration(member), cancellationToken); if (firstClass != null) return firstClass; } else if (syntaxFacts.IsClassDeclaration(member)) { return member; } } return null; } private static string? GetArgumentString(TypedConstant argument) { if (argument.Type == null || argument.Type.SpecialType != SpecialType.System_String || argument.IsNull || !(argument.Value is string stringValue)) { return null; } return stringValue.Trim(); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Analyzers/CSharp/CodeFixes/UseIsNullCheck/CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.UseIsNullCheck; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseIsNullCheckForReferenceEquals), Shared] internal class CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider : AbstractUseIsNullCheckForReferenceEqualsCodeFixProvider<ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider() { } protected override string GetIsNullTitle() => CSharpAnalyzersResources.Use_is_null_check; protected override string GetIsNotNullTitle() => GetIsNullTitle(); private static readonly LiteralExpressionSyntax s_nullLiteralExpression = LiteralExpression(SyntaxKind.NullLiteralExpression); private static readonly ConstantPatternSyntax s_nullLiteralPattern = ConstantPattern(s_nullLiteralExpression); private static SyntaxNode CreateEqualsNullCheck(ExpressionSyntax argument) => BinaryExpression(SyntaxKind.EqualsExpression, argument, s_nullLiteralExpression).Parenthesize(); private static SyntaxNode CreateIsNullCheck(ExpressionSyntax argument) => IsPatternExpression(argument, s_nullLiteralPattern).Parenthesize(); private static SyntaxNode CreateIsNotNullCheck(ExpressionSyntax argument) { var parseOptions = (CSharpParseOptions)argument.SyntaxTree.Options; if (parseOptions.LanguageVersion.IsCSharp9OrAbove()) { return IsPatternExpression( argument, UnaryPattern( Token(SyntaxKind.NotKeyword), s_nullLiteralPattern)).Parenthesize(); } return BinaryExpression( SyntaxKind.IsExpression, argument, PredefinedType(Token(SyntaxKind.ObjectKeyword))).Parenthesize(); } protected override SyntaxNode CreateNullCheck(ExpressionSyntax argument, bool isUnconstrainedGeneric) => isUnconstrainedGeneric ? CreateEqualsNullCheck(argument) : CreateIsNullCheck(argument); protected override SyntaxNode CreateNotNullCheck(ExpressionSyntax argument) => CreateIsNotNullCheck(argument); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.UseIsNullCheck; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseIsNullCheckForReferenceEquals), Shared] internal class CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider : AbstractUseIsNullCheckForReferenceEqualsCodeFixProvider<ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseIsNullCheckForReferenceEqualsCodeFixProvider() { } protected override string GetIsNullTitle() => CSharpAnalyzersResources.Use_is_null_check; protected override string GetIsNotNullTitle() => GetIsNullTitle(); private static readonly LiteralExpressionSyntax s_nullLiteralExpression = LiteralExpression(SyntaxKind.NullLiteralExpression); private static readonly ConstantPatternSyntax s_nullLiteralPattern = ConstantPattern(s_nullLiteralExpression); private static SyntaxNode CreateEqualsNullCheck(ExpressionSyntax argument) => BinaryExpression(SyntaxKind.EqualsExpression, argument, s_nullLiteralExpression).Parenthesize(); private static SyntaxNode CreateIsNullCheck(ExpressionSyntax argument) => IsPatternExpression(argument, s_nullLiteralPattern).Parenthesize(); private static SyntaxNode CreateIsNotNullCheck(ExpressionSyntax argument) { var parseOptions = (CSharpParseOptions)argument.SyntaxTree.Options; if (parseOptions.LanguageVersion.IsCSharp9OrAbove()) { return IsPatternExpression( argument, UnaryPattern( Token(SyntaxKind.NotKeyword), s_nullLiteralPattern)).Parenthesize(); } return BinaryExpression( SyntaxKind.IsExpression, argument, PredefinedType(Token(SyntaxKind.ObjectKeyword))).Parenthesize(); } protected override SyntaxNode CreateNullCheck(ExpressionSyntax argument, bool isUnconstrainedGeneric) => isUnconstrainedGeneric ? CreateEqualsNullCheck(argument) : CreateIsNullCheck(argument); protected override SyntaxNode CreateNotNullCheck(ExpressionSyntax argument) => CreateIsNotNullCheck(argument); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/AssemblyReferencesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; 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 Roslyn.Test.MetadataUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class AssemblyReferencesTests : EditAndContinueTestBase { private static readonly CSharpCompilationOptions s_signedDll = TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2); /// <summary> /// The baseline metadata might have less (or even different) references than /// the current compilation. We shouldn't assume that the reference sets are the same. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void CompilationReferences_Less() { // Add some references that are actually not used in the source. // The only actual reference stored in the metadata image would be: mscorlib (rowid 1). // If we incorrectly assume the references are the same we will map TypeRefs of // Mscorlib to System.Windows.Forms. var references = new[] { SystemWindowsFormsRef, MscorlibRef, SystemCoreRef }; string src1 = @" using System; using System.Threading.Tasks; class C { public Task<int> F() { Console.WriteLine(123); return null; } public static void Main() { Console.WriteLine(1); } } "; string src2 = @" using System; using System.Threading.Tasks; class C { public Task<int> F() { Console.WriteLine(123); return null; } public static void Main() { Console.WriteLine(2); } } "; var c1 = CreateEmptyCompilation(src1, references); var c2 = c1.WithSource(src2); var md1 = AssemblyMetadata.CreateFromStream(c1.EmitToStream()); var baseline = EmitBaseline.CreateInitialBaseline(md1.GetModules()[0], handle => default(EditAndContinueMethodDebugInformation)); var mdStream = new MemoryStream(); var ilStream = new MemoryStream(); var pdbStream = new MemoryStream(); var updatedMethods = new List<MethodDefinitionHandle>(); var edits = new[] { SemanticEdit.Create( SemanticEditKind.Update, c1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"), c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main")) }; c2.EmitDifference(baseline, edits, s => false, mdStream, ilStream, pdbStream); var actualIL = ImmutableArray.Create(ilStream.ToArray()).GetMethodIL(); var expectedIL = @" { // Code size 7 (0x7) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: call 0x0A000006 IL_0006: ret }"; // If the references are mismatched then the symbol matcher won't be able to find Task<T> // and will recompile the method body of F (even though the method hasn't changed). AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL); } /// <summary> /// The baseline metadata might have more references than the current compilation. /// References that aren't found in the compilation are treated as missing. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void CompilationReferences_More() { string src1 = @" using System; class C { public static int F(object a) { return 1; } public static void Main() { Console.WriteLine(F(null)); } } "; string src2 = @" using System; class C { public static int F(object a) { return 1; } public static void Main() { F(null); } } "; // Let's say an IL rewriter inserts a new overload of F that references // a type in a new AssemblyRef. string srcPE = @" using System; class C { public static int F(System.Diagnostics.Process a) { return 2; } public static int F(object a) { return 1; } public static void Main() { F(null); } } "; var md1 = AssemblyMetadata.CreateFromStream(CreateEmptyCompilation(srcPE, new[] { MscorlibRef, SystemRef }).EmitToStream()); var c1 = CreateEmptyCompilation(src1, new[] { MscorlibRef }); var c2 = c1.WithSource(src2); var baseline = EmitBaseline.CreateInitialBaseline(md1.GetModules()[0], handle => default(EditAndContinueMethodDebugInformation)); var mdStream = new MemoryStream(); var ilStream = new MemoryStream(); var pdbStream = new MemoryStream(); var updatedMethods = new List<MethodDefinitionHandle>(); var edits = new[] { SemanticEdit.Create( SemanticEditKind.Update, c1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"), c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main")) }; c2.EmitDifference(baseline, edits, s => false, mdStream, ilStream, pdbStream); var actualIL = ImmutableArray.Create(ilStream.ToArray()).GetMethodIL(); // Symbol matcher should ignore overloads with missing type symbols and match // F(object). var expectedIL = @" { // Code size 8 (0x8) .maxstack 8 IL_0000: ldnull IL_0001: call 0x06000002 IL_0006: pop IL_0007: ret }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL); } /// <summary> /// Symbol matcher considers two source types that only differ in the declaring compilations different. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ChangingCompilationDependencies() { string srcLib = @" public class D { } "; string src0 = @" class C { public static int F(D a) { return 1; } } "; string src1 = @" class C { public static int F(D a) { return 2; } } "; string src2 = @" class C { public static int F(D a) { return 3; } } "; var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); lib0.VerifyDiagnostics(); var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); lib1.VerifyDiagnostics(); var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); lib2.VerifyDiagnostics(); var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() }); var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() }); var v0 = CompileAndVerify(compilation0); var v1 = CompileAndVerify(compilation1); var v2 = CompileAndVerify(compilation2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2))); diff2.EmitResult.Diagnostics.Verify(); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void DependencyVersionWildcards_Compilation() { TestDependencyVersionWildcards( "1.0.0.*", new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1002)); TestDependencyVersionWildcards( "1.0.0.*", new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1002), new Version(1, 0, 2000, 1002)); TestDependencyVersionWildcards( "1.0.0.*", new Version(1, 0, 2000, 1003), new Version(1, 0, 2000, 1002), new Version(1, 0, 2000, 1001)); TestDependencyVersionWildcards( "1.0.*", new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1002), new Version(1, 0, 2000, 1003)); TestDependencyVersionWildcards( "1.0.*", new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1005), new Version(1, 0, 2000, 1002)); } private void TestDependencyVersionWildcards(string sourceVersion, Version version0, Version version1, Version version2) { string srcLib = $@" [assembly: System.Reflection.AssemblyVersion(""{sourceVersion}"")] public class D {{ }} "; string src0 = @" class C { public static int F(D a) { return 1; } } "; string src1 = @" class C { public static int F(D a) { return 2; } } "; string src2 = @" class C { public static int F(D a) { return 3; } public static int G(D a) { return 4; } } "; var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version0); lib0.VerifyDiagnostics(); var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version1); lib1.VerifyDiagnostics(); var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version2); lib2.VerifyDiagnostics(); var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() }); var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() }); var v0 = CompileAndVerify(compilation0); var v1 = CompileAndVerify(compilation1); var v2 = CompileAndVerify(compilation2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2), SemanticEdit.Create(SemanticEditKind.Insert, null, g2))); var md1 = diff1.GetMetadata(); var md2 = diff2.GetMetadata(); var aggReader = new AggregatedMetadataReader(md0.MetadataReader, md1.Reader, md2.Reader); // all references to Lib should be to the baseline version: VerifyAssemblyReferences(aggReader, new[] { "mscorlib, 4.0.0.0", "Lib, " + lib0.Assembly.Identity.Version, "mscorlib, 4.0.0.0", "Lib, " + lib0.Assembly.Identity.Version, "mscorlib, 4.0.0.0", "Lib, " + lib0.Assembly.Identity.Version, }); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void DependencyVersionWildcards_Metadata() { string srcLib = @" [assembly: System.Reflection.AssemblyVersion(""1.0.*"")] public class D { } "; string src0 = @" class C { public static int F(D a) { return 1; } } "; string src1 = @" class C { public static int F(D a) { return 2; } } "; string src2 = @" class C { public static int F(D a) { return 3; } public static int G(D a) { return 4; } } "; var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1001)); lib0.VerifyDiagnostics(); var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1002)); lib1.VerifyDiagnostics(); var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1003)); lib2.VerifyDiagnostics(); var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.EmitToImageReference() }, assemblyName: "C", options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.EmitToImageReference() }); var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.EmitToImageReference() }); var v0 = CompileAndVerify(compilation0); var v1 = CompileAndVerify(compilation1); var v2 = CompileAndVerify(compilation2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); diff1.EmitResult.Diagnostics.Verify( // error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging: // 'Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null' changed version to '1.0.2000.1002'. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C", string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging, "Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null", "1.0.2000.1002"))); } [WorkItem(9004, "https://github.com/dotnet/roslyn/issues/9004")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void DependencyVersionWildcardsCollisions() { string srcLib01 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.1"")] public class D { } "; string srcLib02 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.2"")] public class D { } "; string srcLib11 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.1.1"")] public class D { } "; string srcLib12 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.1.2"")] public class D { } "; string src0 = @" extern alias L0; extern alias L1; class C { public static int F(L0::D a, L1::D b) => 1; } "; string src1 = @" extern alias L0; extern alias L1; class C { public static int F(L0::D a, L1::D b) => 2; } "; var lib01 = CreateCompilation(srcLib01, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics(); var ref01 = lib01.ToMetadataReference(ImmutableArray.Create("L0")); var lib02 = CreateCompilation(srcLib02, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics(); var ref02 = lib02.ToMetadataReference(ImmutableArray.Create("L0")); var lib11 = CreateCompilation(srcLib11, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics(); var ref11 = lib11.ToMetadataReference(ImmutableArray.Create("L1")); var lib12 = CreateCompilation(srcLib12, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics(); var ref12 = lib12.ToMetadataReference(ImmutableArray.Create("L1")); var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, ref01, ref11 }, assemblyName: "C", options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, ref02, ref12 }); var v0 = CompileAndVerify(compilation0); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); diff1.EmitResult.Diagnostics.Verify( // error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging: // 'Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null' changed version to '1.0.0.2'. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C", string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging, "Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "1.0.0.2"))); } private void VerifyAssemblyReferences(AggregatedMetadataReader reader, string[] expected) { AssertEx.Equal(expected, reader.GetAssemblyReferences().Select(aref => $"{reader.GetString(aref.Name)}, {aref.Version}")); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [WorkItem(202017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/202017")] public void CurrentCompilationVersionWildcards() { var source0 = MarkedSource(@" using System; [assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")] class C { static void M() { new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke(); } static void F() { } }"); var source1 = MarkedSource(@" using System; [assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")] class C { static void M() { new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke(); new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke(); } static void F() { } }"); var source2 = MarkedSource(@" using System; [assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")] class C { static void M() { new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke(); new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke(); } static void F() { Console.WriteLine(1); } }"); var source3 = MarkedSource(@" using System; [assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")] class C { static void M() { new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke(); new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke(); new Action(<N:2>() => { Console.WriteLine(3); }</N:2>).Invoke(); new Action(<N:3>() => { Console.WriteLine(4); }</N:3>).Invoke(); } static void F() { Console.WriteLine(1); } }"); var options = ComSafeDebugDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2); var compilation0 = CreateCompilation(source0.Tree, options: options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 0))); var compilation1 = compilation0.WithSource(source1.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 10))); var compilation2 = compilation1.WithSource(source2.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 20))); var compilation3 = compilation2.WithSource(source3.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 30))); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var m3 = compilation3.GetMember<MethodSymbol>("C.M"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // First update adds some new synthesized members (lambda related) var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}"); // Second update is to a method that doesn't produce any synthesized members var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}"); // Last update again adds some new synthesized members (lambdas). // Synthesized members added in the first update need to be mapped to the current compilation. // Their containing assembly version is different than the version of the previous assembly and // hence we need to account for wildcards when comparing the versions. var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m2, m3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); diff3.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1#1, <>9__0_2#3, <>9__0_3#3, <M>b__0_0, <M>b__0_1#1, <M>b__0_2#3, <M>b__0_3#3}"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; 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 Roslyn.Test.MetadataUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class AssemblyReferencesTests : EditAndContinueTestBase { private static readonly CSharpCompilationOptions s_signedDll = TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2); /// <summary> /// The baseline metadata might have less (or even different) references than /// the current compilation. We shouldn't assume that the reference sets are the same. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void CompilationReferences_Less() { // Add some references that are actually not used in the source. // The only actual reference stored in the metadata image would be: mscorlib (rowid 1). // If we incorrectly assume the references are the same we will map TypeRefs of // Mscorlib to System.Windows.Forms. var references = new[] { SystemWindowsFormsRef, MscorlibRef, SystemCoreRef }; string src1 = @" using System; using System.Threading.Tasks; class C { public Task<int> F() { Console.WriteLine(123); return null; } public static void Main() { Console.WriteLine(1); } } "; string src2 = @" using System; using System.Threading.Tasks; class C { public Task<int> F() { Console.WriteLine(123); return null; } public static void Main() { Console.WriteLine(2); } } "; var c1 = CreateEmptyCompilation(src1, references); var c2 = c1.WithSource(src2); var md1 = AssemblyMetadata.CreateFromStream(c1.EmitToStream()); var baseline = EmitBaseline.CreateInitialBaseline(md1.GetModules()[0], handle => default(EditAndContinueMethodDebugInformation)); var mdStream = new MemoryStream(); var ilStream = new MemoryStream(); var pdbStream = new MemoryStream(); var updatedMethods = new List<MethodDefinitionHandle>(); var edits = new[] { SemanticEdit.Create( SemanticEditKind.Update, c1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"), c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main")) }; c2.EmitDifference(baseline, edits, s => false, mdStream, ilStream, pdbStream); var actualIL = ImmutableArray.Create(ilStream.ToArray()).GetMethodIL(); var expectedIL = @" { // Code size 7 (0x7) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: call 0x0A000006 IL_0006: ret }"; // If the references are mismatched then the symbol matcher won't be able to find Task<T> // and will recompile the method body of F (even though the method hasn't changed). AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL); } /// <summary> /// The baseline metadata might have more references than the current compilation. /// References that aren't found in the compilation are treated as missing. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void CompilationReferences_More() { string src1 = @" using System; class C { public static int F(object a) { return 1; } public static void Main() { Console.WriteLine(F(null)); } } "; string src2 = @" using System; class C { public static int F(object a) { return 1; } public static void Main() { F(null); } } "; // Let's say an IL rewriter inserts a new overload of F that references // a type in a new AssemblyRef. string srcPE = @" using System; class C { public static int F(System.Diagnostics.Process a) { return 2; } public static int F(object a) { return 1; } public static void Main() { F(null); } } "; var md1 = AssemblyMetadata.CreateFromStream(CreateEmptyCompilation(srcPE, new[] { MscorlibRef, SystemRef }).EmitToStream()); var c1 = CreateEmptyCompilation(src1, new[] { MscorlibRef }); var c2 = c1.WithSource(src2); var baseline = EmitBaseline.CreateInitialBaseline(md1.GetModules()[0], handle => default(EditAndContinueMethodDebugInformation)); var mdStream = new MemoryStream(); var ilStream = new MemoryStream(); var pdbStream = new MemoryStream(); var updatedMethods = new List<MethodDefinitionHandle>(); var edits = new[] { SemanticEdit.Create( SemanticEditKind.Update, c1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"), c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main")) }; c2.EmitDifference(baseline, edits, s => false, mdStream, ilStream, pdbStream); var actualIL = ImmutableArray.Create(ilStream.ToArray()).GetMethodIL(); // Symbol matcher should ignore overloads with missing type symbols and match // F(object). var expectedIL = @" { // Code size 8 (0x8) .maxstack 8 IL_0000: ldnull IL_0001: call 0x06000002 IL_0006: pop IL_0007: ret }"; AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL); } /// <summary> /// Symbol matcher considers two source types that only differ in the declaring compilations different. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ChangingCompilationDependencies() { string srcLib = @" public class D { } "; string src0 = @" class C { public static int F(D a) { return 1; } } "; string src1 = @" class C { public static int F(D a) { return 2; } } "; string src2 = @" class C { public static int F(D a) { return 3; } } "; var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); lib0.VerifyDiagnostics(); var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); lib1.VerifyDiagnostics(); var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); lib2.VerifyDiagnostics(); var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() }); var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() }); var v0 = CompileAndVerify(compilation0); var v1 = CompileAndVerify(compilation1); var v2 = CompileAndVerify(compilation2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2))); diff2.EmitResult.Diagnostics.Verify(); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void DependencyVersionWildcards_Compilation() { TestDependencyVersionWildcards( "1.0.0.*", new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1002)); TestDependencyVersionWildcards( "1.0.0.*", new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1002), new Version(1, 0, 2000, 1002)); TestDependencyVersionWildcards( "1.0.0.*", new Version(1, 0, 2000, 1003), new Version(1, 0, 2000, 1002), new Version(1, 0, 2000, 1001)); TestDependencyVersionWildcards( "1.0.*", new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1002), new Version(1, 0, 2000, 1003)); TestDependencyVersionWildcards( "1.0.*", new Version(1, 0, 2000, 1001), new Version(1, 0, 2000, 1005), new Version(1, 0, 2000, 1002)); } private void TestDependencyVersionWildcards(string sourceVersion, Version version0, Version version1, Version version2) { string srcLib = $@" [assembly: System.Reflection.AssemblyVersion(""{sourceVersion}"")] public class D {{ }} "; string src0 = @" class C { public static int F(D a) { return 1; } } "; string src1 = @" class C { public static int F(D a) { return 2; } } "; string src2 = @" class C { public static int F(D a) { return 3; } public static int G(D a) { return 4; } } "; var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version0); lib0.VerifyDiagnostics(); var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version1); lib1.VerifyDiagnostics(); var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version2); lib2.VerifyDiagnostics(); var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() }); var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() }); var v0 = CompileAndVerify(compilation0); var v1 = CompileAndVerify(compilation1); var v2 = CompileAndVerify(compilation2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2), SemanticEdit.Create(SemanticEditKind.Insert, null, g2))); var md1 = diff1.GetMetadata(); var md2 = diff2.GetMetadata(); var aggReader = new AggregatedMetadataReader(md0.MetadataReader, md1.Reader, md2.Reader); // all references to Lib should be to the baseline version: VerifyAssemblyReferences(aggReader, new[] { "mscorlib, 4.0.0.0", "Lib, " + lib0.Assembly.Identity.Version, "mscorlib, 4.0.0.0", "Lib, " + lib0.Assembly.Identity.Version, "mscorlib, 4.0.0.0", "Lib, " + lib0.Assembly.Identity.Version, }); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void DependencyVersionWildcards_Metadata() { string srcLib = @" [assembly: System.Reflection.AssemblyVersion(""1.0.*"")] public class D { } "; string src0 = @" class C { public static int F(D a) { return 1; } } "; string src1 = @" class C { public static int F(D a) { return 2; } } "; string src2 = @" class C { public static int F(D a) { return 3; } public static int G(D a) { return 4; } } "; var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1001)); lib0.VerifyDiagnostics(); var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1002)); lib1.VerifyDiagnostics(); var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll); ((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1003)); lib2.VerifyDiagnostics(); var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.EmitToImageReference() }, assemblyName: "C", options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.EmitToImageReference() }); var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.EmitToImageReference() }); var v0 = CompileAndVerify(compilation0); var v1 = CompileAndVerify(compilation1); var v2 = CompileAndVerify(compilation2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); diff1.EmitResult.Diagnostics.Verify( // error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging: // 'Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null' changed version to '1.0.2000.1002'. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C", string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging, "Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null", "1.0.2000.1002"))); } [WorkItem(9004, "https://github.com/dotnet/roslyn/issues/9004")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void DependencyVersionWildcardsCollisions() { string srcLib01 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.1"")] public class D { } "; string srcLib02 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.0.2"")] public class D { } "; string srcLib11 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.1.1"")] public class D { } "; string srcLib12 = @" [assembly: System.Reflection.AssemblyVersion(""1.0.1.2"")] public class D { } "; string src0 = @" extern alias L0; extern alias L1; class C { public static int F(L0::D a, L1::D b) => 1; } "; string src1 = @" extern alias L0; extern alias L1; class C { public static int F(L0::D a, L1::D b) => 2; } "; var lib01 = CreateCompilation(srcLib01, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics(); var ref01 = lib01.ToMetadataReference(ImmutableArray.Create("L0")); var lib02 = CreateCompilation(srcLib02, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics(); var ref02 = lib02.ToMetadataReference(ImmutableArray.Create("L0")); var lib11 = CreateCompilation(srcLib11, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics(); var ref11 = lib11.ToMetadataReference(ImmutableArray.Create("L1")); var lib12 = CreateCompilation(srcLib12, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics(); var ref12 = lib12.ToMetadataReference(ImmutableArray.Create("L1")); var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, ref01, ref11 }, assemblyName: "C", options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, ref02, ref12 }); var v0 = CompileAndVerify(compilation0); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); diff1.EmitResult.Diagnostics.Verify( // error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging: // 'Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null' changed version to '1.0.0.2'. Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C", string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging, "Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "1.0.0.2"))); } private void VerifyAssemblyReferences(AggregatedMetadataReader reader, string[] expected) { AssertEx.Equal(expected, reader.GetAssemblyReferences().Select(aref => $"{reader.GetString(aref.Name)}, {aref.Version}")); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [WorkItem(202017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/202017")] public void CurrentCompilationVersionWildcards() { var source0 = MarkedSource(@" using System; [assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")] class C { static void M() { new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke(); } static void F() { } }"); var source1 = MarkedSource(@" using System; [assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")] class C { static void M() { new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke(); new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke(); } static void F() { } }"); var source2 = MarkedSource(@" using System; [assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")] class C { static void M() { new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke(); new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke(); } static void F() { Console.WriteLine(1); } }"); var source3 = MarkedSource(@" using System; [assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")] class C { static void M() { new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke(); new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke(); new Action(<N:2>() => { Console.WriteLine(3); }</N:2>).Invoke(); new Action(<N:3>() => { Console.WriteLine(4); }</N:3>).Invoke(); } static void F() { Console.WriteLine(1); } }"); var options = ComSafeDebugDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2); var compilation0 = CreateCompilation(source0.Tree, options: options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 0))); var compilation1 = compilation0.WithSource(source1.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 10))); var compilation2 = compilation1.WithSource(source2.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 20))); var compilation3 = compilation2.WithSource(source3.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 30))); var v0 = CompileAndVerify(compilation0, verify: Verification.Passes); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var m3 = compilation3.GetMember<MethodSymbol>("C.M"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // First update adds some new synthesized members (lambda related) var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}"); // Second update is to a method that doesn't produce any synthesized members var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}"); // Last update again adds some new synthesized members (lambdas). // Synthesized members added in the first update need to be mapped to the current compilation. // Their containing assembly version is different than the version of the previous assembly and // hence we need to account for wildcards when comparing the versions. var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m2, m3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); diff3.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1#1, <>9__0_2#3, <>9__0_3#3, <M>b__0_0, <M>b__0_1#1, <M>b__0_2#3, <M>b__0_3#3}"); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Test/Core/Mocks/VirtualizedRelativePathResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { internal sealed class VirtualizedRelativePathResolver : RelativePathResolver { private readonly HashSet<string> _existingFullPaths; public VirtualizedRelativePathResolver(IEnumerable<string> existingFullPaths, string baseDirectory = null, ImmutableArray<string> searchPaths = default(ImmutableArray<string>)) : base(searchPaths.NullToEmpty(), baseDirectory) { _existingFullPaths = new HashSet<string>(existingFullPaths, StringComparer.Ordinal); } protected override bool FileExists(string fullPath) { // normalize path to remove '..' and '.' return _existingFullPaths.Contains(Path.GetFullPath(fullPath)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis; namespace Roslyn.Test.Utilities { internal sealed class VirtualizedRelativePathResolver : RelativePathResolver { private readonly HashSet<string> _existingFullPaths; public VirtualizedRelativePathResolver(IEnumerable<string> existingFullPaths, string baseDirectory = null, ImmutableArray<string> searchPaths = default(ImmutableArray<string>)) : base(searchPaths.NullToEmpty(), baseDirectory) { _existingFullPaths = new HashSet<string>(existingFullPaths, StringComparer.Ordinal); } protected override bool FileExists(string fullPath) { // normalize path to remove '..' and '.' return _existingFullPaths.Contains(Path.GetFullPath(fullPath)); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Extension/SetGlobalGlobalPropertiesForCPS.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.ProjectSystem.Build; using Microsoft.VisualStudio.Shell.Interop; namespace Roslyn.Compilers.Extension { [ExportBuildGlobalPropertiesProvider] [AppliesTo("(" + ProjectCapabilities.CSharp + " | " + ProjectCapabilities.VB + ")" + " & " + ProjectCapabilities.LanguageService)] public class SetGlobalGlobalPropertiesForCPS : StaticGlobalPropertiesProviderBase { [ImportingConstructor] [Obsolete("This exported object must be obtained through the MEF export provider.", error: true)] public SetGlobalGlobalPropertiesForCPS(IProjectCommonServices commonServices) : base(commonServices) { } public override Task<IImmutableDictionary<string, string>> GetGlobalPropertiesAsync(CancellationToken cancellationToken) { // Currently the SolutionExists context will always occur before CPS calls this class // If this behavior ever changes we will need to modify this class. return CompilerPackage.RoslynHive != null ? Task.FromResult<IImmutableDictionary<string, string>>(Empty.PropertiesMap.Add("RoslynHive", CompilerPackage.RoslynHive)) : Task.FromResult<IImmutableDictionary<string, string>>(Empty.PropertiesMap); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.ProjectSystem.Build; using Microsoft.VisualStudio.Shell.Interop; namespace Roslyn.Compilers.Extension { [ExportBuildGlobalPropertiesProvider] [AppliesTo("(" + ProjectCapabilities.CSharp + " | " + ProjectCapabilities.VB + ")" + " & " + ProjectCapabilities.LanguageService)] public class SetGlobalGlobalPropertiesForCPS : StaticGlobalPropertiesProviderBase { [ImportingConstructor] [Obsolete("This exported object must be obtained through the MEF export provider.", error: true)] public SetGlobalGlobalPropertiesForCPS(IProjectCommonServices commonServices) : base(commonServices) { } public override Task<IImmutableDictionary<string, string>> GetGlobalPropertiesAsync(CancellationToken cancellationToken) { // Currently the SolutionExists context will always occur before CPS calls this class // If this behavior ever changes we will need to modify this class. return CompilerPackage.RoslynHive != null ? Task.FromResult<IImmutableDictionary<string, string>>(Empty.PropertiesMap.Add("RoslynHive", CompilerPackage.RoslynHive)) : Task.FromResult<IImmutableDictionary<string, string>>(Empty.PropertiesMap); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/Core/Implementation/BraceMatching/BraceHighlightTag.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { internal class BraceHighlightTag : TextMarkerTag { public static readonly BraceHighlightTag StartTag = new(navigateToStart: true); public static readonly BraceHighlightTag EndTag = new(navigateToStart: false); public bool NavigateToStart { get; } private BraceHighlightTag(bool navigateToStart) : base(ClassificationTypeDefinitions.BraceMatchingName) { this.NavigateToStart = navigateToStart; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { internal class BraceHighlightTag : TextMarkerTag { public static readonly BraceHighlightTag StartTag = new(navigateToStart: true); public static readonly BraceHighlightTag EndTag = new(navigateToStart: false); public bool NavigateToStart { get; } private BraceHighlightTag(bool navigateToStart) : base(ClassificationTypeDefinitions.BraceMatchingName) { this.NavigateToStart = navigateToStart; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/AbstractGenerateParameterizedMemberService.SignatureInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal abstract partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { internal abstract class SignatureInfo { protected readonly SemanticDocument Document; protected readonly State State; private ImmutableArray<ITypeParameterSymbol> _typeParameters; private IDictionary<ITypeSymbol, ITypeParameterSymbol> _typeArgumentToTypeParameterMap; public SignatureInfo( SemanticDocument document, State state) { Document = document; State = state; } public ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters(CancellationToken cancellationToken) { return _typeParameters.IsDefault ? (_typeParameters = DetermineTypeParametersWorker(cancellationToken)) : _typeParameters; } protected abstract ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWorker(CancellationToken cancellationToken); protected abstract RefKind DetermineRefKind(CancellationToken cancellationToken); public ValueTask<ITypeSymbol> DetermineReturnTypeAsync(CancellationToken cancellationToken) { var type = DetermineReturnTypeWorker(cancellationToken); if (State.IsInConditionalAccessExpression) { type = type.RemoveNullableIfPresent(); } return FixTypeAsync(type, cancellationToken); } protected abstract ImmutableArray<ITypeSymbol> DetermineTypeArguments(CancellationToken cancellationToken); protected abstract ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken); protected abstract ImmutableArray<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken); protected abstract ImmutableArray<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken); protected abstract ImmutableArray<bool> DetermineParameterOptionality(CancellationToken cancellationToken); protected abstract ImmutableArray<ParameterName> DetermineParameterNames(CancellationToken cancellationToken); internal async ValueTask<IPropertySymbol> GeneratePropertyAsync( SyntaxGenerator factory, bool isAbstract, bool includeSetter, CancellationToken cancellationToken) { var accessibility = DetermineAccessibility(isAbstract); var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default, accessibility: accessibility, statements: GenerateStatements(factory, isAbstract)); var setMethod = includeSetter ? getMethod : null; return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, accessibility: accessibility, modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract), type: await DetermineReturnTypeAsync(cancellationToken).ConfigureAwait(false), refKind: DetermineRefKind(cancellationToken), explicitInterfaceImplementations: default, name: State.IdentifierToken.ValueText, parameters: await DetermineParametersAsync(cancellationToken).ConfigureAwait(false), getMethod: getMethod, setMethod: setMethod); } public async ValueTask<IMethodSymbol> GenerateMethodAsync( SyntaxGenerator factory, bool isAbstract, CancellationToken cancellationToken) { var parameters = await DetermineParametersAsync(cancellationToken).ConfigureAwait(false); var returnType = await DetermineReturnTypeAsync(cancellationToken).ConfigureAwait(false); var isUnsafe = false; if (!State.IsContainedInUnsafeType) { isUnsafe = returnType.RequiresUnsafeModifier() || parameters.Any(p => p.Type.RequiresUnsafeModifier()); } var method = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: DetermineAccessibility(isAbstract), modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract, isUnsafe: isUnsafe), returnType: returnType, refKind: DetermineRefKind(cancellationToken), explicitInterfaceImplementations: default, name: State.IdentifierToken.ValueText, typeParameters: DetermineTypeParameters(cancellationToken), parameters: parameters, statements: GenerateStatements(factory, isAbstract), handlesExpressions: default, returnTypeAttributes: default, methodKind: State.MethodKind); // Ensure no conflicts between type parameter names and parameter names. var languageServiceProvider = Document.Project.Solution.Workspace.Services.GetLanguageServices(State.TypeToGenerateIn.Language); var syntaxFacts = languageServiceProvider.GetService<ISyntaxFactsService>(); var equalityComparer = syntaxFacts.StringComparer; var reservedParameterNames = DetermineParameterNames(cancellationToken) .Select(p => p.BestNameForParameter) .ToSet(equalityComparer); var newTypeParameterNames = NameGenerator.EnsureUniqueness( method.TypeParameters.SelectAsArray(t => t.Name), n => !reservedParameterNames.Contains(n)); return method.RenameTypeParameters(newTypeParameterNames); } private async ValueTask<ITypeSymbol> FixTypeAsync( ITypeSymbol typeSymbol, CancellationToken cancellationToken) { // A type can't refer to a type parameter that isn't available in the type we're // eventually generating into. var availableMethodTypeParameters = DetermineTypeParameters(cancellationToken); var availableTypeParameters = State.TypeToGenerateIn.GetAllTypeParameters(); var compilation = Document.SemanticModel.Compilation; var allTypeParameters = availableMethodTypeParameters.Concat(availableTypeParameters); var availableTypeParameterNames = allTypeParameters.Select(t => t.Name).ToSet(); var typeArgumentToTypeParameterMap = GetTypeArgumentToTypeParameterMap(cancellationToken); typeSymbol = typeSymbol.RemoveAnonymousTypes(compilation); typeSymbol = await ReplaceTypeParametersBasedOnTypeConstraintsAsync( Document.Project, typeSymbol, compilation, availableTypeParameterNames, cancellationToken).ConfigureAwait(false); return typeSymbol.RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation) .SubstituteTypes(typeArgumentToTypeParameterMap, new TypeGenerator()); } private IDictionary<ITypeSymbol, ITypeParameterSymbol> GetTypeArgumentToTypeParameterMap( CancellationToken cancellationToken) { return _typeArgumentToTypeParameterMap ?? (_typeArgumentToTypeParameterMap = CreateTypeArgumentToTypeParameterMap(cancellationToken)); } private IDictionary<ITypeSymbol, ITypeParameterSymbol> CreateTypeArgumentToTypeParameterMap( CancellationToken cancellationToken) { var typeArguments = DetermineTypeArguments(cancellationToken); var typeParameters = DetermineTypeParameters(cancellationToken); // We use a nullability-ignoring comparer because top-level and nested nullability won't matter. If we are looking to replace // IEnumerable<string> with T, we want to replace IEnumerable<string?> whenever it appears in an argument or return type, partly because // there's no way to represent something like T-with-only-the-inner-thing-nullable. We could leave the entire argument as is, but we're suspecting // this is closer to the user's desire, even if it might require some tweaking after the fact. var result = new Dictionary<ITypeSymbol, ITypeParameterSymbol>(SymbolEqualityComparer.Default); for (var i = 0; i < typeArguments.Length; i++) { if (typeArguments[i] != null) { result[typeArguments[i]] = typeParameters[i]; } } return result; } private ImmutableArray<SyntaxNode> GenerateStatements( SyntaxGenerator factory, bool isAbstract) { var throwStatement = CodeGenerationHelpers.GenerateThrowStatement(factory, Document, "System.NotImplementedException"); return isAbstract || State.TypeToGenerateIn.TypeKind == TypeKind.Interface || throwStatement == null ? default : ImmutableArray.Create(throwStatement); } private async ValueTask<ImmutableArray<IParameterSymbol>> DetermineParametersAsync(CancellationToken cancellationToken) { var modifiers = DetermineParameterModifiers(cancellationToken); var types = await SpecializedTasks.WhenAll(DetermineParameterTypes(cancellationToken).Select(t => FixTypeAsync(t, cancellationToken))).ConfigureAwait(false); var optionality = DetermineParameterOptionality(cancellationToken); var names = DetermineParameterNames(cancellationToken); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var result); for (var i = 0; i < modifiers.Length; i++) { result.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: modifiers[i], isParams: false, isOptional: optionality[i], type: types[i], name: names[i].BestNameForParameter)); } return result.ToImmutable(); } private Accessibility DetermineAccessibility(bool isAbstract) { var containingType = State.ContainingType; // If we're generating into an interface, then we don't use any modifiers. if (State.TypeToGenerateIn.TypeKind != TypeKind.Interface) { // Otherwise, figure out what accessibility modifier to use and optionally // mark it as static. if (containingType.IsContainedWithin(State.TypeToGenerateIn)) { return isAbstract ? Accessibility.Protected : Accessibility.Private; } else if (DerivesFrom(containingType) && State.IsStatic) { // NOTE(cyrusn): We only generate protected in the case of statics. Consider // the case where we're generating into one of our base types. i.e.: // // class B : A { void Goo() { A a; a.Goo(); } // // In this case we can *not* mark the method as protected. 'B' can only // access protected members of 'A' through an instance of 'B' (or a subclass // of B). It can not access protected members through an instance of the // superclass. In this case we need to make the method public or internal. // // However, this does not apply if the method will be static. i.e. // // class B : A { void Goo() { A.Goo(); } // // B can access the protected statics of A, and so we generate 'Goo' as // protected. // TODO: Code coverage return Accessibility.Protected; } else if (containingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(State.TypeToGenerateIn.ContainingAssembly)) { return Accessibility.Internal; } else { // TODO: Code coverage return Accessibility.Public; } } return Accessibility.NotApplicable; } private bool DerivesFrom(INamedTypeSymbol containingType) { return containingType.GetBaseTypes().Select(t => t.OriginalDefinition) .OfType<INamedTypeSymbol>() .Contains(State.TypeToGenerateIn); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal abstract partial class AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { internal abstract class SignatureInfo { protected readonly SemanticDocument Document; protected readonly State State; private ImmutableArray<ITypeParameterSymbol> _typeParameters; private IDictionary<ITypeSymbol, ITypeParameterSymbol> _typeArgumentToTypeParameterMap; public SignatureInfo( SemanticDocument document, State state) { Document = document; State = state; } public ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters(CancellationToken cancellationToken) { return _typeParameters.IsDefault ? (_typeParameters = DetermineTypeParametersWorker(cancellationToken)) : _typeParameters; } protected abstract ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWorker(CancellationToken cancellationToken); protected abstract RefKind DetermineRefKind(CancellationToken cancellationToken); public ValueTask<ITypeSymbol> DetermineReturnTypeAsync(CancellationToken cancellationToken) { var type = DetermineReturnTypeWorker(cancellationToken); if (State.IsInConditionalAccessExpression) { type = type.RemoveNullableIfPresent(); } return FixTypeAsync(type, cancellationToken); } protected abstract ImmutableArray<ITypeSymbol> DetermineTypeArguments(CancellationToken cancellationToken); protected abstract ITypeSymbol DetermineReturnTypeWorker(CancellationToken cancellationToken); protected abstract ImmutableArray<RefKind> DetermineParameterModifiers(CancellationToken cancellationToken); protected abstract ImmutableArray<ITypeSymbol> DetermineParameterTypes(CancellationToken cancellationToken); protected abstract ImmutableArray<bool> DetermineParameterOptionality(CancellationToken cancellationToken); protected abstract ImmutableArray<ParameterName> DetermineParameterNames(CancellationToken cancellationToken); internal async ValueTask<IPropertySymbol> GeneratePropertyAsync( SyntaxGenerator factory, bool isAbstract, bool includeSetter, CancellationToken cancellationToken) { var accessibility = DetermineAccessibility(isAbstract); var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol( attributes: default, accessibility: accessibility, statements: GenerateStatements(factory, isAbstract)); var setMethod = includeSetter ? getMethod : null; return CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, accessibility: accessibility, modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract), type: await DetermineReturnTypeAsync(cancellationToken).ConfigureAwait(false), refKind: DetermineRefKind(cancellationToken), explicitInterfaceImplementations: default, name: State.IdentifierToken.ValueText, parameters: await DetermineParametersAsync(cancellationToken).ConfigureAwait(false), getMethod: getMethod, setMethod: setMethod); } public async ValueTask<IMethodSymbol> GenerateMethodAsync( SyntaxGenerator factory, bool isAbstract, CancellationToken cancellationToken) { var parameters = await DetermineParametersAsync(cancellationToken).ConfigureAwait(false); var returnType = await DetermineReturnTypeAsync(cancellationToken).ConfigureAwait(false); var isUnsafe = false; if (!State.IsContainedInUnsafeType) { isUnsafe = returnType.RequiresUnsafeModifier() || parameters.Any(p => p.Type.RequiresUnsafeModifier()); } var method = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility: DetermineAccessibility(isAbstract), modifiers: new DeclarationModifiers(isStatic: State.IsStatic, isAbstract: isAbstract, isUnsafe: isUnsafe), returnType: returnType, refKind: DetermineRefKind(cancellationToken), explicitInterfaceImplementations: default, name: State.IdentifierToken.ValueText, typeParameters: DetermineTypeParameters(cancellationToken), parameters: parameters, statements: GenerateStatements(factory, isAbstract), handlesExpressions: default, returnTypeAttributes: default, methodKind: State.MethodKind); // Ensure no conflicts between type parameter names and parameter names. var languageServiceProvider = Document.Project.Solution.Workspace.Services.GetLanguageServices(State.TypeToGenerateIn.Language); var syntaxFacts = languageServiceProvider.GetService<ISyntaxFactsService>(); var equalityComparer = syntaxFacts.StringComparer; var reservedParameterNames = DetermineParameterNames(cancellationToken) .Select(p => p.BestNameForParameter) .ToSet(equalityComparer); var newTypeParameterNames = NameGenerator.EnsureUniqueness( method.TypeParameters.SelectAsArray(t => t.Name), n => !reservedParameterNames.Contains(n)); return method.RenameTypeParameters(newTypeParameterNames); } private async ValueTask<ITypeSymbol> FixTypeAsync( ITypeSymbol typeSymbol, CancellationToken cancellationToken) { // A type can't refer to a type parameter that isn't available in the type we're // eventually generating into. var availableMethodTypeParameters = DetermineTypeParameters(cancellationToken); var availableTypeParameters = State.TypeToGenerateIn.GetAllTypeParameters(); var compilation = Document.SemanticModel.Compilation; var allTypeParameters = availableMethodTypeParameters.Concat(availableTypeParameters); var availableTypeParameterNames = allTypeParameters.Select(t => t.Name).ToSet(); var typeArgumentToTypeParameterMap = GetTypeArgumentToTypeParameterMap(cancellationToken); typeSymbol = typeSymbol.RemoveAnonymousTypes(compilation); typeSymbol = await ReplaceTypeParametersBasedOnTypeConstraintsAsync( Document.Project, typeSymbol, compilation, availableTypeParameterNames, cancellationToken).ConfigureAwait(false); return typeSymbol.RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation) .SubstituteTypes(typeArgumentToTypeParameterMap, new TypeGenerator()); } private IDictionary<ITypeSymbol, ITypeParameterSymbol> GetTypeArgumentToTypeParameterMap( CancellationToken cancellationToken) { return _typeArgumentToTypeParameterMap ?? (_typeArgumentToTypeParameterMap = CreateTypeArgumentToTypeParameterMap(cancellationToken)); } private IDictionary<ITypeSymbol, ITypeParameterSymbol> CreateTypeArgumentToTypeParameterMap( CancellationToken cancellationToken) { var typeArguments = DetermineTypeArguments(cancellationToken); var typeParameters = DetermineTypeParameters(cancellationToken); // We use a nullability-ignoring comparer because top-level and nested nullability won't matter. If we are looking to replace // IEnumerable<string> with T, we want to replace IEnumerable<string?> whenever it appears in an argument or return type, partly because // there's no way to represent something like T-with-only-the-inner-thing-nullable. We could leave the entire argument as is, but we're suspecting // this is closer to the user's desire, even if it might require some tweaking after the fact. var result = new Dictionary<ITypeSymbol, ITypeParameterSymbol>(SymbolEqualityComparer.Default); for (var i = 0; i < typeArguments.Length; i++) { if (typeArguments[i] != null) { result[typeArguments[i]] = typeParameters[i]; } } return result; } private ImmutableArray<SyntaxNode> GenerateStatements( SyntaxGenerator factory, bool isAbstract) { var throwStatement = CodeGenerationHelpers.GenerateThrowStatement(factory, Document, "System.NotImplementedException"); return isAbstract || State.TypeToGenerateIn.TypeKind == TypeKind.Interface || throwStatement == null ? default : ImmutableArray.Create(throwStatement); } private async ValueTask<ImmutableArray<IParameterSymbol>> DetermineParametersAsync(CancellationToken cancellationToken) { var modifiers = DetermineParameterModifiers(cancellationToken); var types = await SpecializedTasks.WhenAll(DetermineParameterTypes(cancellationToken).Select(t => FixTypeAsync(t, cancellationToken))).ConfigureAwait(false); var optionality = DetermineParameterOptionality(cancellationToken); var names = DetermineParameterNames(cancellationToken); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var result); for (var i = 0; i < modifiers.Length; i++) { result.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: modifiers[i], isParams: false, isOptional: optionality[i], type: types[i], name: names[i].BestNameForParameter)); } return result.ToImmutable(); } private Accessibility DetermineAccessibility(bool isAbstract) { var containingType = State.ContainingType; // If we're generating into an interface, then we don't use any modifiers. if (State.TypeToGenerateIn.TypeKind != TypeKind.Interface) { // Otherwise, figure out what accessibility modifier to use and optionally // mark it as static. if (containingType.IsContainedWithin(State.TypeToGenerateIn)) { return isAbstract ? Accessibility.Protected : Accessibility.Private; } else if (DerivesFrom(containingType) && State.IsStatic) { // NOTE(cyrusn): We only generate protected in the case of statics. Consider // the case where we're generating into one of our base types. i.e.: // // class B : A { void Goo() { A a; a.Goo(); } // // In this case we can *not* mark the method as protected. 'B' can only // access protected members of 'A' through an instance of 'B' (or a subclass // of B). It can not access protected members through an instance of the // superclass. In this case we need to make the method public or internal. // // However, this does not apply if the method will be static. i.e. // // class B : A { void Goo() { A.Goo(); } // // B can access the protected statics of A, and so we generate 'Goo' as // protected. // TODO: Code coverage return Accessibility.Protected; } else if (containingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(State.TypeToGenerateIn.ContainingAssembly)) { return Accessibility.Internal; } else { // TODO: Code coverage return Accessibility.Public; } } return Accessibility.NotApplicable; } private bool DerivesFrom(INamedTypeSymbol containingType) { return containingType.GetBaseTypes().Select(t => t.OriginalDefinition) .OfType<INamedTypeSymbol>() .Contains(State.TypeToGenerateIn); } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/TaskSchedulerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host.Mef; using System; using System.Composition; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Default)] [Shared] internal sealed class TaskSchedulerProvider : ITaskSchedulerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TaskSchedulerProvider() { } public TaskScheduler CurrentContextScheduler => (SynchronizationContext.Current != null) ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Default; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host.Mef; using System; using System.Composition; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Default)] [Shared] internal sealed class TaskSchedulerProvider : ITaskSchedulerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TaskSchedulerProvider() { } public TaskScheduler CurrentContextScheduler => (SynchronizationContext.Current != null) ? TaskScheduler.FromCurrentSynchronizationContext() : TaskScheduler.Default; } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Test/Syntax/Parsing/ScriptParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ScriptParsingTests : ParsingTests { public ScriptParsingTests(ITestOutputHelper output) : base(output) { } #region Helpers protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options ?? TestOptions.Script); } private void ParseAndValidate(string text, params ErrorDescription[] errors) { ParseAndValidate(text, null, errors); } private SyntaxTree ParseAndValidate(string text, CSharpParseOptions options, params ErrorDescription[] errors) { var parsedTree = ParseTree(text, options); var parsedText = parsedTree.GetCompilationUnitRoot(); // we validate the text roundtrips Assert.Equal(text, parsedText.ToFullString()); // get all errors var actualErrors = parsedTree.GetDiagnostics(parsedText); if (errors == null || errors.Length == 0) { Assert.Empty(actualErrors); } else { DiagnosticsUtils.VerifyErrorCodes(actualErrors, errors); } return parsedTree; } #endregion [Fact] public void Error_StaticPartial() { var test = @" int static partial class C { } "; ParseAndValidate(test, new ErrorDescription { Code = 1585, Line = 4, Column = 1 } //static must precede type ); } [WorkItem(529472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529472")] [Fact(Skip = "529472")] public void CS1002ERR_SemicolonExpected() { var test = @" int a Console.Goo "; ParseAndValidate(test, TestOptions.Script, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 6 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 3, Column = 12 }}); } [Fact] public void Error_NewKeywordUsedAsOperator() { var test = @" new in "; UsingTree(test).GetDiagnostics().Verify( // (2,5): error CS1526: A new expression requires an argument list or (), [], or {} after type // new in Diagnostic(ErrorCode.ERR_BadNewExpr, "in").WithLocation(2, 5), // (2,5): error CS1002: ; expected // new in Diagnostic(ErrorCode.ERR_SemicolonExpected, "in").WithLocation(2, 5), // (2,5): error CS7017: Member definition, statement, or end-of-file expected // new in Diagnostic(ErrorCode.ERR_GlobalDefinitionOrStatementExpected, "in").WithLocation(2, 5)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ArgumentList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } #region Method Declarations [Fact] public void MethodDeclarationAndMethodCall() { UsingTree(@" void bar() { } bar(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } #endregion #region Field Declarations [Fact] public void FieldDeclarationError1() { var tree = UsingTree("int x y;"); Assert.True(tree.GetCompilationUnitRoot().ContainsDiagnostics); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken).IsMissing.ShouldBe(true); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void FieldDeclarationError2() { var tree = UsingTree("int x y z;"); Assert.True(tree.GetCompilationUnitRoot().ContainsDiagnostics); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken).IsMissing.ShouldBe(true); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Constructor and Finalizer [Fact] public void Constructor() { var test = @" Script() { } "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 10 }); } [Fact] public void StaticConstructor() { var test = @" static Script() { } "; ParseAndValidate(test, new ErrorDescription { Code = 1520, Line = 2, Column = 8 }); } [Fact] public void Finalizer() { var test = @" ~Script() { } "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 11 }); } #endregion #region New [Fact] public void NewExpression() { UsingTree(@"new[] { 1 };"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ImplicitArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CloseBracketToken); N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewAnonymousTypeExpressionStatement() { UsingTree(@"new { a = 1 };"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AnonymousObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.AnonymousObjectMemberDeclarator); { N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewArrayExpressionStatement() { UsingTree(@"new T[5];"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewArrayExpressionWithInitializerAndPostFixExpressionStatement() { UsingTree(@"new int[] { }.Clone();"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_WithBody() { UsingTree("new void Goo() { }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsIdentifier() { var tree = UsingTree(@" new T Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsArray() { UsingTree("new int[] Goo();"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsPartial() { var tree = UsingTree(@" new partial Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsPartialArray() { var tree = UsingTree(@" new partial[] Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsPartialQualified() { var tree = UsingTree(@" new partial.partial Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialMethod_ReturnsPredefined1() { NewModifier_PartialMethod_ReturnsPredefined("void", SyntaxKind.VoidKeyword); NewModifier_PartialMethod_ReturnsPredefined("int", SyntaxKind.IntKeyword); NewModifier_PartialMethod_ReturnsPredefined("bool", SyntaxKind.BoolKeyword); } private void NewModifier_PartialMethod_ReturnsPredefined(string typeName, SyntaxKind keyword) { var tree = UsingTree("new partial " + typeName + " Goo();"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.PredefinedType); { N(keyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialMethod_ReturnsPartial() { var tree = UsingTree(@" new partial partial Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialMethod_ReturnsPartialQualified() { var tree = UsingTree(@" new partial partial.partial partial(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsPrimitive() { UsingTree("new int Goo();"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Indexer_ReturnsIdentifier() { var tree = UsingTree(@" new T this[int a] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Indexer_ReturnsArray() { var tree = UsingTree(@" new T[] this[int a] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialIndexer() { // partial indexers are not allowed, but we should still parse it and report a semantic error // "Only methods, classes, structs, or interfaces may be partial" var tree = UsingTree(@" new partial partial this[int i] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_WithOtherModifier1() { NewModifier_WithOtherModifier("public", SyntaxKind.PublicKeyword); NewModifier_WithOtherModifier("internal", SyntaxKind.InternalKeyword); NewModifier_WithOtherModifier("protected", SyntaxKind.ProtectedKeyword); NewModifier_WithOtherModifier("private", SyntaxKind.PrivateKeyword); NewModifier_WithOtherModifier("sealed", SyntaxKind.SealedKeyword); NewModifier_WithOtherModifier("abstract", SyntaxKind.AbstractKeyword); NewModifier_WithOtherModifier("static", SyntaxKind.StaticKeyword); NewModifier_WithOtherModifier("virtual", SyntaxKind.VirtualKeyword); NewModifier_WithOtherModifier("extern", SyntaxKind.ExternKeyword); NewModifier_WithOtherModifier("new", SyntaxKind.NewKeyword); NewModifier_WithOtherModifier("override", SyntaxKind.OverrideKeyword); NewModifier_WithOtherModifier("readonly", SyntaxKind.ReadOnlyKeyword); NewModifier_WithOtherModifier("volatile", SyntaxKind.VolatileKeyword); NewModifier_WithOtherModifier("unsafe", SyntaxKind.UnsafeKeyword); } private void NewModifier_WithOtherModifier(string modifier, SyntaxKind keyword) { var tree = UsingTree("new " + modifier + @" T Goo;"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.NewKeyword); N(keyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Class() { var tree = UsingTree(@" new class C { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialClass() { var tree = UsingTree(@" new partial class C { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_ClassWithMisplacedModifiers1() { var tree = UsingTree(@" new partial public class C { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_ClassWithMisplacedModifiers2() { var tree = UsingTree(@" new static partial public class C { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Using [Fact] public void Using() { var tree = UsingTree(@" using Goo; using Goo.Bar; using Goo = Bar; using (var x = bar) { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.UsingStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } } #endregion #region Unsafe [Fact] public void Unsafe_Block() { var tree = UsingTree(@" unsafe { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.UnsafeStatement); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Unsafe_Field() { var tree = UsingTree(@" unsafe int Goo; "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Unsafe_Method() { var tree = UsingTree(@" unsafe void Goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Unsafe_Property() { var tree = UsingTree(@" unsafe int Goo { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } /// bug="3784" project = "Roslyn" [Fact] public void PointerDeclaration() { var test = @" unsafe Idf * Idf; "; ParseAndValidate(test); } #endregion #region Fixed [Fact] public void Fixed() { var tree = UsingTree(@" fixed (int* a = b) { } fixed int x[5]; "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.FixedStatement); { N(SyntaxKind.FixedKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.FixedKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Delegate [Fact] public void Delegate1() { var tree = UsingTree(@" delegate { }(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Delegate2() { var tree = UsingTree(@" delegate(){ }(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Delegate3() { var tree = UsingTree(@" delegate void Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.DelegateDeclaration); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Indexer [Fact] public void Indexer1() { var tree = UsingTree(@" bool this[int index]{} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Indexer2() { var tree = UsingTree(@" public partial bool this[int index] {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Indexer4() { var tree = UsingTree(@" new public bool this[int index] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "index"); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Indexer5() { var tree = UsingTree(@" new public bool this[int index] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "index"); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Error_IndexerDefinition() { var test = @"string this ="""";"; ParseAndValidate(test, new ErrorDescription { Code = 1001, Line = 1, Column = 13 }, new ErrorDescription { Code = 1003, Line = 1, Column = 13 }, new ErrorDescription { Code = 1003, Line = 1, Column = 16 }, new ErrorDescription { Code = 1514, Line = 1, Column = 16 }, new ErrorDescription { Code = 1014, Line = 1, Column = 16 }, new ErrorDescription { Code = 1513, Line = 1, Column = 17 }); CreateCompilation(test).VerifyDiagnostics( // (1,13): error CS1003: Syntax error, '[' expected // string this =""; Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments("[", "=").WithLocation(1, 13), // (1,13): error CS1001: Identifier expected // string this =""; Diagnostic(ErrorCode.ERR_IdentifierExpected, "=").WithLocation(1, 13), // (1,16): error CS1003: Syntax error, ']' expected // string this =""; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("]", ";").WithLocation(1, 16), // (1,16): error CS1514: { expected // string this =""; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(1, 16), // (1,16): error CS1014: A get or set accessor expected // string this =""; Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(1, 16), // (1,17): error CS1513: } expected // string this =""; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 17), // (1,8): error CS0548: '<invalid-global-code>.this': property or indexer must have at least one accessor // string this =""; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("<invalid-global-code>.this").WithLocation(1, 8), // error CS1551: Indexers must have at least one parameter Diagnostic(ErrorCode.ERR_IndexerNeedsParam).WithLocation(1, 1)); } #endregion #region Extern [Fact] public void ExternAlias() { var tree = UsingTree(@" extern alias Goo; extern alias Goo(); extern alias Goo { get; } extern alias Goo<T> { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ExternAliasDirective); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.AliasKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } #endregion #region Ordering [Fact] public void Delegate() { var test = @" delegate { } delegate() { } delegate void Goo(); delegate void MyDel(int i); "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 3, Column = 15 }); } [Fact] public void ExternAliasAmbiguity() { var test = @" extern alias Goo; extern alias Goo(); extern alias Goo { get; } extern alias Goo<T> { get; } "; ParseAndValidate(test, new ErrorDescription { Code = 7002, Line = 5, Column = 14 }); } [Fact] public void ExternOrdering_Statement() { var test = @" using(var x = 1) { } extern alias Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 439, Line = 3, Column = 1 }); } [Fact] public void ExternOrdering_Method() { var test = @" extern void goo(); extern alias Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 439, Line = 3, Column = 1 }); } [Fact] public void ExternOrdering_Field() { var test = @" int a = 1; extern alias Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 439, Line = 3, Column = 1 }); } [Fact] public void ExternOrdering_Property() { var test = @" extern alias Goo { get; } extern alias Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 439, Line = 3, Column = 1 }); } [Fact] public void UsingOrdering_Statement() { var test = @" using(var x = 1) { } using Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 1529, Line = 3, Column = 1 }); } [Fact] public void UsingOrdering_Member() { var test = @" void goo() { } using Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 1529, Line = 3, Column = 1 }); } #endregion #region Partial [Fact] public void PartialMethod() { var tree = UsingTree(@" partial void Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } var test = @" new public bool this[int index] { get { return true; } } "; ParseAndValidate(test); } /// bug="3778" project = "Roslyn" [Fact] public void PartialMethodDefinition() { var test = @" partial void Goo(); "; ParseAndValidate(test); } /// bug="3780" project = "Roslyn" [Fact] public void UsingNewModifierWithPartialMethodDefinition() { var test = @" new partial void Goo(); "; ParseAndValidate(test); } [Fact] public void ImplementingDeclarationOfPartialMethod() { var test = @" partial void Goo(){}; "; ParseAndValidate(test, new ErrorDescription { Code = 1597, Line = 2, Column = 21 }); } [Fact] public void EnumDeclaration() { var test = @" partial enum en {}; "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial enum en {}; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1), // (2,14): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial enum en {}; Diagnostic(ErrorCode.ERR_PartialMisplaced, "en").WithLocation(2, 14)); } [Fact] public void UsingPartial() { var tree = UsingTree(@" partial = partial; partial partial; partial partial = partial; partial Goo { get; } partial partial Goo { get; } partial partial[] Goo { get; } partial partial<int> Goo { get; } partial Goo() { } partial partial Goo() { } partial partial[] Goo() { } partial partial<int> Goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } #endregion #region Attributes [Fact] public void Attributes() { var tree = UsingTree(@" [assembly: Goo] [module: Bar] [Goo] void goo() { } [Bar] int x; [Baz] class C { } [Baz] struct C { } [Baz] enum C { } [Baz] delegate D(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.AttributeTargetSpecifier); { N(SyntaxKind.AssemblyKeyword); N(SyntaxKind.ColonToken); } N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.AttributeTargetSpecifier); { N(SyntaxKind.ModuleKeyword); N(SyntaxKind.ColonToken); } N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.StructDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.StructKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EnumDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.EnumKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.DelegateDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DelegateKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } M(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Fields [Fact] public void Fields() { var tree = UsingTree(@" int x; volatile int x; readonly int x; static int x; fixed int x[10]; "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VolatileKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.ReadOnlyKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.FixedKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Multiplication [Fact] public void Multiplication() { // pointer decl string test = @"a.b * c;"; ParseAndValidate(test, TestOptions.Regular9); // pointer decl test = @"a.b * c"; ParseAndValidate(test, TestOptions.Regular9, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 1, Column = 8 } }); // expected ';' // multiplication test = @"a.b * c;"; ParseAndValidate(test, TestOptions.Script); // multiplication test = @"a.b * c;"; ParseAndValidate(test, TestOptions.Script); // multiplication test = @"a.b * c"; ParseAndValidate(test, TestOptions.Script); } [Fact] public void Multiplication_Interactive_Semicolon() { var tree = UsingTree(@"a * b;", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Multiplication_Interactive_NoSemicolon() { var tree = UsingTree(@"a * b", TestOptions.Script); Assert.False(tree.GetCompilationUnitRoot().ContainsDiagnostics); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Multiplication_Complex() { var tree = UsingTree(@"a<t>.n * f(x)", TestOptions.Script); Assert.False(tree.GetCompilationUnitRoot().ContainsDiagnostics); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.AsteriskToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseParenToken); } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } #endregion #region Ternary Operator // T is a type name, including: // a<b> // a<b>.c // a[] // a[,,] // a<b>.b[] // a<b,c>.d[] // etc. // // Ts is a comma separated list of type names // field decls: // T ? idf; // T ? idf, ... // T ? idf = <expr>, ... // T ? idf = <expr>; // property decls: // T ? idf { ... // T ? idf<Ts> { ... // T ? idf<Ts>. ... { ... // method decls: // T ? idf() where ... // T ? idf() { ... // T ? idf(T idf ... // T ? idf.idf(T idf ... // T ? idf<Ts>(T idf ... // T ? idf<Ts>.idf<Ts>. ...(T idf ... // T ? idf([Attr]T idf ... // T ? idf([Attr]T ? idf ... // T ? idf(out T ? idf ... // T ? idf(T ? idf, ... // T ? idf(this idf ... // T ? idf(params ... // T ? idf(__arglist ... // expressions: // T ? non-idf // T ? idf // T ? idf. ... // T ? idf[ ... // T ? idf< // T ? idf<T // T ? idf<Ts> // T ? idf<Ts>. // T ? idf<Ts>. ... ( // T ? idf( // T ? idf(a // T ? idf(a) // T ? idf(this // T ? idf(this = ... // T ? idf(this[ ... // T ? idf(this. ... // T ? idf(this< ... // T ? idf(this( ... // T ? idf(ref a) // T ? idf() // T ? idf(); // method without body must be abstract, which is probably not what user intended to write in interactive // T ? idf(T ? idf // T ? idf(x: 1, y: 2) : c(z: 3) // T ? idf => { } : c => { } // T ? idf => (d ? e => 1 : f => 2)(3) : c => 2 // T ? idf = <expr> // T ? b = x ? y : z : w // fields // [Fact] public void Ternary_FieldDecl_Semicolon1() { var tree = UsingTree(@"T ? a;", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_FieldDecl_Semicolon2() { var tree = UsingTree(@"T ? b, c = 1;", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_FieldDecl_Semicolon3() { var tree = UsingTree(@"T ? b = d => { };", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_FieldDecl_Semicolon4() { var tree = UsingTree(@"T ? b = x ? y : z;", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_FieldDecl_Comma1() { var tree = UsingTree(@"T ? a,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_FieldDecl_Comma2() { var tree = UsingTree(@"T ? a = 1,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } // properties // [Fact] public void Ternary_PropertyDecl1() { var tree = UsingTree(@"T ? a {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_PropertyDecl2() { var tree = UsingTree(@"T ? a.b {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_PropertyDecl3() { var tree = UsingTree(@"T ? a<T>.b {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_PropertyDecl4() { var tree = UsingTree(@"T ? a<T?>.b<S>.c {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } // methods // [Fact] public void Ternary_MethodDecl1() { var tree = UsingTree(@"T ? a() {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl1_Where() { var tree = UsingTree(@"T ? a() where", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.TypeConstraint); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl2() { var tree = UsingTree(@"T ? a(T b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl3() { var tree = UsingTree(@"T ? a.b(T c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl4() { var tree = UsingTree(@"T ? a<A>.b<B>(C c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl5() { var tree = UsingTree(@"T ? a([Attr]C c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Attr"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl6() { var tree = UsingTree(@"T ? a([Attr(a = b)]c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Attr"); } N(SyntaxKind.AttributeArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AttributeArgument); { N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl7() { var tree = UsingTree(@"T ? a(out C c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl8() { var tree = UsingTree(@"T ? a(C[] a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl9() { var tree = UsingTree(@"T ? a(params", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ParamsKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl10() { var tree = UsingTree(@"T ? a(out T ? b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl11() { var tree = UsingTree(@"T ? a(ref T ? b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl12() { var tree = UsingTree(@"T ? a(params T ? b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ParamsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl13() { var tree = UsingTree(@"T ? a([Attr]T ? b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Attr"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl14A() { var tree = UsingTree(@"T ? a(T ? b,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CommaToken); M(SyntaxKind.Parameter); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl14B() { var tree = UsingTree(@"T ? a(T ? b)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl15() { var tree = UsingTree(@"T ? a(T c)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl16() { var tree = UsingTree(@"T ? a(this c d", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ThisKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IdentifierToken, "d"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl17() { var tree = UsingTree(@"T ? a(ref out T a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl18() { var tree = UsingTree(@"T ? a(int a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl19() { var tree = UsingTree(@"T ? a(ref int a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl20() { var tree = UsingTree(@"T ? a(T a =", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl21() { var tree = UsingTree(@"T ? a(T[,] a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl22() { var tree = UsingTree(@"T ? a(T?[10] a)"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "10"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } /// <summary> /// Prefer method declaration over an expression. /// </summary> [Fact] public void Ternary_MethodDecl_GenericAmbiguity1() { var tree = UsingTree(@"T ? m(a < b, c > d)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "m"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } // expressions // [Fact] public void Ternary_Expression1() { var tree = UsingTree(@"T ? 1", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression2() { var tree = UsingTree(@"T ? a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression3() { var tree = UsingTree(@"T ? a.", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression4() { var tree = UsingTree(@"T ? a[", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.CloseBracketToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression5() { var tree = UsingTree(@"T ? a<", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression6() { var tree = UsingTree(@"T ? a<b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression7() { var tree = UsingTree(@"T ? a<b>", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.GreaterThanToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression8() { var tree = UsingTree(@"T ? a<b,c>", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression9() { var tree = UsingTree(@"T ? a<b>.", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression10() { var tree = UsingTree(@"T ? a<b>.c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression11() { var tree = UsingTree(@"T ? a<b>.c(", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression12() { var tree = UsingTree(@"T ? a(", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression13() { var tree = UsingTree(@"T ? a.b(", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression14() { var tree = UsingTree(@"T ? m(c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression15() { var tree = UsingTree(@"T ? m(c,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression16() { var tree = UsingTree(@"T ? m(c:", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.ColonToken); } M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression17() { var tree = UsingTree(@"T ? m(c?", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression18() { var tree = UsingTree(@"T ? m(c? a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression19() { var tree = UsingTree(@"T ? m(c? a =", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression20() { var tree = UsingTree(@"T ? m(c? a = b ?", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.QuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression21() { var tree = UsingTree(@"T ? m()", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression22() { var tree = UsingTree(@"T ? m(a)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression23() { var tree = UsingTree(@"T ? m();", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression24() { var tree = UsingTree(@"T ? m(a);", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression25() { var tree = UsingTree(@"T ? m(x: 1", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression26() { var tree = UsingTree(@"T ? m(x: 1, y: a ? b : c)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression27() { var tree = UsingTree(@"T ? u => { } : v => { }", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "u"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "v"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression28() { var tree = UsingTree(@"T ? u => (d ? e => 1 : f => 2)(3) : c => 2", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "u"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression30() { var tree = UsingTree(@"T ? a ?", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression31() { var tree = UsingTree(@"T ? a =", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression32() { var tree = UsingTree(@"T ? a = b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression33() { var tree = UsingTree(@"T ? a = b : ", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression34() { var tree = UsingTree(@"T ? m(out c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression35() { var tree = UsingTree(@"T ? m(ref c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression36() { var tree = UsingTree(@"T ? m(ref out", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression37() { var tree = UsingTree(@"T ? m(ref out c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression38() { var tree = UsingTree(@"T ? m(this", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression39() { var tree = UsingTree(@"T ? m(this.", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression40() { var tree = UsingTree(@"T ? m(this<", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.LessThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression41() { var tree = UsingTree(@"T ? m(this[", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression41A() { var tree = UsingTree(@"T ? m(this a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } } M(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression42() { var tree = UsingTree(@"T ? m(this(", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression43() { var tree = UsingTree(@"T ? m(T[", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression44() { var tree = UsingTree(@"T ? m(T[1", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression45() { var tree = UsingTree(@"T ? m(T[1]", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl46() { var tree = UsingTree(@"T ? a(T ? a =", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression47() { var tree = UsingTree(@"T ? a(T)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression48() { var tree = UsingTree(@"T ? a(ref int.MaxValue)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression49() { var tree = UsingTree(@"T ? a(ref a,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression50() { var tree = UsingTree(@"T ? a(,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression51() { var tree = UsingTree(@"T ? a(T ? b[1] : b[2])", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ColonToken); N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBracketToken); } } } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression52() { var tree = UsingTree(@" T ? f(a ? b : c) "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } /// <summary> /// Trailing colon turns a method declaration into an expression. /// </summary> [Fact] public void Ternary_Expression_GenericAmbiguity1() { var tree = UsingTree(@"T ? m(a < b, c > d) :", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_WithQuery_FieldDecl1() { var tree = UsingTree(@" T? from; "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_WithQuery_Expression1() { var tree = UsingTree(@" T ? from "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_WithQuery_Expression2() { var tree = UsingTree(@" T ? from x "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_WithQuery_Expression3() { var tree = UsingTree(@" T ? f(from "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } /// <summary> /// Assume that "from" usually doesn't bind to a type and is rather a start of a query. /// </summary> [Fact] public void Ternary_WithQuery_Expression4() { var tree = UsingTree(@" T ? f(from x "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } #endregion #region Queries [Fact] public void From_Identifier() { var tree = UsingTree(@"from", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_FieldDecl() { var tree = UsingTree(@"from c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void From_FieldDecl2() { var tree = UsingTree(@"from x,"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_FieldDecl3() { var tree = UsingTree(@"from x;"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void From_FieldDecl4() { var tree = UsingTree(@"from x ="); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_FieldDecl5() { var tree = UsingTree(@"from x["); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } } M(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl1() { var tree = UsingTree(@"from c("); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl2() { var tree = UsingTree(@"from a<"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); M(SyntaxKind.TypeParameter); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.GreaterThanToken); } M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl3() { var tree = UsingTree(@"from a."); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl4() { var tree = UsingTree(@"from a::"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl5() { var tree = UsingTree(@"from global::"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "global"); } M(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_PropertyDecl1() { var tree = UsingTree(@"from c {"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query1() { var tree = UsingTree(@"from c d"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IdentifierToken, "d"); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query2() { var tree = UsingTree(@"from x* a"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.IdentifierToken, "a"); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query3() { var tree = UsingTree(@"from x? a"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query4() { var tree = UsingTree(@"from x[] a"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "a"); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query5() { var tree = UsingTree(@"from goo in"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query6() { var tree = UsingTree(@"from goo.bar in"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "bar"); } } M(SyntaxKind.IdentifierToken); N(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } #endregion #region Global statement separators /// <summary> /// Comma after a global statement is ignored and a new global statement is parsed. /// </summary> [Fact] public void GlobalStatementSeparators_Comma1() { var tree = UsingTree("a < b,c.", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_Comma2() { var tree = UsingTree(@" a < b, void goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_ClosingParen() { var tree = UsingTree(@" a < b) void goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_ClosingBracket() { var tree = UsingTree(@" a < b] void goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_ClosingBrace() { var tree = UsingTree(@" a < b} void goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_NonAsciiCharacter() { var test = @" H �oz "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 3 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnexpectedCharacter, Line = 2, Column = 3 }); } [Fact] public void GlobalStatementSeparators_UnicodeCharacter() { var test = @" int नुसौप्रख्यातनिदेशकपुरानी "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 29 }); } [Fact] public void GlobalStatementSeparators_Missing() { var test = @" using System; int a Console.Goo() "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 3, Column = 6 }); } #endregion #region Invalid Keywords [Fact] public void OperatorError() { var test = @"operator"; ParseAndValidate(test, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1031, Line = 1, Column = 9 }, new ErrorDescription { Code = 1003, Line = 1, Column = 1 }, new ErrorDescription { Code = 1026, Line = 1, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 1, Column = 9 }); } [Fact] public void OperatorImplicitError() { var test = @"implicit"; ParseAndValidate(test, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1031, Line = 1, Column = 9 }, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1026, Line = 1, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 1, Column = 9 }); } [Fact] public void OperatorExplicitError() { var test = @"explicit"; ParseAndValidate(test, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1031, Line = 1, Column = 9 }, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1026, Line = 1, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 1, Column = 9 }); } #endregion [Fact] public void FieldDeclaration() { var test = @" volatile int x; const int w; readonly int y; static int z; "; ParseAndValidate(test, new ErrorDescription { Code = 145, Line = 3, Column = 11 }); } /// bug="3782" project = "Roslyn" [Fact] public void ClassDeclaration() { var test = @" class C { } static class C2 { } partial class C3 { } "; ParseAndValidate(test); } /// bug="3783" project = "Roslyn" [Fact] public void InterfaceDeclaration() { var test = @" interface IC { } "; ParseAndValidate(test); } [Fact] public void TopLevelXML() { var test = @" <Expects Status=success></Expects> "; ParseAndValidate(test, new ErrorDescription { Code = 1525, Line = 2, Column = 1 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 10 }, new ErrorDescription { Code = 1525, Line = 2, Column = 25 }, new ErrorDescription { Code = 1525, Line = 2, Column = 26 }, new ErrorDescription { Code = 1733, Line = 2, Column = 35 }); } [Fact] public void NotIncorrectKeyword() { var test = @" parial class Test { } "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 8 }); } [Fact] public void Keyword() { var test = @" p class A { } "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 3 }); } [WorkItem(528532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528532")] [Fact] public void ParseForwardSlash() { var test = @"/"; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); Assert.Equal(1, tree.GetCompilationUnitRoot().ChildNodes().Count()); Assert.Equal(SyntaxKind.GlobalStatement, tree.GetCompilationUnitRoot().ChildNodes().ToList()[0].Kind()); } [WorkItem(541164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541164")] [Fact] public void CS1733ERR_ExpressionExpected() { var test = @"Console.WriteLine(""Hello"")?"; ParseAndValidate(test, new ErrorDescription { Code = 1733, Line = 1, Column = 28 }, new ErrorDescription { Code = 1003, Line = 1, Column = 28 }, new ErrorDescription { Code = 1733, Line = 1, Column = 28 }); } #region Shebang [Fact] public void Shebang() { var command = "/usr/bin/env csi"; var tree = ParseAndValidate($"#!{command}", TestOptions.Script); var root = tree.GetCompilationUnitRoot(); Assert.Empty(root.ChildNodes()); var eof = root.EndOfFileToken; Assert.Equal(SyntaxKind.EndOfFileToken, eof.Kind()); var trivia = eof.GetLeadingTrivia().Single(); TestShebang(trivia, command); Assert.True(root.ContainsDirectives); TestShebang(root.GetDirectives().Single(), command); tree = ParseAndValidate($"#! {command}\r\n ", TestOptions.Script); root = tree.GetCompilationUnitRoot(); Assert.Empty(root.ChildNodes()); eof = root.EndOfFileToken; Assert.Equal(SyntaxKind.EndOfFileToken, eof.Kind()); var leading = eof.GetLeadingTrivia().ToArray(); Assert.Equal(2, leading.Length); Assert.Equal(SyntaxKind.ShebangDirectiveTrivia, leading[0].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, leading[1].Kind()); TestShebang(leading[0], command); Assert.True(root.ContainsDirectives); TestShebang(root.GetDirectives().Single(), command); tree = ParseAndValidate( $@"#!{command} Console.WriteLine(""Hi!"");", TestOptions.Script); root = tree.GetCompilationUnitRoot(); var statement = root.ChildNodes().Single(); Assert.Equal(SyntaxKind.GlobalStatement, statement.Kind()); trivia = statement.GetLeadingTrivia().Single(); TestShebang(trivia, command); Assert.True(root.ContainsDirectives); TestShebang(root.GetDirectives().Single(), command); } [Fact] public void ShebangNotFirstCharacter() { ParseAndValidate(" #!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 1, Column = 2 }); ParseAndValidate("\n#!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 2, Column = 1 }); ParseAndValidate("\r\n#!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 2, Column = 1 }); ParseAndValidate("#!/bin/sh\r\n#!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 2, Column = 1 }); ParseAndValidate("a #!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_BadDirectivePlacement, Line = 1, Column = 3 }); } [Fact] public void ShebangNoBang() { ParseAndValidate("#/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 1, Column = 1 }); } [Fact] public void ShebangSpaceBang() { ParseAndValidate("# !/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 1, Column = 1 }); } [Fact] public void ShebangInComment() { var tree = ParseAndValidate("//#!/usr/bin/env csi", TestOptions.Script); var root = tree.GetCompilationUnitRoot(); Assert.Empty(root.ChildNodes()); var eof = root.EndOfFileToken; Assert.Equal(SyntaxKind.EndOfFileToken, eof.Kind()); Assert.Equal(SyntaxKind.SingleLineCommentTrivia, eof.GetLeadingTrivia().Single().Kind()); } [Fact] public void ShebangNotInScript() { ParseAndValidate("#!/usr/bin/env csi", TestOptions.Regular, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 1, Column = 1 }); } private void TestShebang(SyntaxTrivia trivia, string expectedSkippedText) { Assert.True(trivia.IsDirective); Assert.Equal(SyntaxKind.ShebangDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); TestShebang((ShebangDirectiveTriviaSyntax)trivia.GetStructure(), expectedSkippedText); } private void TestShebang(DirectiveTriviaSyntax directive, string expectedSkippedText) { var shebang = (ShebangDirectiveTriviaSyntax)directive; Assert.False(shebang.HasStructuredTrivia); Assert.Equal(SyntaxKind.HashToken, shebang.HashToken.Kind()); Assert.Equal(SyntaxKind.ExclamationToken, shebang.ExclamationToken.Kind()); var endOfDirective = shebang.EndOfDirectiveToken; Assert.Equal(SyntaxKind.EndOfDirectiveToken, endOfDirective.Kind()); Assert.Equal(0, endOfDirective.Span.Length); var skippedText = endOfDirective.LeadingTrivia.Single(); Assert.Equal(SyntaxKind.PreprocessingMessageTrivia, skippedText.Kind()); Assert.Equal(expectedSkippedText, skippedText.ToString()); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class ScriptParsingTests : ParsingTests { public ScriptParsingTests(ITestOutputHelper output) : base(output) { } #region Helpers protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options: options ?? TestOptions.Script); } private void ParseAndValidate(string text, params ErrorDescription[] errors) { ParseAndValidate(text, null, errors); } private SyntaxTree ParseAndValidate(string text, CSharpParseOptions options, params ErrorDescription[] errors) { var parsedTree = ParseTree(text, options); var parsedText = parsedTree.GetCompilationUnitRoot(); // we validate the text roundtrips Assert.Equal(text, parsedText.ToFullString()); // get all errors var actualErrors = parsedTree.GetDiagnostics(parsedText); if (errors == null || errors.Length == 0) { Assert.Empty(actualErrors); } else { DiagnosticsUtils.VerifyErrorCodes(actualErrors, errors); } return parsedTree; } #endregion [Fact] public void Error_StaticPartial() { var test = @" int static partial class C { } "; ParseAndValidate(test, new ErrorDescription { Code = 1585, Line = 4, Column = 1 } //static must precede type ); } [WorkItem(529472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529472")] [Fact(Skip = "529472")] public void CS1002ERR_SemicolonExpected() { var test = @" int a Console.Goo "; ParseAndValidate(test, TestOptions.Script, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 6 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 3, Column = 12 }}); } [Fact] public void Error_NewKeywordUsedAsOperator() { var test = @" new in "; UsingTree(test).GetDiagnostics().Verify( // (2,5): error CS1526: A new expression requires an argument list or (), [], or {} after type // new in Diagnostic(ErrorCode.ERR_BadNewExpr, "in").WithLocation(2, 5), // (2,5): error CS1002: ; expected // new in Diagnostic(ErrorCode.ERR_SemicolonExpected, "in").WithLocation(2, 5), // (2,5): error CS7017: Member definition, statement, or end-of-file expected // new in Diagnostic(ErrorCode.ERR_GlobalDefinitionOrStatementExpected, "in").WithLocation(2, 5)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ArgumentList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } #region Method Declarations [Fact] public void MethodDeclarationAndMethodCall() { UsingTree(@" void bar() { } bar(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } #endregion #region Field Declarations [Fact] public void FieldDeclarationError1() { var tree = UsingTree("int x y;"); Assert.True(tree.GetCompilationUnitRoot().ContainsDiagnostics); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken).IsMissing.ShouldBe(true); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void FieldDeclarationError2() { var tree = UsingTree("int x y z;"); Assert.True(tree.GetCompilationUnitRoot().ContainsDiagnostics); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken).IsMissing.ShouldBe(true); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Constructor and Finalizer [Fact] public void Constructor() { var test = @" Script() { } "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 10 }); } [Fact] public void StaticConstructor() { var test = @" static Script() { } "; ParseAndValidate(test, new ErrorDescription { Code = 1520, Line = 2, Column = 8 }); } [Fact] public void Finalizer() { var test = @" ~Script() { } "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 11 }); } #endregion #region New [Fact] public void NewExpression() { UsingTree(@"new[] { 1 };"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ImplicitArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CloseBracketToken); N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewAnonymousTypeExpressionStatement() { UsingTree(@"new { a = 1 };"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AnonymousObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.AnonymousObjectMemberDeclarator); { N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewArrayExpressionStatement() { UsingTree(@"new T[5];"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewArrayExpressionWithInitializerAndPostFixExpressionStatement() { UsingTree(@"new int[] { }.Clone();"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_WithBody() { UsingTree("new void Goo() { }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsIdentifier() { var tree = UsingTree(@" new T Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsArray() { UsingTree("new int[] Goo();"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsPartial() { var tree = UsingTree(@" new partial Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsPartialArray() { var tree = UsingTree(@" new partial[] Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsPartialQualified() { var tree = UsingTree(@" new partial.partial Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialMethod_ReturnsPredefined1() { NewModifier_PartialMethod_ReturnsPredefined("void", SyntaxKind.VoidKeyword); NewModifier_PartialMethod_ReturnsPredefined("int", SyntaxKind.IntKeyword); NewModifier_PartialMethod_ReturnsPredefined("bool", SyntaxKind.BoolKeyword); } private void NewModifier_PartialMethod_ReturnsPredefined(string typeName, SyntaxKind keyword) { var tree = UsingTree("new partial " + typeName + " Goo();"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.PredefinedType); { N(keyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialMethod_ReturnsPartial() { var tree = UsingTree(@" new partial partial Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialMethod_ReturnsPartialQualified() { var tree = UsingTree(@" new partial partial.partial partial(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Method_ReturnsPrimitive() { UsingTree("new int Goo();"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Indexer_ReturnsIdentifier() { var tree = UsingTree(@" new T this[int a] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Indexer_ReturnsArray() { var tree = UsingTree(@" new T[] this[int a] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialIndexer() { // partial indexers are not allowed, but we should still parse it and report a semantic error // "Only methods, classes, structs, or interfaces may be partial" var tree = UsingTree(@" new partial partial this[int i] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_WithOtherModifier1() { NewModifier_WithOtherModifier("public", SyntaxKind.PublicKeyword); NewModifier_WithOtherModifier("internal", SyntaxKind.InternalKeyword); NewModifier_WithOtherModifier("protected", SyntaxKind.ProtectedKeyword); NewModifier_WithOtherModifier("private", SyntaxKind.PrivateKeyword); NewModifier_WithOtherModifier("sealed", SyntaxKind.SealedKeyword); NewModifier_WithOtherModifier("abstract", SyntaxKind.AbstractKeyword); NewModifier_WithOtherModifier("static", SyntaxKind.StaticKeyword); NewModifier_WithOtherModifier("virtual", SyntaxKind.VirtualKeyword); NewModifier_WithOtherModifier("extern", SyntaxKind.ExternKeyword); NewModifier_WithOtherModifier("new", SyntaxKind.NewKeyword); NewModifier_WithOtherModifier("override", SyntaxKind.OverrideKeyword); NewModifier_WithOtherModifier("readonly", SyntaxKind.ReadOnlyKeyword); NewModifier_WithOtherModifier("volatile", SyntaxKind.VolatileKeyword); NewModifier_WithOtherModifier("unsafe", SyntaxKind.UnsafeKeyword); } private void NewModifier_WithOtherModifier(string modifier, SyntaxKind keyword) { var tree = UsingTree("new " + modifier + @" T Goo;"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.NewKeyword); N(keyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_Class() { var tree = UsingTree(@" new class C { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_PartialClass() { var tree = UsingTree(@" new partial class C { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_ClassWithMisplacedModifiers1() { var tree = UsingTree(@" new partial public class C { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void NewModifier_ClassWithMisplacedModifiers2() { var tree = UsingTree(@" new static partial public class C { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Using [Fact] public void Using() { var tree = UsingTree(@" using Goo; using Goo.Bar; using Goo = Bar; using (var x = bar) { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.UsingStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } } #endregion #region Unsafe [Fact] public void Unsafe_Block() { var tree = UsingTree(@" unsafe { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.UnsafeStatement); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Unsafe_Field() { var tree = UsingTree(@" unsafe int Goo; "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Unsafe_Method() { var tree = UsingTree(@" unsafe void Goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Unsafe_Property() { var tree = UsingTree(@" unsafe int Goo { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } /// bug="3784" project = "Roslyn" [Fact] public void PointerDeclaration() { var test = @" unsafe Idf * Idf; "; ParseAndValidate(test); } #endregion #region Fixed [Fact] public void Fixed() { var tree = UsingTree(@" fixed (int* a = b) { } fixed int x[5]; "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.FixedStatement); { N(SyntaxKind.FixedKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.FixedKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Delegate [Fact] public void Delegate1() { var tree = UsingTree(@" delegate { }(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Delegate2() { var tree = UsingTree(@" delegate(){ }(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Delegate3() { var tree = UsingTree(@" delegate void Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.DelegateDeclaration); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Indexer [Fact] public void Indexer1() { var tree = UsingTree(@" bool this[int index]{} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Indexer2() { var tree = UsingTree(@" public partial bool this[int index] {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.PartialKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Indexer4() { var tree = UsingTree(@" new public bool this[int index] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "index"); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Indexer5() { var tree = UsingTree(@" new public bool this[int index] { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.IndexerDeclaration); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.ThisKeyword); N(SyntaxKind.BracketedParameterList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "index"); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Error_IndexerDefinition() { var test = @"string this ="""";"; ParseAndValidate(test, new ErrorDescription { Code = 1001, Line = 1, Column = 13 }, new ErrorDescription { Code = 1003, Line = 1, Column = 13 }, new ErrorDescription { Code = 1003, Line = 1, Column = 16 }, new ErrorDescription { Code = 1514, Line = 1, Column = 16 }, new ErrorDescription { Code = 1014, Line = 1, Column = 16 }, new ErrorDescription { Code = 1513, Line = 1, Column = 17 }); CreateCompilation(test).VerifyDiagnostics( // (1,13): error CS1003: Syntax error, '[' expected // string this =""; Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments("[", "=").WithLocation(1, 13), // (1,13): error CS1001: Identifier expected // string this =""; Diagnostic(ErrorCode.ERR_IdentifierExpected, "=").WithLocation(1, 13), // (1,16): error CS1003: Syntax error, ']' expected // string this =""; Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments("]", ";").WithLocation(1, 16), // (1,16): error CS1514: { expected // string this =""; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(1, 16), // (1,16): error CS1014: A get or set accessor expected // string this =""; Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(1, 16), // (1,17): error CS1513: } expected // string this =""; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 17), // (1,8): error CS0548: '<invalid-global-code>.this': property or indexer must have at least one accessor // string this =""; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("<invalid-global-code>.this").WithLocation(1, 8), // error CS1551: Indexers must have at least one parameter Diagnostic(ErrorCode.ERR_IndexerNeedsParam).WithLocation(1, 1)); } #endregion #region Extern [Fact] public void ExternAlias() { var tree = UsingTree(@" extern alias Goo; extern alias Goo(); extern alias Goo { get; } extern alias Goo<T> { get; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ExternAliasDirective); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.AliasKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } #endregion #region Ordering [Fact] public void Delegate() { var test = @" delegate { } delegate() { } delegate void Goo(); delegate void MyDel(int i); "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 3, Column = 15 }); } [Fact] public void ExternAliasAmbiguity() { var test = @" extern alias Goo; extern alias Goo(); extern alias Goo { get; } extern alias Goo<T> { get; } "; ParseAndValidate(test, new ErrorDescription { Code = 7002, Line = 5, Column = 14 }); } [Fact] public void ExternOrdering_Statement() { var test = @" using(var x = 1) { } extern alias Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 439, Line = 3, Column = 1 }); } [Fact] public void ExternOrdering_Method() { var test = @" extern void goo(); extern alias Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 439, Line = 3, Column = 1 }); } [Fact] public void ExternOrdering_Field() { var test = @" int a = 1; extern alias Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 439, Line = 3, Column = 1 }); } [Fact] public void ExternOrdering_Property() { var test = @" extern alias Goo { get; } extern alias Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 439, Line = 3, Column = 1 }); } [Fact] public void UsingOrdering_Statement() { var test = @" using(var x = 1) { } using Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 1529, Line = 3, Column = 1 }); } [Fact] public void UsingOrdering_Member() { var test = @" void goo() { } using Goo; "; ParseAndValidate(test, new ErrorDescription { Code = 1529, Line = 3, Column = 1 }); } #endregion #region Partial [Fact] public void PartialMethod() { var tree = UsingTree(@" partial void Goo(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } var test = @" new public bool this[int index] { get { return true; } } "; ParseAndValidate(test); } /// bug="3778" project = "Roslyn" [Fact] public void PartialMethodDefinition() { var test = @" partial void Goo(); "; ParseAndValidate(test); } /// bug="3780" project = "Roslyn" [Fact] public void UsingNewModifierWithPartialMethodDefinition() { var test = @" new partial void Goo(); "; ParseAndValidate(test); } [Fact] public void ImplementingDeclarationOfPartialMethod() { var test = @" partial void Goo(){}; "; ParseAndValidate(test, new ErrorDescription { Code = 1597, Line = 2, Column = 21 }); } [Fact] public void EnumDeclaration() { var test = @" partial enum en {}; "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial enum en {}; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1), // (2,14): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial enum en {}; Diagnostic(ErrorCode.ERR_PartialMisplaced, "en").WithLocation(2, 14)); } [Fact] public void UsingPartial() { var tree = UsingTree(@" partial = partial; partial partial; partial partial = partial; partial Goo { get; } partial partial Goo { get; } partial partial[] Goo { get; } partial partial<int> Goo { get; } partial Goo() { } partial partial Goo() { } partial partial[] Goo() { } partial partial<int> Goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PartialKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } } #endregion #region Attributes [Fact] public void Attributes() { var tree = UsingTree(@" [assembly: Goo] [module: Bar] [Goo] void goo() { } [Bar] int x; [Baz] class C { } [Baz] struct C { } [Baz] enum C { } [Baz] delegate D(); "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.AttributeTargetSpecifier); { N(SyntaxKind.AssemblyKeyword); N(SyntaxKind.ColonToken); } N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.AttributeTargetSpecifier); { N(SyntaxKind.ModuleKeyword); N(SyntaxKind.ColonToken); } N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.StructDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.StructKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EnumDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.EnumKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.DelegateDeclaration); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DelegateKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } M(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Fields [Fact] public void Fields() { var tree = UsingTree(@" int x; volatile int x; readonly int x; static int x; fixed int x[10]; "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VolatileKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.ReadOnlyKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.StaticKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.FixedKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } #endregion #region Multiplication [Fact] public void Multiplication() { // pointer decl string test = @"a.b * c;"; ParseAndValidate(test, TestOptions.Regular9); // pointer decl test = @"a.b * c"; ParseAndValidate(test, TestOptions.Regular9, new[] { new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 1, Column = 8 } }); // expected ';' // multiplication test = @"a.b * c;"; ParseAndValidate(test, TestOptions.Script); // multiplication test = @"a.b * c;"; ParseAndValidate(test, TestOptions.Script); // multiplication test = @"a.b * c"; ParseAndValidate(test, TestOptions.Script); } [Fact] public void Multiplication_Interactive_Semicolon() { var tree = UsingTree(@"a * b;", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Multiplication_Interactive_NoSemicolon() { var tree = UsingTree(@"a * b", TestOptions.Script); Assert.False(tree.GetCompilationUnitRoot().ContainsDiagnostics); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Multiplication_Complex() { var tree = UsingTree(@"a<t>.n * f(x)", TestOptions.Script); Assert.False(tree.GetCompilationUnitRoot().ContainsDiagnostics); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.AsteriskToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseParenToken); } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } #endregion #region Ternary Operator // T is a type name, including: // a<b> // a<b>.c // a[] // a[,,] // a<b>.b[] // a<b,c>.d[] // etc. // // Ts is a comma separated list of type names // field decls: // T ? idf; // T ? idf, ... // T ? idf = <expr>, ... // T ? idf = <expr>; // property decls: // T ? idf { ... // T ? idf<Ts> { ... // T ? idf<Ts>. ... { ... // method decls: // T ? idf() where ... // T ? idf() { ... // T ? idf(T idf ... // T ? idf.idf(T idf ... // T ? idf<Ts>(T idf ... // T ? idf<Ts>.idf<Ts>. ...(T idf ... // T ? idf([Attr]T idf ... // T ? idf([Attr]T ? idf ... // T ? idf(out T ? idf ... // T ? idf(T ? idf, ... // T ? idf(this idf ... // T ? idf(params ... // T ? idf(__arglist ... // expressions: // T ? non-idf // T ? idf // T ? idf. ... // T ? idf[ ... // T ? idf< // T ? idf<T // T ? idf<Ts> // T ? idf<Ts>. // T ? idf<Ts>. ... ( // T ? idf( // T ? idf(a // T ? idf(a) // T ? idf(this // T ? idf(this = ... // T ? idf(this[ ... // T ? idf(this. ... // T ? idf(this< ... // T ? idf(this( ... // T ? idf(ref a) // T ? idf() // T ? idf(); // method without body must be abstract, which is probably not what user intended to write in interactive // T ? idf(T ? idf // T ? idf(x: 1, y: 2) : c(z: 3) // T ? idf => { } : c => { } // T ? idf => (d ? e => 1 : f => 2)(3) : c => 2 // T ? idf = <expr> // T ? b = x ? y : z : w // fields // [Fact] public void Ternary_FieldDecl_Semicolon1() { var tree = UsingTree(@"T ? a;", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_FieldDecl_Semicolon2() { var tree = UsingTree(@"T ? b, c = 1;", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_FieldDecl_Semicolon3() { var tree = UsingTree(@"T ? b = d => { };", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_FieldDecl_Semicolon4() { var tree = UsingTree(@"T ? b = x ? y : z;", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_FieldDecl_Comma1() { var tree = UsingTree(@"T ? a,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_FieldDecl_Comma2() { var tree = UsingTree(@"T ? a = 1,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } // properties // [Fact] public void Ternary_PropertyDecl1() { var tree = UsingTree(@"T ? a {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_PropertyDecl2() { var tree = UsingTree(@"T ? a.b {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_PropertyDecl3() { var tree = UsingTree(@"T ? a<T>.b {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_PropertyDecl4() { var tree = UsingTree(@"T ? a<T?>.b<S>.c {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } // methods // [Fact] public void Ternary_MethodDecl1() { var tree = UsingTree(@"T ? a() {", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl1_Where() { var tree = UsingTree(@"T ? a() where", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.TypeConstraint); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl2() { var tree = UsingTree(@"T ? a(T b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl3() { var tree = UsingTree(@"T ? a.b(T c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl4() { var tree = UsingTree(@"T ? a<A>.b<B>(C c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "b"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl5() { var tree = UsingTree(@"T ? a([Attr]C c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Attr"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl6() { var tree = UsingTree(@"T ? a([Attr(a = b)]c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Attr"); } N(SyntaxKind.AttributeArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AttributeArgument); { N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl7() { var tree = UsingTree(@"T ? a(out C c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.IdentifierToken, "c"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl8() { var tree = UsingTree(@"T ? a(C[] a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl9() { var tree = UsingTree(@"T ? a(params", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ParamsKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl10() { var tree = UsingTree(@"T ? a(out T ? b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.OutKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl11() { var tree = UsingTree(@"T ? a(ref T ? b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl12() { var tree = UsingTree(@"T ? a(params T ? b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ParamsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl13() { var tree = UsingTree(@"T ? a([Attr]T ? b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Attr"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl14A() { var tree = UsingTree(@"T ? a(T ? b,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CommaToken); M(SyntaxKind.Parameter); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl14B() { var tree = UsingTree(@"T ? a(T ? b)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl15() { var tree = UsingTree(@"T ? a(T c)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl16() { var tree = UsingTree(@"T ? a(this c d", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ThisKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IdentifierToken, "d"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl17() { var tree = UsingTree(@"T ? a(ref out T a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl18() { var tree = UsingTree(@"T ? a(int a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl19() { var tree = UsingTree(@"T ? a(ref int a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.RefKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl20() { var tree = UsingTree(@"T ? a(T a =", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl21() { var tree = UsingTree(@"T ? a(T[,] a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CommaToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl22() { var tree = UsingTree(@"T ? a(T?[10] a)"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "10"); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } /// <summary> /// Prefer method declaration over an expression. /// </summary> [Fact] public void Ternary_MethodDecl_GenericAmbiguity1() { var tree = UsingTree(@"T ? m(a < b, c > d)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "m"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } // expressions // [Fact] public void Ternary_Expression1() { var tree = UsingTree(@"T ? 1", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression2() { var tree = UsingTree(@"T ? a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression3() { var tree = UsingTree(@"T ? a.", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression4() { var tree = UsingTree(@"T ? a[", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.CloseBracketToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression5() { var tree = UsingTree(@"T ? a<", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression6() { var tree = UsingTree(@"T ? a<b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression7() { var tree = UsingTree(@"T ? a<b>", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.GreaterThanToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression8() { var tree = UsingTree(@"T ? a<b,c>", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression9() { var tree = UsingTree(@"T ? a<b>.", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression10() { var tree = UsingTree(@"T ? a<b>.c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression11() { var tree = UsingTree(@"T ? a<b>.c(", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression12() { var tree = UsingTree(@"T ? a(", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression13() { var tree = UsingTree(@"T ? a.b(", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression14() { var tree = UsingTree(@"T ? m(c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression15() { var tree = UsingTree(@"T ? m(c,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression16() { var tree = UsingTree(@"T ? m(c:", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.ColonToken); } M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression17() { var tree = UsingTree(@"T ? m(c?", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression18() { var tree = UsingTree(@"T ? m(c? a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression19() { var tree = UsingTree(@"T ? m(c? a =", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression20() { var tree = UsingTree(@"T ? m(c? a = b ?", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.QuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression21() { var tree = UsingTree(@"T ? m()", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression22() { var tree = UsingTree(@"T ? m(a)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression23() { var tree = UsingTree(@"T ? m();", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression24() { var tree = UsingTree(@"T ? m(a);", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression25() { var tree = UsingTree(@"T ? m(x: 1", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression26() { var tree = UsingTree(@"T ? m(x: 1, y: a ? b : c)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression27() { var tree = UsingTree(@"T ? u => { } : v => { }", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "u"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "v"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression28() { var tree = UsingTree(@"T ? u => (d ? e => 1 : f => 2)(3) : c => 2", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "u"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression30() { var tree = UsingTree(@"T ? a ?", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression31() { var tree = UsingTree(@"T ? a =", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression32() { var tree = UsingTree(@"T ? a = b", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression33() { var tree = UsingTree(@"T ? a = b : ", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression34() { var tree = UsingTree(@"T ? m(out c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression35() { var tree = UsingTree(@"T ? m(ref c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression36() { var tree = UsingTree(@"T ? m(ref out", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression37() { var tree = UsingTree(@"T ? m(ref out c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression38() { var tree = UsingTree(@"T ? m(this", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression39() { var tree = UsingTree(@"T ? m(this.", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression40() { var tree = UsingTree(@"T ? m(this<", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.LessThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression41() { var tree = UsingTree(@"T ? m(this[", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression41A() { var tree = UsingTree(@"T ? m(this a", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } } M(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression42() { var tree = UsingTree(@"T ? m(this(", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression43() { var tree = UsingTree(@"T ? m(T[", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); M(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression44() { var tree = UsingTree(@"T ? m(T[1", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression45() { var tree = UsingTree(@"T ? m(T[1]", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_MethodDecl46() { var tree = UsingTree(@"T ? a(T ? a =", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression47() { var tree = UsingTree(@"T ? a(T)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression48() { var tree = UsingTree(@"T ? a(ref int.MaxValue)", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression49() { var tree = UsingTree(@"T ? a(ref a,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression50() { var tree = UsingTree(@"T ? a(,", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression51() { var tree = UsingTree(@"T ? a(T ? b[1] : b[2])", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ColonToken); N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBracketToken); } } } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_Expression52() { var tree = UsingTree(@" T ? f(a ? b : c) "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } /// <summary> /// Trailing colon turns a method declaration into an expression. /// </summary> [Fact] public void Ternary_Expression_GenericAmbiguity1() { var tree = UsingTree(@"T ? m(a < b, c > d) :", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "m"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_WithQuery_FieldDecl1() { var tree = UsingTree(@" T? from; "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void Ternary_WithQuery_Expression1() { var tree = UsingTree(@" T ? from "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_WithQuery_Expression2() { var tree = UsingTree(@" T ? from x "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void Ternary_WithQuery_Expression3() { var tree = UsingTree(@" T ? f(from "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } /// <summary> /// Assume that "from" usually doesn't bind to a type and is rather a start of a query. /// </summary> [Fact] public void Ternary_WithQuery_Expression4() { var tree = UsingTree(@" T ? f(from x "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } #endregion #region Queries [Fact] public void From_Identifier() { var tree = UsingTree(@"from", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_FieldDecl() { var tree = UsingTree(@"from c", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void From_FieldDecl2() { var tree = UsingTree(@"from x,"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_FieldDecl3() { var tree = UsingTree(@"from x;"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void From_FieldDecl4() { var tree = UsingTree(@"from x ="); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_FieldDecl5() { var tree = UsingTree(@"from x["); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } } M(SyntaxKind.CloseBracketToken); } } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl1() { var tree = UsingTree(@"from c("); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl2() { var tree = UsingTree(@"from a<"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); M(SyntaxKind.TypeParameter); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.GreaterThanToken); } M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl3() { var tree = UsingTree(@"from a."); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl4() { var tree = UsingTree(@"from a::"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } M(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_MethodDecl5() { var tree = UsingTree(@"from global::"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "global"); } M(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.ParameterList); { M(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_PropertyDecl1() { var tree = UsingTree(@"from c {"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "from"); } N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query1() { var tree = UsingTree(@"from c d"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IdentifierToken, "d"); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query2() { var tree = UsingTree(@"from x* a"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.IdentifierToken, "a"); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query3() { var tree = UsingTree(@"from x? a"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.IdentifierToken, "a"); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query4() { var tree = UsingTree(@"from x[] a"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "a"); M(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query5() { var tree = UsingTree(@"from goo in"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void From_Query6() { var tree = UsingTree(@"from goo.bar in"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "goo"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "bar"); } } M(SyntaxKind.IdentifierToken); N(SyntaxKind.InKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.QueryBody); { M(SyntaxKind.SelectClause); { M(SyntaxKind.SelectKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } #endregion #region Global statement separators /// <summary> /// Comma after a global statement is ignored and a new global statement is parsed. /// </summary> [Fact] public void GlobalStatementSeparators_Comma1() { var tree = UsingTree("a < b,c.", TestOptions.Script); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_Comma2() { var tree = UsingTree(@" a < b, void goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_ClosingParen() { var tree = UsingTree(@" a < b) void goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_ClosingBracket() { var tree = UsingTree(@" a < b] void goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_ClosingBrace() { var tree = UsingTree(@" a < b} void goo() { } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } M(SyntaxKind.SemicolonToken); } } N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalStatementSeparators_NonAsciiCharacter() { var test = @" H �oz "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 3 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnexpectedCharacter, Line = 2, Column = 3 }); } [Fact] public void GlobalStatementSeparators_UnicodeCharacter() { var test = @" int नुसौप्रख्यातनिदेशकपुरानी "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 29 }); } [Fact] public void GlobalStatementSeparators_Missing() { var test = @" using System; int a Console.Goo() "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 3, Column = 6 }); } #endregion #region Invalid Keywords [Fact] public void OperatorError() { var test = @"operator"; ParseAndValidate(test, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1031, Line = 1, Column = 9 }, new ErrorDescription { Code = 1003, Line = 1, Column = 1 }, new ErrorDescription { Code = 1026, Line = 1, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 1, Column = 9 }); } [Fact] public void OperatorImplicitError() { var test = @"implicit"; ParseAndValidate(test, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1031, Line = 1, Column = 9 }, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1026, Line = 1, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 1, Column = 9 }); } [Fact] public void OperatorExplicitError() { var test = @"explicit"; ParseAndValidate(test, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1031, Line = 1, Column = 9 }, new ErrorDescription { Code = 1003, Line = 1, Column = 9 }, new ErrorDescription { Code = 1026, Line = 1, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 1, Column = 9 }); } #endregion [Fact] public void FieldDeclaration() { var test = @" volatile int x; const int w; readonly int y; static int z; "; ParseAndValidate(test, new ErrorDescription { Code = 145, Line = 3, Column = 11 }); } /// bug="3782" project = "Roslyn" [Fact] public void ClassDeclaration() { var test = @" class C { } static class C2 { } partial class C3 { } "; ParseAndValidate(test); } /// bug="3783" project = "Roslyn" [Fact] public void InterfaceDeclaration() { var test = @" interface IC { } "; ParseAndValidate(test); } [Fact] public void TopLevelXML() { var test = @" <Expects Status=success></Expects> "; ParseAndValidate(test, new ErrorDescription { Code = 1525, Line = 2, Column = 1 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 10 }, new ErrorDescription { Code = 1525, Line = 2, Column = 25 }, new ErrorDescription { Code = 1525, Line = 2, Column = 26 }, new ErrorDescription { Code = 1733, Line = 2, Column = 35 }); } [Fact] public void NotIncorrectKeyword() { var test = @" parial class Test { } "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 8 }); } [Fact] public void Keyword() { var test = @" p class A { } "; ParseAndValidate(test, new ErrorDescription { Code = (int)ErrorCode.ERR_SemicolonExpected, Line = 2, Column = 3 }); } [WorkItem(528532, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528532")] [Fact] public void ParseForwardSlash() { var test = @"/"; var tree = SyntaxFactory.ParseSyntaxTree(test, options: TestOptions.Script); Assert.Equal(1, tree.GetCompilationUnitRoot().ChildNodes().Count()); Assert.Equal(SyntaxKind.GlobalStatement, tree.GetCompilationUnitRoot().ChildNodes().ToList()[0].Kind()); } [WorkItem(541164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541164")] [Fact] public void CS1733ERR_ExpressionExpected() { var test = @"Console.WriteLine(""Hello"")?"; ParseAndValidate(test, new ErrorDescription { Code = 1733, Line = 1, Column = 28 }, new ErrorDescription { Code = 1003, Line = 1, Column = 28 }, new ErrorDescription { Code = 1733, Line = 1, Column = 28 }); } #region Shebang [Fact] public void Shebang() { var command = "/usr/bin/env csi"; var tree = ParseAndValidate($"#!{command}", TestOptions.Script); var root = tree.GetCompilationUnitRoot(); Assert.Empty(root.ChildNodes()); var eof = root.EndOfFileToken; Assert.Equal(SyntaxKind.EndOfFileToken, eof.Kind()); var trivia = eof.GetLeadingTrivia().Single(); TestShebang(trivia, command); Assert.True(root.ContainsDirectives); TestShebang(root.GetDirectives().Single(), command); tree = ParseAndValidate($"#! {command}\r\n ", TestOptions.Script); root = tree.GetCompilationUnitRoot(); Assert.Empty(root.ChildNodes()); eof = root.EndOfFileToken; Assert.Equal(SyntaxKind.EndOfFileToken, eof.Kind()); var leading = eof.GetLeadingTrivia().ToArray(); Assert.Equal(2, leading.Length); Assert.Equal(SyntaxKind.ShebangDirectiveTrivia, leading[0].Kind()); Assert.Equal(SyntaxKind.WhitespaceTrivia, leading[1].Kind()); TestShebang(leading[0], command); Assert.True(root.ContainsDirectives); TestShebang(root.GetDirectives().Single(), command); tree = ParseAndValidate( $@"#!{command} Console.WriteLine(""Hi!"");", TestOptions.Script); root = tree.GetCompilationUnitRoot(); var statement = root.ChildNodes().Single(); Assert.Equal(SyntaxKind.GlobalStatement, statement.Kind()); trivia = statement.GetLeadingTrivia().Single(); TestShebang(trivia, command); Assert.True(root.ContainsDirectives); TestShebang(root.GetDirectives().Single(), command); } [Fact] public void ShebangNotFirstCharacter() { ParseAndValidate(" #!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 1, Column = 2 }); ParseAndValidate("\n#!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 2, Column = 1 }); ParseAndValidate("\r\n#!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 2, Column = 1 }); ParseAndValidate("#!/bin/sh\r\n#!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 2, Column = 1 }); ParseAndValidate("a #!/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_BadDirectivePlacement, Line = 1, Column = 3 }); } [Fact] public void ShebangNoBang() { ParseAndValidate("#/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 1, Column = 1 }); } [Fact] public void ShebangSpaceBang() { ParseAndValidate("# !/usr/bin/env csi", TestOptions.Script, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 1, Column = 1 }); } [Fact] public void ShebangInComment() { var tree = ParseAndValidate("//#!/usr/bin/env csi", TestOptions.Script); var root = tree.GetCompilationUnitRoot(); Assert.Empty(root.ChildNodes()); var eof = root.EndOfFileToken; Assert.Equal(SyntaxKind.EndOfFileToken, eof.Kind()); Assert.Equal(SyntaxKind.SingleLineCommentTrivia, eof.GetLeadingTrivia().Single().Kind()); } [Fact] public void ShebangNotInScript() { ParseAndValidate("#!/usr/bin/env csi", TestOptions.Regular, new ErrorDescription { Code = (int)ErrorCode.ERR_PPDirectiveExpected, Line = 1, Column = 1 }); } private void TestShebang(SyntaxTrivia trivia, string expectedSkippedText) { Assert.True(trivia.IsDirective); Assert.Equal(SyntaxKind.ShebangDirectiveTrivia, trivia.Kind()); Assert.True(trivia.HasStructure); TestShebang((ShebangDirectiveTriviaSyntax)trivia.GetStructure(), expectedSkippedText); } private void TestShebang(DirectiveTriviaSyntax directive, string expectedSkippedText) { var shebang = (ShebangDirectiveTriviaSyntax)directive; Assert.False(shebang.HasStructuredTrivia); Assert.Equal(SyntaxKind.HashToken, shebang.HashToken.Kind()); Assert.Equal(SyntaxKind.ExclamationToken, shebang.ExclamationToken.Kind()); var endOfDirective = shebang.EndOfDirectiveToken; Assert.Equal(SyntaxKind.EndOfDirectiveToken, endOfDirective.Kind()); Assert.Equal(0, endOfDirective.Span.Length); var skippedText = endOfDirective.LeadingTrivia.Single(); Assert.Equal(SyntaxKind.PreprocessingMessageTrivia, skippedText.Kind()); Assert.Equal(expectedSkippedText, skippedText.ToString()); } #endregion } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// this class maintain contextual information such as /// indentation of current position, based token to follow in current position and etc. /// </summary> internal partial class FormattingContext { private readonly AbstractFormatEngine _engine; private readonly TokenStream _tokenStream; // interval tree for inseparable regions (Span to indentation data) // due to dependencies, each region defined in the data can't be formatted independently. private readonly ContextIntervalTree<RelativeIndentationData, FormattingContextIntervalIntrospector> _relativeIndentationTree; // interval tree for each operations. // given a span in the tree, it returns data (indentation, anchor delta, etc) to be applied for the span private readonly ContextIntervalTree<IndentationData, FormattingContextIntervalIntrospector> _indentationTree; private readonly ContextIntervalTree<SuppressWrappingData, SuppressIntervalIntrospector> _suppressWrappingTree; private readonly ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector> _suppressSpacingTree; private readonly ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector> _suppressFormattingTree; private readonly ContextIntervalTree<AnchorData, FormattingContextIntervalIntrospector> _anchorTree; // anchor token to anchor data map. // unlike anchorTree that would return anchor data for given span in the tree, it will return // anchorData based on key which is anchor token. private readonly SegmentedDictionary<SyntaxToken, AnchorData> _anchorBaseTokenMap; // hashset to prevent duplicate entries in the trees. private readonly HashSet<TextSpan> _indentationMap; private readonly HashSet<TextSpan> _suppressWrappingMap; private readonly HashSet<TextSpan> _suppressSpacingMap; private readonly HashSet<TextSpan> _suppressFormattingMap; private readonly HashSet<TextSpan> _anchorMap; // used for selection based formatting case. it contains operations that will define // what indentation to use as a starting indentation. (we always use 0 for formatting whole tree case) private List<IndentBlockOperation> _initialIndentBlockOperations; public FormattingContext(AbstractFormatEngine engine, TokenStream tokenStream) { Contract.ThrowIfNull(engine); Contract.ThrowIfNull(tokenStream); _engine = engine; _tokenStream = tokenStream; _relativeIndentationTree = new ContextIntervalTree<RelativeIndentationData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _indentationTree = new ContextIntervalTree<IndentationData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _suppressWrappingTree = new ContextIntervalTree<SuppressWrappingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _suppressSpacingTree = new ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _suppressFormattingTree = new ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _anchorTree = new ContextIntervalTree<AnchorData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _anchorBaseTokenMap = new SegmentedDictionary<SyntaxToken, AnchorData>(); _indentationMap = new HashSet<TextSpan>(); _suppressWrappingMap = new HashSet<TextSpan>(); _suppressSpacingMap = new HashSet<TextSpan>(); _suppressFormattingMap = new HashSet<TextSpan>(); _anchorMap = new HashSet<TextSpan>(); _initialIndentBlockOperations = new List<IndentBlockOperation>(); } public void Initialize( ChainedFormattingRules formattingRules, SyntaxToken startToken, SyntaxToken endToken, CancellationToken cancellationToken) { var rootNode = this.TreeData.Root; if (_tokenStream.IsFormattingWholeDocument) { // if we are trying to format whole document, there is no reason to get initial context. just set // initial indentation. var data = new RootIndentationData(rootNode); _indentationTree.AddIntervalInPlace(data); _indentationMap.Add(data.TextSpan); return; } var initialContextFinder = new InitialContextFinder(_tokenStream, formattingRules, rootNode); var (indentOperations, suppressOperations) = initialContextFinder.Do(startToken, endToken); if (indentOperations != null) { var indentationOperations = indentOperations; var initialOperation = indentationOperations[0]; var baseIndentationFinder = new BottomUpBaseIndentationFinder( formattingRules, this.Options.GetOption(FormattingOptions2.TabSize), this.Options.GetOption(FormattingOptions2.IndentationSize), _tokenStream, _engine.SyntaxFacts); var initialIndentation = baseIndentationFinder.GetIndentationOfCurrentPosition( rootNode, initialOperation, t => _tokenStream.GetCurrentColumn(t), cancellationToken); var data = new SimpleIndentationData(initialOperation.TextSpan, initialIndentation); _indentationTree.AddIntervalInPlace(data); _indentationMap.Add(data.TextSpan); // hold onto initial operations _initialIndentBlockOperations = indentationOperations; } suppressOperations?.Do(o => this.AddInitialSuppressOperation(o)); } public void AddIndentBlockOperations( List<IndentBlockOperation> operations, CancellationToken cancellationToken) { Contract.ThrowIfNull(operations); // if there is no initial block operations if (_initialIndentBlockOperations.Count <= 0) { // sort operations and add them to interval tree operations.Sort(CommonFormattingHelpers.IndentBlockOperationComparer); operations.Do(o => { cancellationToken.ThrowIfCancellationRequested(); this.AddIndentBlockOperation(o); }); return; } var baseSpan = _initialIndentBlockOperations[0].TextSpan; // indentation tree must build up from inputs that are in right order except initial indentation. // merge indentation operations from two places (initial operations for current selection, and nodes inside of selections) // sort it in right order and apply them to tree var count = _initialIndentBlockOperations.Count - 1 + operations.Count; var mergedList = new List<IndentBlockOperation>(count); // initial operations are already sorted, just add, no need to filter for (var i = 1; i < _initialIndentBlockOperations.Count; i++) { mergedList.Add(_initialIndentBlockOperations[i]); } for (var i = 0; i < operations.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); // filter out operations whose position is before the base indentation var operationSpan = operations[i].TextSpan; if (operationSpan.Start < baseSpan.Start || operationSpan.Contains(baseSpan)) { continue; } mergedList.Add(operations[i]); } mergedList.Sort(CommonFormattingHelpers.IndentBlockOperationComparer); mergedList.Do(o => { cancellationToken.ThrowIfCancellationRequested(); this.AddIndentBlockOperation(o); }); } public void AddIndentBlockOperation(IndentBlockOperation operation) { var intervalTreeSpan = operation.TextSpan; // don't add stuff if it is empty if (intervalTreeSpan.IsEmpty || _indentationMap.Contains(intervalTreeSpan)) { return; } // relative indentation case where indentation depends on other token if (operation.IsRelativeIndentation) { var effectiveBaseToken = operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken) : operation.BaseToken; var inseparableRegionStartingPosition = effectiveBaseToken.FullSpan.Start; var relativeIndentationGetter = new Lazy<int>(() => { var baseIndentationDelta = operation.GetAdjustedIndentationDelta(_engine.SyntaxFacts, TreeData.Root, effectiveBaseToken); var indentationDelta = baseIndentationDelta * this.Options.GetOption(FormattingOptions2.IndentationSize); // baseIndentation is calculated for the adjusted token if option is RelativeToFirstTokenOnBaseTokenLine var baseIndentation = _tokenStream.GetCurrentColumn(operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken) : operation.BaseToken); return baseIndentation + indentationDelta; }, isThreadSafe: true); // set new indentation var relativeIndentationData = new RelativeIndentationData(inseparableRegionStartingPosition, intervalTreeSpan, operation, relativeIndentationGetter); _indentationTree.AddIntervalInPlace(relativeIndentationData); _relativeIndentationTree.AddIntervalInPlace(relativeIndentationData); _indentationMap.Add(intervalTreeSpan); return; } // absolute position case if (operation.Option.IsOn(IndentBlockOption.AbsolutePosition)) { _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, operation.IndentationDeltaOrPosition)); _indentationMap.Add(intervalTreeSpan); return; } // regular indentation case where indentation is based on its previous indentation var indentationData = _indentationTree.GetSmallestContainingInterval(operation.TextSpan.Start, 0); if (indentationData == null) { // no previous indentation var indentation = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, indentation)); _indentationMap.Add(intervalTreeSpan); return; } // get indentation based on its previous indentation var indentationGetter = new Lazy<int>(() => { var indentationDelta = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); return indentationData.Indentation + indentationDelta; }, isThreadSafe: true); // set new indentation _indentationTree.AddIntervalInPlace(new LazyIndentationData(intervalTreeSpan, indentationGetter)); _indentationMap.Add(intervalTreeSpan); } public void AddInitialSuppressOperation(SuppressOperation operation) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } var onSameLine = _tokenStream.TwoTokensOriginallyOnSameLine(operation.StartToken, operation.EndToken); AddSuppressOperation(operation, onSameLine); } public void AddSuppressOperations( List<SuppressOperation> operations, CancellationToken cancellationToken) { var valuePairs = new SegmentedArray<(SuppressOperation operation, bool shouldSuppress, bool onSameLine)>(operations.Count); // TODO: think about a way to figure out whether it is already suppressed and skip the expensive check below. for (var i = 0; i < operations.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); var operation = operations[i]; // if an operation contains elastic trivia itself and the operation is not marked to ignore the elastic trivia // ignore the operation if (operation.ContainsElasticTrivia(_tokenStream) && !operation.Option.IsOn(SuppressOption.IgnoreElasticWrapping)) { // don't bother to calculate line alignment between tokens valuePairs[i] = (operation, shouldSuppress: false, onSameLine: false); continue; } var onSameLine = _tokenStream.TwoTokensOriginallyOnSameLine(operation.StartToken, operation.EndToken); valuePairs[i] = (operation, shouldSuppress: true, onSameLine); } foreach (var (operation, shouldSuppress, onSameLine) in valuePairs) { cancellationToken.ThrowIfCancellationRequested(); if (shouldSuppress) { AddSuppressOperation(operation, onSameLine); } } } private void AddSuppressOperation(SuppressOperation operation, bool onSameLine) { AddSpacingSuppressOperation(operation, onSameLine); AddFormattingSuppressOperation(operation); AddWrappingSuppressOperation(operation, onSameLine); } private void AddSpacingSuppressOperation(SuppressOperation operation, bool twoTokensOnSameLine) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } // we might need to merge bits with enclosing suppress flag var option = operation.Option; if (!option.IsMaskOn(SuppressOption.NoSpacing) || _suppressSpacingMap.Contains(operation.TextSpan)) { return; } if (!(option.IsOn(SuppressOption.NoSpacingIfOnSingleLine) && twoTokensOnSameLine) && !(option.IsOn(SuppressOption.NoSpacingIfOnMultipleLine) && !twoTokensOnSameLine)) { return; } var data = new SuppressSpacingData(operation.TextSpan); _suppressSpacingMap.Add(operation.TextSpan); _suppressSpacingTree.AddIntervalInPlace(data); } private void AddFormattingSuppressOperation(SuppressOperation operation) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } // we might need to merge bits with enclosing suppress flag var option = operation.Option; if (!option.IsOn(SuppressOption.DisableFormatting) || _suppressFormattingMap.Contains(operation.TextSpan)) { return; } var data = new SuppressSpacingData(operation.TextSpan); _suppressFormattingMap.Add(operation.TextSpan); _suppressFormattingTree.AddIntervalInPlace(data); } private void AddWrappingSuppressOperation(SuppressOperation operation, bool twoTokensOnSameLine) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } var option = operation.Option; if (!option.IsMaskOn(SuppressOption.NoWrapping) || _suppressWrappingMap.Contains(operation.TextSpan)) { return; } if (!(option.IsOn(SuppressOption.NoWrappingIfOnSingleLine) && twoTokensOnSameLine) && !(option.IsOn(SuppressOption.NoWrappingIfOnMultipleLine) && !twoTokensOnSameLine)) { return; } var ignoreElastic = option.IsMaskOn(SuppressOption.IgnoreElasticWrapping) || !operation.ContainsElasticTrivia(_tokenStream); var data = new SuppressWrappingData(operation.TextSpan, ignoreElastic: ignoreElastic); _suppressWrappingMap.Add(operation.TextSpan); _suppressWrappingTree.AddIntervalInPlace(data); } public void AddAnchorIndentationOperation(AnchorIndentationOperation operation) { // don't add stuff if it is empty if (operation.TextSpan.IsEmpty || _anchorMap.Contains(operation.TextSpan) || _anchorBaseTokenMap.ContainsKey(operation.AnchorToken)) { return; } var originalSpace = _tokenStream.GetOriginalColumn(operation.StartToken); var data = new AnchorData(operation, originalSpace); _anchorTree.AddIntervalInPlace(data); _anchorBaseTokenMap.Add(operation.AnchorToken, data); _anchorMap.Add(operation.TextSpan); } [Conditional("DEBUG")] private static void DebugCheckEmpty<T, TIntrospector>(ContextIntervalTree<T, TIntrospector> tree, TextSpan textSpan) where TIntrospector : struct, IIntervalIntrospector<T> { var intervals = tree.GetIntervalsThatContain(textSpan.Start, textSpan.Length); Contract.ThrowIfFalse(intervals.Length == 0); } public int GetBaseIndentation(SyntaxToken token) => GetBaseIndentation(token.SpanStart); public int GetBaseIndentation(int position) { var indentationData = _indentationTree.GetSmallestContainingInterval(position, 0); if (indentationData == null) { DebugCheckEmpty(_indentationTree, new TextSpan(position, 0)); return 0; } return indentationData.Indentation; } public IEnumerable<IndentBlockOperation> GetAllRelativeIndentBlockOperations() => _relativeIndentationTree.GetIntervalsThatIntersectWith(this.TreeData.StartPosition, this.TreeData.EndPosition, new FormattingContextIntervalIntrospector()).Select(i => i.Operation); public bool TryGetEndTokenForRelativeIndentationSpan(SyntaxToken token, int maxChainDepth, out SyntaxToken endToken, CancellationToken cancellationToken) { endToken = default; var depth = 0; while (true) { cancellationToken.ThrowIfCancellationRequested(); if (depth++ > maxChainDepth) { return false; } var span = token.Span; var indentationData = _relativeIndentationTree.GetSmallestContainingInterval(span.Start, 0); if (indentationData == null) { // this means the given token is not inside of inseparable regions endToken = token; return true; } // recursively find the end token outside of inseparable regions token = indentationData.EndToken.GetNextToken(includeZeroWidth: true); if (token.RawKind == 0) { // reached end of tree return true; } } } private AnchorData? GetAnchorData(SyntaxToken token) { var span = token.Span; var anchorData = _anchorTree.GetSmallestContainingInterval(span.Start, 0); if (anchorData == null) { // no anchor DebugCheckEmpty(_anchorTree, new TextSpan(span.Start, 0)); return null; } return anchorData; } public int GetAnchorDeltaFromOriginalColumn(SyntaxToken token) { var anchorData = GetAnchorData(token); if (anchorData == null) { return 0; } var currentColumn = _tokenStream.GetCurrentColumn(anchorData.AnchorToken); return currentColumn - anchorData.OriginalColumn; } public SyntaxToken GetAnchorToken(SyntaxToken token) { var anchorData = GetAnchorData(token); if (anchorData == null) { return default; } return anchorData.AnchorToken; } public int GetDeltaFromPreviousChangesMap(SyntaxToken token, Dictionary<SyntaxToken, int> previousChangesMap) { // no changes if (!previousChangesMap.ContainsKey(token)) { return 0; } var currentColumn = _tokenStream.GetCurrentColumn(token); return currentColumn - previousChangesMap[token]; } public SyntaxToken GetEndTokenForAnchorSpan(TokenData tokenData) { // consider situation like below // // var q = from c in cs // where c > 1 // + // 2; // // if alignment operation moves "where" to align with "from" // we want to move "+" and "2" along with it (anchor operation) // // below we are trying to figure out up to which token ("2" in the above example) // we should apply the anchor operation var baseAnchorData = FindAnchorSpanOnSameLineAfterToken(tokenData); if (baseAnchorData == null) { return default; } // our anchor operation is very flexible so it not only let one anchor to contain others, it also // let anchors to overlap each other for whatever reasons // below, we will try to flat the overlapped anchor span, and find the last position (token) of that span // find other anchors overlapping with current anchor span var anchorData = _anchorTree.GetIntervalsThatOverlapWith(baseAnchorData.TextSpan.Start, baseAnchorData.TextSpan.Length); // among those anchors find the biggest end token var lastEndToken = baseAnchorData.EndToken; foreach (var interval in anchorData) { // anchor token is not in scope, move to next if (!baseAnchorData.TextSpan.IntersectsWith(interval.AnchorToken.Span)) { continue; } if (interval.EndToken.Span.End < lastEndToken.Span.End) { continue; } lastEndToken = interval.EndToken; } return lastEndToken; } private AnchorData? FindAnchorSpanOnSameLineAfterToken(TokenData tokenData) { // every token after given token on same line is implicitly dependent to the token. // check whether one of them is an anchor token. AnchorData? lastBaseAnchorData = null; while (tokenData.IndexInStream >= 0) { if (_anchorBaseTokenMap.TryGetValue(tokenData.Token, out var tempAnchorData)) { lastBaseAnchorData = tempAnchorData; } // tokenPairIndex is always 0 <= ... < TokenCount - 1 var tokenPairIndex = tokenData.IndexInStream; if (_tokenStream.TokenCount - 1 <= tokenPairIndex || _tokenStream.GetTriviaData(tokenPairIndex).SecondTokenIsFirstTokenOnLine) { return lastBaseAnchorData; } tokenData = tokenData.GetNextTokenData(); } return lastBaseAnchorData; } public bool IsWrappingSuppressed(TextSpan textSpan, bool containsElasticTrivia) { if (IsFormattingDisabled(textSpan)) { return true; } // use edge exclusive version of GetSmallestContainingInterval var data = _suppressWrappingTree.GetSmallestEdgeExclusivelyContainingInterval(textSpan.Start, textSpan.Length); if (data == null) { return false; } if (containsElasticTrivia && !data.IgnoreElastic) { return false; } return true; } public bool IsSpacingSuppressed(TextSpan textSpan, bool containsElasticTrivia) { if (IsFormattingDisabled(textSpan)) { return true; } // For spaces, never ignore elastic trivia because that can // generate incorrect code if (containsElasticTrivia) { return false; } // use edge exclusive version of GetSmallestContainingInterval var data = _suppressSpacingTree.GetSmallestEdgeExclusivelyContainingInterval(textSpan.Start, textSpan.Length); if (data == null) { return false; } return true; } public bool IsSpacingSuppressed(int pairIndex) { var token1 = _tokenStream.GetToken(pairIndex); var token2 = _tokenStream.GetToken(pairIndex + 1); var spanBetweenTwoTokens = TextSpan.FromBounds(token1.SpanStart, token2.Span.End); // this version of SpacingSuppressed will be called after all basic space operations are done. // so no more elastic trivia should have left out return IsSpacingSuppressed(spanBetweenTwoTokens, containsElasticTrivia: false); } public bool IsFormattingDisabled(TextSpan textSpan) => _suppressFormattingTree.HasIntervalThatIntersectsWith(textSpan.Start, textSpan.Length); public bool IsFormattingDisabled(int pairIndex) { var token1 = _tokenStream.GetToken(pairIndex); var token2 = _tokenStream.GetToken(pairIndex + 1); var spanBetweenTwoTokens = TextSpan.FromBounds(token1.SpanStart, token2.Span.End); return IsFormattingDisabled(spanBetweenTwoTokens); } public AnalyzerConfigOptions Options => _engine.Options; public TreeData TreeData => _engine.TreeData; public TokenStream TokenStream => _tokenStream; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting { /// <summary> /// this class maintain contextual information such as /// indentation of current position, based token to follow in current position and etc. /// </summary> internal partial class FormattingContext { private readonly AbstractFormatEngine _engine; private readonly TokenStream _tokenStream; // interval tree for inseparable regions (Span to indentation data) // due to dependencies, each region defined in the data can't be formatted independently. private readonly ContextIntervalTree<RelativeIndentationData, FormattingContextIntervalIntrospector> _relativeIndentationTree; // interval tree for each operations. // given a span in the tree, it returns data (indentation, anchor delta, etc) to be applied for the span private readonly ContextIntervalTree<IndentationData, FormattingContextIntervalIntrospector> _indentationTree; private readonly ContextIntervalTree<SuppressWrappingData, SuppressIntervalIntrospector> _suppressWrappingTree; private readonly ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector> _suppressSpacingTree; private readonly ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector> _suppressFormattingTree; private readonly ContextIntervalTree<AnchorData, FormattingContextIntervalIntrospector> _anchorTree; // anchor token to anchor data map. // unlike anchorTree that would return anchor data for given span in the tree, it will return // anchorData based on key which is anchor token. private readonly SegmentedDictionary<SyntaxToken, AnchorData> _anchorBaseTokenMap; // hashset to prevent duplicate entries in the trees. private readonly HashSet<TextSpan> _indentationMap; private readonly HashSet<TextSpan> _suppressWrappingMap; private readonly HashSet<TextSpan> _suppressSpacingMap; private readonly HashSet<TextSpan> _suppressFormattingMap; private readonly HashSet<TextSpan> _anchorMap; // used for selection based formatting case. it contains operations that will define // what indentation to use as a starting indentation. (we always use 0 for formatting whole tree case) private List<IndentBlockOperation> _initialIndentBlockOperations; public FormattingContext(AbstractFormatEngine engine, TokenStream tokenStream) { Contract.ThrowIfNull(engine); Contract.ThrowIfNull(tokenStream); _engine = engine; _tokenStream = tokenStream; _relativeIndentationTree = new ContextIntervalTree<RelativeIndentationData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _indentationTree = new ContextIntervalTree<IndentationData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _suppressWrappingTree = new ContextIntervalTree<SuppressWrappingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _suppressSpacingTree = new ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _suppressFormattingTree = new ContextIntervalTree<SuppressSpacingData, SuppressIntervalIntrospector>(new SuppressIntervalIntrospector()); _anchorTree = new ContextIntervalTree<AnchorData, FormattingContextIntervalIntrospector>(new FormattingContextIntervalIntrospector()); _anchorBaseTokenMap = new SegmentedDictionary<SyntaxToken, AnchorData>(); _indentationMap = new HashSet<TextSpan>(); _suppressWrappingMap = new HashSet<TextSpan>(); _suppressSpacingMap = new HashSet<TextSpan>(); _suppressFormattingMap = new HashSet<TextSpan>(); _anchorMap = new HashSet<TextSpan>(); _initialIndentBlockOperations = new List<IndentBlockOperation>(); } public void Initialize( ChainedFormattingRules formattingRules, SyntaxToken startToken, SyntaxToken endToken, CancellationToken cancellationToken) { var rootNode = this.TreeData.Root; if (_tokenStream.IsFormattingWholeDocument) { // if we are trying to format whole document, there is no reason to get initial context. just set // initial indentation. var data = new RootIndentationData(rootNode); _indentationTree.AddIntervalInPlace(data); _indentationMap.Add(data.TextSpan); return; } var initialContextFinder = new InitialContextFinder(_tokenStream, formattingRules, rootNode); var (indentOperations, suppressOperations) = initialContextFinder.Do(startToken, endToken); if (indentOperations != null) { var indentationOperations = indentOperations; var initialOperation = indentationOperations[0]; var baseIndentationFinder = new BottomUpBaseIndentationFinder( formattingRules, this.Options.GetOption(FormattingOptions2.TabSize), this.Options.GetOption(FormattingOptions2.IndentationSize), _tokenStream, _engine.SyntaxFacts); var initialIndentation = baseIndentationFinder.GetIndentationOfCurrentPosition( rootNode, initialOperation, t => _tokenStream.GetCurrentColumn(t), cancellationToken); var data = new SimpleIndentationData(initialOperation.TextSpan, initialIndentation); _indentationTree.AddIntervalInPlace(data); _indentationMap.Add(data.TextSpan); // hold onto initial operations _initialIndentBlockOperations = indentationOperations; } suppressOperations?.Do(o => this.AddInitialSuppressOperation(o)); } public void AddIndentBlockOperations( List<IndentBlockOperation> operations, CancellationToken cancellationToken) { Contract.ThrowIfNull(operations); // if there is no initial block operations if (_initialIndentBlockOperations.Count <= 0) { // sort operations and add them to interval tree operations.Sort(CommonFormattingHelpers.IndentBlockOperationComparer); operations.Do(o => { cancellationToken.ThrowIfCancellationRequested(); this.AddIndentBlockOperation(o); }); return; } var baseSpan = _initialIndentBlockOperations[0].TextSpan; // indentation tree must build up from inputs that are in right order except initial indentation. // merge indentation operations from two places (initial operations for current selection, and nodes inside of selections) // sort it in right order and apply them to tree var count = _initialIndentBlockOperations.Count - 1 + operations.Count; var mergedList = new List<IndentBlockOperation>(count); // initial operations are already sorted, just add, no need to filter for (var i = 1; i < _initialIndentBlockOperations.Count; i++) { mergedList.Add(_initialIndentBlockOperations[i]); } for (var i = 0; i < operations.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); // filter out operations whose position is before the base indentation var operationSpan = operations[i].TextSpan; if (operationSpan.Start < baseSpan.Start || operationSpan.Contains(baseSpan)) { continue; } mergedList.Add(operations[i]); } mergedList.Sort(CommonFormattingHelpers.IndentBlockOperationComparer); mergedList.Do(o => { cancellationToken.ThrowIfCancellationRequested(); this.AddIndentBlockOperation(o); }); } public void AddIndentBlockOperation(IndentBlockOperation operation) { var intervalTreeSpan = operation.TextSpan; // don't add stuff if it is empty if (intervalTreeSpan.IsEmpty || _indentationMap.Contains(intervalTreeSpan)) { return; } // relative indentation case where indentation depends on other token if (operation.IsRelativeIndentation) { var effectiveBaseToken = operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken) : operation.BaseToken; var inseparableRegionStartingPosition = effectiveBaseToken.FullSpan.Start; var relativeIndentationGetter = new Lazy<int>(() => { var baseIndentationDelta = operation.GetAdjustedIndentationDelta(_engine.SyntaxFacts, TreeData.Root, effectiveBaseToken); var indentationDelta = baseIndentationDelta * this.Options.GetOption(FormattingOptions2.IndentationSize); // baseIndentation is calculated for the adjusted token if option is RelativeToFirstTokenOnBaseTokenLine var baseIndentation = _tokenStream.GetCurrentColumn(operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine) ? _tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken) : operation.BaseToken); return baseIndentation + indentationDelta; }, isThreadSafe: true); // set new indentation var relativeIndentationData = new RelativeIndentationData(inseparableRegionStartingPosition, intervalTreeSpan, operation, relativeIndentationGetter); _indentationTree.AddIntervalInPlace(relativeIndentationData); _relativeIndentationTree.AddIntervalInPlace(relativeIndentationData); _indentationMap.Add(intervalTreeSpan); return; } // absolute position case if (operation.Option.IsOn(IndentBlockOption.AbsolutePosition)) { _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, operation.IndentationDeltaOrPosition)); _indentationMap.Add(intervalTreeSpan); return; } // regular indentation case where indentation is based on its previous indentation var indentationData = _indentationTree.GetSmallestContainingInterval(operation.TextSpan.Start, 0); if (indentationData == null) { // no previous indentation var indentation = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); _indentationTree.AddIntervalInPlace(new SimpleIndentationData(intervalTreeSpan, indentation)); _indentationMap.Add(intervalTreeSpan); return; } // get indentation based on its previous indentation var indentationGetter = new Lazy<int>(() => { var indentationDelta = operation.IndentationDeltaOrPosition * this.Options.GetOption(FormattingOptions2.IndentationSize); return indentationData.Indentation + indentationDelta; }, isThreadSafe: true); // set new indentation _indentationTree.AddIntervalInPlace(new LazyIndentationData(intervalTreeSpan, indentationGetter)); _indentationMap.Add(intervalTreeSpan); } public void AddInitialSuppressOperation(SuppressOperation operation) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } var onSameLine = _tokenStream.TwoTokensOriginallyOnSameLine(operation.StartToken, operation.EndToken); AddSuppressOperation(operation, onSameLine); } public void AddSuppressOperations( List<SuppressOperation> operations, CancellationToken cancellationToken) { var valuePairs = new SegmentedArray<(SuppressOperation operation, bool shouldSuppress, bool onSameLine)>(operations.Count); // TODO: think about a way to figure out whether it is already suppressed and skip the expensive check below. for (var i = 0; i < operations.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); var operation = operations[i]; // if an operation contains elastic trivia itself and the operation is not marked to ignore the elastic trivia // ignore the operation if (operation.ContainsElasticTrivia(_tokenStream) && !operation.Option.IsOn(SuppressOption.IgnoreElasticWrapping)) { // don't bother to calculate line alignment between tokens valuePairs[i] = (operation, shouldSuppress: false, onSameLine: false); continue; } var onSameLine = _tokenStream.TwoTokensOriginallyOnSameLine(operation.StartToken, operation.EndToken); valuePairs[i] = (operation, shouldSuppress: true, onSameLine); } foreach (var (operation, shouldSuppress, onSameLine) in valuePairs) { cancellationToken.ThrowIfCancellationRequested(); if (shouldSuppress) { AddSuppressOperation(operation, onSameLine); } } } private void AddSuppressOperation(SuppressOperation operation, bool onSameLine) { AddSpacingSuppressOperation(operation, onSameLine); AddFormattingSuppressOperation(operation); AddWrappingSuppressOperation(operation, onSameLine); } private void AddSpacingSuppressOperation(SuppressOperation operation, bool twoTokensOnSameLine) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } // we might need to merge bits with enclosing suppress flag var option = operation.Option; if (!option.IsMaskOn(SuppressOption.NoSpacing) || _suppressSpacingMap.Contains(operation.TextSpan)) { return; } if (!(option.IsOn(SuppressOption.NoSpacingIfOnSingleLine) && twoTokensOnSameLine) && !(option.IsOn(SuppressOption.NoSpacingIfOnMultipleLine) && !twoTokensOnSameLine)) { return; } var data = new SuppressSpacingData(operation.TextSpan); _suppressSpacingMap.Add(operation.TextSpan); _suppressSpacingTree.AddIntervalInPlace(data); } private void AddFormattingSuppressOperation(SuppressOperation operation) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } // we might need to merge bits with enclosing suppress flag var option = operation.Option; if (!option.IsOn(SuppressOption.DisableFormatting) || _suppressFormattingMap.Contains(operation.TextSpan)) { return; } var data = new SuppressSpacingData(operation.TextSpan); _suppressFormattingMap.Add(operation.TextSpan); _suppressFormattingTree.AddIntervalInPlace(data); } private void AddWrappingSuppressOperation(SuppressOperation operation, bool twoTokensOnSameLine) { // don't add stuff if it is empty if (operation == null || operation.TextSpan.IsEmpty) { return; } var option = operation.Option; if (!option.IsMaskOn(SuppressOption.NoWrapping) || _suppressWrappingMap.Contains(operation.TextSpan)) { return; } if (!(option.IsOn(SuppressOption.NoWrappingIfOnSingleLine) && twoTokensOnSameLine) && !(option.IsOn(SuppressOption.NoWrappingIfOnMultipleLine) && !twoTokensOnSameLine)) { return; } var ignoreElastic = option.IsMaskOn(SuppressOption.IgnoreElasticWrapping) || !operation.ContainsElasticTrivia(_tokenStream); var data = new SuppressWrappingData(operation.TextSpan, ignoreElastic: ignoreElastic); _suppressWrappingMap.Add(operation.TextSpan); _suppressWrappingTree.AddIntervalInPlace(data); } public void AddAnchorIndentationOperation(AnchorIndentationOperation operation) { // don't add stuff if it is empty if (operation.TextSpan.IsEmpty || _anchorMap.Contains(operation.TextSpan) || _anchorBaseTokenMap.ContainsKey(operation.AnchorToken)) { return; } var originalSpace = _tokenStream.GetOriginalColumn(operation.StartToken); var data = new AnchorData(operation, originalSpace); _anchorTree.AddIntervalInPlace(data); _anchorBaseTokenMap.Add(operation.AnchorToken, data); _anchorMap.Add(operation.TextSpan); } [Conditional("DEBUG")] private static void DebugCheckEmpty<T, TIntrospector>(ContextIntervalTree<T, TIntrospector> tree, TextSpan textSpan) where TIntrospector : struct, IIntervalIntrospector<T> { var intervals = tree.GetIntervalsThatContain(textSpan.Start, textSpan.Length); Contract.ThrowIfFalse(intervals.Length == 0); } public int GetBaseIndentation(SyntaxToken token) => GetBaseIndentation(token.SpanStart); public int GetBaseIndentation(int position) { var indentationData = _indentationTree.GetSmallestContainingInterval(position, 0); if (indentationData == null) { DebugCheckEmpty(_indentationTree, new TextSpan(position, 0)); return 0; } return indentationData.Indentation; } public IEnumerable<IndentBlockOperation> GetAllRelativeIndentBlockOperations() => _relativeIndentationTree.GetIntervalsThatIntersectWith(this.TreeData.StartPosition, this.TreeData.EndPosition, new FormattingContextIntervalIntrospector()).Select(i => i.Operation); public bool TryGetEndTokenForRelativeIndentationSpan(SyntaxToken token, int maxChainDepth, out SyntaxToken endToken, CancellationToken cancellationToken) { endToken = default; var depth = 0; while (true) { cancellationToken.ThrowIfCancellationRequested(); if (depth++ > maxChainDepth) { return false; } var span = token.Span; var indentationData = _relativeIndentationTree.GetSmallestContainingInterval(span.Start, 0); if (indentationData == null) { // this means the given token is not inside of inseparable regions endToken = token; return true; } // recursively find the end token outside of inseparable regions token = indentationData.EndToken.GetNextToken(includeZeroWidth: true); if (token.RawKind == 0) { // reached end of tree return true; } } } private AnchorData? GetAnchorData(SyntaxToken token) { var span = token.Span; var anchorData = _anchorTree.GetSmallestContainingInterval(span.Start, 0); if (anchorData == null) { // no anchor DebugCheckEmpty(_anchorTree, new TextSpan(span.Start, 0)); return null; } return anchorData; } public int GetAnchorDeltaFromOriginalColumn(SyntaxToken token) { var anchorData = GetAnchorData(token); if (anchorData == null) { return 0; } var currentColumn = _tokenStream.GetCurrentColumn(anchorData.AnchorToken); return currentColumn - anchorData.OriginalColumn; } public SyntaxToken GetAnchorToken(SyntaxToken token) { var anchorData = GetAnchorData(token); if (anchorData == null) { return default; } return anchorData.AnchorToken; } public int GetDeltaFromPreviousChangesMap(SyntaxToken token, Dictionary<SyntaxToken, int> previousChangesMap) { // no changes if (!previousChangesMap.ContainsKey(token)) { return 0; } var currentColumn = _tokenStream.GetCurrentColumn(token); return currentColumn - previousChangesMap[token]; } public SyntaxToken GetEndTokenForAnchorSpan(TokenData tokenData) { // consider situation like below // // var q = from c in cs // where c > 1 // + // 2; // // if alignment operation moves "where" to align with "from" // we want to move "+" and "2" along with it (anchor operation) // // below we are trying to figure out up to which token ("2" in the above example) // we should apply the anchor operation var baseAnchorData = FindAnchorSpanOnSameLineAfterToken(tokenData); if (baseAnchorData == null) { return default; } // our anchor operation is very flexible so it not only let one anchor to contain others, it also // let anchors to overlap each other for whatever reasons // below, we will try to flat the overlapped anchor span, and find the last position (token) of that span // find other anchors overlapping with current anchor span var anchorData = _anchorTree.GetIntervalsThatOverlapWith(baseAnchorData.TextSpan.Start, baseAnchorData.TextSpan.Length); // among those anchors find the biggest end token var lastEndToken = baseAnchorData.EndToken; foreach (var interval in anchorData) { // anchor token is not in scope, move to next if (!baseAnchorData.TextSpan.IntersectsWith(interval.AnchorToken.Span)) { continue; } if (interval.EndToken.Span.End < lastEndToken.Span.End) { continue; } lastEndToken = interval.EndToken; } return lastEndToken; } private AnchorData? FindAnchorSpanOnSameLineAfterToken(TokenData tokenData) { // every token after given token on same line is implicitly dependent to the token. // check whether one of them is an anchor token. AnchorData? lastBaseAnchorData = null; while (tokenData.IndexInStream >= 0) { if (_anchorBaseTokenMap.TryGetValue(tokenData.Token, out var tempAnchorData)) { lastBaseAnchorData = tempAnchorData; } // tokenPairIndex is always 0 <= ... < TokenCount - 1 var tokenPairIndex = tokenData.IndexInStream; if (_tokenStream.TokenCount - 1 <= tokenPairIndex || _tokenStream.GetTriviaData(tokenPairIndex).SecondTokenIsFirstTokenOnLine) { return lastBaseAnchorData; } tokenData = tokenData.GetNextTokenData(); } return lastBaseAnchorData; } public bool IsWrappingSuppressed(TextSpan textSpan, bool containsElasticTrivia) { if (IsFormattingDisabled(textSpan)) { return true; } // use edge exclusive version of GetSmallestContainingInterval var data = _suppressWrappingTree.GetSmallestEdgeExclusivelyContainingInterval(textSpan.Start, textSpan.Length); if (data == null) { return false; } if (containsElasticTrivia && !data.IgnoreElastic) { return false; } return true; } public bool IsSpacingSuppressed(TextSpan textSpan, bool containsElasticTrivia) { if (IsFormattingDisabled(textSpan)) { return true; } // For spaces, never ignore elastic trivia because that can // generate incorrect code if (containsElasticTrivia) { return false; } // use edge exclusive version of GetSmallestContainingInterval var data = _suppressSpacingTree.GetSmallestEdgeExclusivelyContainingInterval(textSpan.Start, textSpan.Length); if (data == null) { return false; } return true; } public bool IsSpacingSuppressed(int pairIndex) { var token1 = _tokenStream.GetToken(pairIndex); var token2 = _tokenStream.GetToken(pairIndex + 1); var spanBetweenTwoTokens = TextSpan.FromBounds(token1.SpanStart, token2.Span.End); // this version of SpacingSuppressed will be called after all basic space operations are done. // so no more elastic trivia should have left out return IsSpacingSuppressed(spanBetweenTwoTokens, containsElasticTrivia: false); } public bool IsFormattingDisabled(TextSpan textSpan) => _suppressFormattingTree.HasIntervalThatIntersectsWith(textSpan.Start, textSpan.Length); public bool IsFormattingDisabled(int pairIndex) { var token1 = _tokenStream.GetToken(pairIndex); var token2 = _tokenStream.GetToken(pairIndex + 1); var spanBetweenTwoTokens = TextSpan.FromBounds(token1.SpanStart, token2.Span.End); return IsFormattingDisabled(spanBetweenTwoTokens); } public AnalyzerConfigOptions Options => _engine.Options; public TreeData TreeData => _engine.TreeData; public TokenStream TokenStream => _tokenStream; } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/DocumentKey.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.Serialization; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.PersistentStorage { /// <summary> /// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a /// <see cref="Document"/> without needing to have the entire <see cref="Document"/> snapshot available. /// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during /// solution load), but querying the data is still desired. /// </summary> [DataContract] internal readonly struct DocumentKey : IEqualityComparer<DocumentKey> { [DataMember(Order = 0)] public readonly ProjectKey Project; [DataMember(Order = 1)] public readonly DocumentId Id; [DataMember(Order = 2)] public readonly string? FilePath; [DataMember(Order = 3)] public readonly string Name; public DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name) { Project = project; Id = id; FilePath = filePath; Name = name; } public static DocumentKey ToDocumentKey(Document document) => ToDocumentKey(ProjectKey.ToProjectKey(document.Project), document.State); public static DocumentKey ToDocumentKey(ProjectKey projectKey, TextDocumentState state) => new(projectKey, state.Id, state.FilePath, state.Name); public bool Equals(DocumentKey x, DocumentKey y) => x.Id == y.Id; public int GetHashCode(DocumentKey obj) => obj.Id.GetHashCode(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.PersistentStorage { /// <summary> /// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a /// <see cref="Document"/> without needing to have the entire <see cref="Document"/> snapshot available. /// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during /// solution load), but querying the data is still desired. /// </summary> [DataContract] internal readonly struct DocumentKey : IEqualityComparer<DocumentKey> { [DataMember(Order = 0)] public readonly ProjectKey Project; [DataMember(Order = 1)] public readonly DocumentId Id; [DataMember(Order = 2)] public readonly string? FilePath; [DataMember(Order = 3)] public readonly string Name; public DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name) { Project = project; Id = id; FilePath = filePath; Name = name; } public static DocumentKey ToDocumentKey(Document document) => ToDocumentKey(ProjectKey.ToProjectKey(document.Project), document.State); public static DocumentKey ToDocumentKey(ProjectKey projectKey, TextDocumentState state) => new(projectKey, state.Id, state.FilePath, state.Name); public bool Equals(DocumentKey x, DocumentKey y) => x.Id == y.Id; public int GetHashCode(DocumentKey obj) => obj.Id.GetHashCode(); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeInterface.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeInterface2))] public sealed class CodeInterface : AbstractCodeType, EnvDTE.CodeInterface, EnvDTE80.CodeInterface2 { internal static EnvDTE.CodeInterface Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeInterface(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeInterface)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeInterface CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeInterface(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeInterface)ComAggregate.CreateAggregatedObject(element); } private CodeInterface( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeInterface( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementInterface; } } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddFunction(LookupNode(), name, kind, type, position, access); }); } public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddProperty(LookupNode(), getterName, putterName, type, position, access); }); } public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object position, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { // Note: C# always creates field-like events in interfaces return FileCodeModel.AddEvent(LookupNode(), name, fullDelegateName, false, position, access); }); } public EnvDTE.CodeElements Parts { get { return PartialTypeCollection.Create(State, this); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeInterface2))] public sealed class CodeInterface : AbstractCodeType, EnvDTE.CodeInterface, EnvDTE80.CodeInterface2 { internal static EnvDTE.CodeInterface Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeInterface(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeInterface)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeInterface CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeInterface(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeInterface)ComAggregate.CreateAggregatedObject(element); } private CodeInterface( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeInterface( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementInterface; } } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddFunction(LookupNode(), name, kind, type, position, access); }); } public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddProperty(LookupNode(), getterName, putterName, type, position, access); }); } public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object position, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { // Note: C# always creates field-like events in interfaces return FileCodeModel.AddEvent(LookupNode(), name, fullDelegateName, false, position, access); }); } public EnvDTE.CodeElements Parts { get { return PartialTypeCollection.Create(State, this); } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Portable/Symbols/SymbolKindExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static class SymbolKindExtensions { public static LocalizableErrorArgument Localize(this SymbolKind kind) { switch (kind) { case SymbolKind.Namespace: return MessageID.IDS_SK_NAMESPACE.Localize(); case SymbolKind.NamedType: return MessageID.IDS_SK_TYPE.Localize(); case SymbolKind.TypeParameter: return MessageID.IDS_SK_TYVAR.Localize(); case SymbolKind.Method: return MessageID.IDS_SK_METHOD.Localize(); case SymbolKind.Property: return MessageID.IDS_SK_PROPERTY.Localize(); case SymbolKind.Event: return MessageID.IDS_SK_EVENT.Localize(); case SymbolKind.Field: return MessageID.IDS_SK_FIELD.Localize(); case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.RangeVariable: return MessageID.IDS_SK_VARIABLE.Localize(); case SymbolKind.Alias: return MessageID.IDS_SK_ALIAS.Localize(); case SymbolKind.Label: return MessageID.IDS_SK_LABEL.Localize(); case SymbolKind.Preprocessing: throw ExceptionUtilities.UnexpectedValue(kind); default: return MessageID.IDS_SK_UNKNOWN.Localize(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static class SymbolKindExtensions { public static LocalizableErrorArgument Localize(this SymbolKind kind) { switch (kind) { case SymbolKind.Namespace: return MessageID.IDS_SK_NAMESPACE.Localize(); case SymbolKind.NamedType: return MessageID.IDS_SK_TYPE.Localize(); case SymbolKind.TypeParameter: return MessageID.IDS_SK_TYVAR.Localize(); case SymbolKind.Method: return MessageID.IDS_SK_METHOD.Localize(); case SymbolKind.Property: return MessageID.IDS_SK_PROPERTY.Localize(); case SymbolKind.Event: return MessageID.IDS_SK_EVENT.Localize(); case SymbolKind.Field: return MessageID.IDS_SK_FIELD.Localize(); case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.RangeVariable: return MessageID.IDS_SK_VARIABLE.Localize(); case SymbolKind.Alias: return MessageID.IDS_SK_ALIAS.Localize(); case SymbolKind.Label: return MessageID.IDS_SK_LABEL.Localize(); case SymbolKind.Preprocessing: throw ExceptionUtilities.UnexpectedValue(kind); default: return MessageID.IDS_SK_UNKNOWN.Localize(); } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Analyzers/CSharp/Tests/PopulateSwitch/PopulateSwitchStatementTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.PopulateSwitch; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PopulateSwitch { public partial class PopulateSwitchStatementTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public PopulateSwitchStatementTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPopulateSwitchStatementDiagnosticAnalyzer(), new CSharpPopulateSwitchStatementCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task OnlyOnFirstToken() { await TestMissingInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([||]e) { case MyEnum.Fizz: case MyEnum.Buzz: default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task AllMembersAndDefaultExist() { await TestMissingInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task AllMembersExist_NotDefault() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithDefault() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; default: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumHasExplicitType() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum : long { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum : long { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithMembersAndDefaultInSection_NewValuesAboveDefaultSection() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: default: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.FizzBuzz: break; case MyEnum.Fizz: case MyEnum.Buzz: default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithMembersAndDefaultInSection_AssumesDefaultIsInLastSection() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { default: break; case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { default: break; case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist0() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; } } } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist1() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { default: break; } } } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist2() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_AllMembersExist() { await TestMissingInRegularAndScriptAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; [||]switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_AllMembersExist_OutOfDefaultOrder() { await TestMissingInRegularAndScriptAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; [||]switch (e) { case CreateNew: break; case OpenOrCreate: break; case Truncate: break; case Open: break; case Append: break; case Create: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_MembersExist() { await TestInRegularAndScriptAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; [||]switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; default: break; } } } }", @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_NoMembersExist() { await TestInRegularAndScriptAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; [||]switch (e) { } } } }", @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumHasNonFlagsAttribute() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { [System.Obsolete] enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { [System.Obsolete] enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumIsNested() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { class MyClass { enum MyEnum { Fizz, Buzz, FizzBuzz } void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { class MyClass { enum MyEnum { Fizz, Buzz, FizzBuzz } void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_SwitchIsNotEnum() { await TestMissingInRegularAndScriptAsync( @"using System; namespace ConsoleApplication1 { class MyClass { void Method() { var e = ""test""; [||]switch (e) { case ""test1"": case ""test1"": default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_UsingConstants() { await TestInRegularAndScriptAsync( @"enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case (MyEnum)0: case (MyEnum)1: break; } } }", @"enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case (MyEnum)0: case (MyEnum)1: break; case MyEnum.FizzBuzz: break; default: break; } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] [WorkItem(13455, "https://github.com/dotnet/roslyn/issues/13455")] public async Task AllMissingTokens() { await TestInRegularAndScriptAsync( @" enum MyEnum { Fizz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) } } ", @" enum MyEnum { Fizz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; } } }"); } [Fact] [WorkItem(40240, "https://github.com/dotnet/roslyn/issues/40240")] public async Task TestAddMissingCasesForNullableEnum() { await TestInRegularAndScriptAsync( @"public class Program { void Main() { Bar? bar; [||]switch (bar) { case Bar.Option1: break; case Bar.Option2: break; case null: break; } } } public enum Bar { Option1, Option2, Option3, } ", @"public class Program { void Main() { Bar? bar; switch (bar) { case Bar.Option1: break; case Bar.Option2: break; case null: break; case Bar.Option3: break; } } } public enum Bar { Option1, Option2, Option3, } "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.PopulateSwitch; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PopulateSwitch { public partial class PopulateSwitchStatementTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public PopulateSwitchStatementTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpPopulateSwitchStatementDiagnosticAnalyzer(), new CSharpPopulateSwitchStatementCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task OnlyOnFirstToken() { await TestMissingInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([||]e) { case MyEnum.Fizz: case MyEnum.Buzz: default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task AllMembersAndDefaultExist() { await TestMissingInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task AllMembersExist_NotDefault() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithDefault() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; default: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumHasExplicitType() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum : long { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum : long { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithMembersAndDefaultInSection_NewValuesAboveDefaultSection() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: default: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.FizzBuzz: break; case MyEnum.Fizz: case MyEnum.Buzz: default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithMembersAndDefaultInSection_AssumesDefaultIsInLastSection() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { default: break; case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { default: break; case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist0() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; } } } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist1() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { default: break; } } } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist2() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_AllMembersExist() { await TestMissingInRegularAndScriptAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; [||]switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_AllMembersExist_OutOfDefaultOrder() { await TestMissingInRegularAndScriptAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; [||]switch (e) { case CreateNew: break; case OpenOrCreate: break; case Truncate: break; case Open: break; case Append: break; case Create: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_MembersExist() { await TestInRegularAndScriptAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; [||]switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; default: break; } } } }", @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_NoMembersExist() { await TestInRegularAndScriptAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; [||]switch (e) { } } } }", @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumHasNonFlagsAttribute() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { [System.Obsolete] enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { [System.Obsolete] enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumIsNested() { await TestInRegularAndScriptAsync( @"namespace ConsoleApplication1 { class MyClass { enum MyEnum { Fizz, Buzz, FizzBuzz } void Method() { var e = MyEnum.Fizz; [||]switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { class MyClass { enum MyEnum { Fizz, Buzz, FizzBuzz } void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_SwitchIsNotEnum() { await TestMissingInRegularAndScriptAsync( @"using System; namespace ConsoleApplication1 { class MyClass { void Method() { var e = ""test""; [||]switch (e) { case ""test1"": case ""test1"": default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_UsingConstants() { await TestInRegularAndScriptAsync( @"enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) { case (MyEnum)0: case (MyEnum)1: break; } } }", @"enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case (MyEnum)0: case (MyEnum)1: break; case MyEnum.FizzBuzz: break; default: break; } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] [WorkItem(13455, "https://github.com/dotnet/roslyn/issues/13455")] public async Task AllMissingTokens() { await TestInRegularAndScriptAsync( @" enum MyEnum { Fizz } class MyClass { void Method() { var e = MyEnum.Fizz; [||]switch (e) } } ", @" enum MyEnum { Fizz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; } } }"); } [Fact] [WorkItem(40240, "https://github.com/dotnet/roslyn/issues/40240")] public async Task TestAddMissingCasesForNullableEnum() { await TestInRegularAndScriptAsync( @"public class Program { void Main() { Bar? bar; [||]switch (bar) { case Bar.Option1: break; case Bar.Option2: break; case null: break; } } } public enum Bar { Option1, Option2, Option3, } ", @"public class Program { void Main() { Bar? bar; switch (bar) { case Bar.Option1: break; case Bar.Option2: break; case null: break; case Bar.Option3: break; } } } public enum Bar { Option1, Option2, Option3, } "); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExternAliasCompletionProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class ExternAliasCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(ExternAliasCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoAliases() { await VerifyNoItemsExistAsync(@" extern alias $$ class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task ExternAlias() { var markup = @" extern alias $$ "; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 1, "C#", "C#", false); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterExternAlias() { var markup = @" extern alias goo $$ "; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 0, "C#", "C#", false); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotGlobal() { var markup = @" extern alias $$ "; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "global", 0, "C#", "C#", false); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfAlreadyUsed() { var markup = @" extern alias goo; extern alias $$"; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 0, "C#", "C#", false); } [WorkItem(1075278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075278")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInComment() { var markup = @" extern alias // $$ "; await VerifyNoItemsExistAsync(markup); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class ExternAliasCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(ExternAliasCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoAliases() { await VerifyNoItemsExistAsync(@" extern alias $$ class C { }"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task ExternAlias() { var markup = @" extern alias $$ "; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 1, "C#", "C#", false); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterExternAlias() { var markup = @" extern alias goo $$ "; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 0, "C#", "C#", false); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotGlobal() { var markup = @" extern alias $$ "; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "global", 0, "C#", "C#", false); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfAlreadyUsed() { var markup = @" extern alias goo; extern alias $$"; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "goo", "goo", 0, "C#", "C#", false); } [WorkItem(1075278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075278")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInComment() { var markup = @" extern alias // $$ "; await VerifyNoItemsExistAsync(markup); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberMethodSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceMemberMethodSymbol : SourceMethodSymbolWithAttributes, IAttributeTargetSymbol { // The flags type is used to compact many different bits of information. protected struct Flags { // We currently pack everything into a 32 bit int with the following layout: // // | |n|vvv|yy|s|r|q|z|wwwww| // // w = method kind. 5 bits. // z = isExtensionMethod. 1 bit. // q = isMetadataVirtualIgnoringInterfaceChanges. 1 bit. // r = isMetadataVirtual. 1 bit. (At least as true as isMetadataVirtualIgnoringInterfaceChanges.) // s = isMetadataVirtualLocked. 1 bit. // y = ReturnsVoid. 2 bits. // v = NullableContext. 3 bits. // n = IsNullableAnalysisEnabled. 1 bit. private int _flags; private const int MethodKindOffset = 0; private const int MethodKindSize = 5; private const int IsExtensionMethodOffset = MethodKindOffset + MethodKindSize; private const int IsExtensionMethodSize = 1; private const int IsMetadataVirtualIgnoringInterfaceChangesOffset = IsExtensionMethodOffset + IsExtensionMethodSize; private const int IsMetadataVirtualIgnoringInterfaceChangesSize = 1; private const int IsMetadataVirtualOffset = IsMetadataVirtualIgnoringInterfaceChangesOffset + IsMetadataVirtualIgnoringInterfaceChangesSize; private const int IsMetadataVirtualSize = 1; private const int IsMetadataVirtualLockedOffset = IsMetadataVirtualOffset + IsMetadataVirtualSize; private const int IsMetadataVirtualLockedSize = 1; private const int ReturnsVoidOffset = IsMetadataVirtualLockedOffset + IsMetadataVirtualLockedSize; private const int ReturnsVoidSize = 2; private const int NullableContextOffset = ReturnsVoidOffset + ReturnsVoidSize; private const int NullableContextSize = 3; private const int IsNullableAnalysisEnabledOffset = NullableContextOffset + NullableContextSize; private const int IsNullableAnalysisEnabledSize = 1; private const int MethodKindMask = (1 << MethodKindSize) - 1; private const int IsExtensionMethodBit = 1 << IsExtensionMethodOffset; private const int IsMetadataVirtualIgnoringInterfaceChangesBit = 1 << IsMetadataVirtualIgnoringInterfaceChangesOffset; private const int IsMetadataVirtualBit = 1 << IsMetadataVirtualIgnoringInterfaceChangesOffset; private const int IsMetadataVirtualLockedBit = 1 << IsMetadataVirtualLockedOffset; private const int ReturnsVoidBit = 1 << ReturnsVoidOffset; private const int ReturnsVoidIsSetBit = 1 << ReturnsVoidOffset + 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int IsNullableAnalysisEnabledBit = 1 << IsNullableAnalysisEnabledOffset; public bool TryGetReturnsVoid(out bool value) { int bits = _flags; value = (bits & ReturnsVoidBit) != 0; return (bits & ReturnsVoidIsSetBit) != 0; } public void SetReturnsVoid(bool value) { ThreadSafeFlagOperations.Set(ref _flags, (int)(ReturnsVoidIsSetBit | (value ? ReturnsVoidBit : 0))); } public MethodKind MethodKind { get { return (MethodKind)((_flags >> MethodKindOffset) & MethodKindMask); } } public bool IsExtensionMethod { get { return (_flags & IsExtensionMethodBit) != 0; } } public bool IsNullableAnalysisEnabled { get { return (_flags & IsNullableAnalysisEnabledBit) != 0; } } public bool IsMetadataVirtualLocked { get { return (_flags & IsMetadataVirtualLockedBit) != 0; } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<MethodKind>(MethodKindMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif private static bool ModifiersRequireMetadataVirtual(DeclarationModifiers modifiers) { return (modifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual | DeclarationModifiers.Override)) != 0; } public Flags( MethodKind methodKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isMetadataVirtualIgnoringModifiers = false) { bool isMetadataVirtual = isMetadataVirtualIgnoringModifiers || ModifiersRequireMetadataVirtual(declarationModifiers); int methodKindInt = ((int)methodKind & MethodKindMask) << MethodKindOffset; int isExtensionMethodInt = isExtensionMethod ? IsExtensionMethodBit : 0; int isNullableAnalysisEnabledInt = isNullableAnalysisEnabled ? IsNullableAnalysisEnabledBit : 0; int isMetadataVirtualIgnoringInterfaceImplementationChangesInt = isMetadataVirtual ? IsMetadataVirtualIgnoringInterfaceChangesBit : 0; int isMetadataVirtualInt = isMetadataVirtual ? IsMetadataVirtualBit : 0; _flags = methodKindInt | isExtensionMethodInt | isNullableAnalysisEnabledInt | isMetadataVirtualIgnoringInterfaceImplementationChangesInt | isMetadataVirtualInt | (returnsVoid ? ReturnsVoidBit : 0) | ReturnsVoidIsSetBit; } public bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { // This flag is immutable, so there's no reason to set a lock bit, as we do below. if (ignoreInterfaceImplementationChanges) { return (_flags & IsMetadataVirtualIgnoringInterfaceChangesBit) != 0; } if (!IsMetadataVirtualLocked) { ThreadSafeFlagOperations.Set(ref _flags, IsMetadataVirtualLockedBit); } return (_flags & IsMetadataVirtualBit) != 0; } public void EnsureMetadataVirtual() { // ACASEY: This assert is here to check that we're not mutating the value of IsMetadataVirtual after // someone has consumed it. The best practice is to not access IsMetadataVirtual before ForceComplete // has been called on all SourceNamedTypeSymbols. If it is necessary to do so, then you can pass // ignoreInterfaceImplementationChanges: true, but you must be conscious that seeing "false" may not // reflect the final, emitted modifier. Debug.Assert(!IsMetadataVirtualLocked); if ((_flags & IsMetadataVirtualBit) == 0) { ThreadSafeFlagOperations.Set(ref _flags, IsMetadataVirtualBit); } } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } protected SymbolCompletionState state; protected DeclarationModifiers DeclarationModifiers; protected Flags flags; private readonly NamedTypeSymbol _containingType; private ParameterSymbol _lazyThisParameter; private TypeWithAnnotations.Boxed _lazyIteratorElementType; private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; protected ImmutableArray<Location> locations; protected string lazyDocComment; protected string lazyExpandedDocComment; //null if has never been computed. Initial binding diagnostics //are stashed here in service of API usage patterns //where method body diagnostics are requested multiple times. private ImmutableArray<Diagnostic> _cachedDiagnostics; internal ImmutableArray<Diagnostic> Diagnostics { get { return _cachedDiagnostics; } } internal ImmutableArray<Diagnostic> SetDiagnostics(ImmutableArray<Diagnostic> newSet, out bool diagsWritten) { //return the diagnostics that were actually saved in the event that there were two threads racing. diagsWritten = ImmutableInterlocked.InterlockedInitialize(ref _cachedDiagnostics, newSet); return _cachedDiagnostics; } protected SourceMemberMethodSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator) : this(containingType, syntaxReferenceOpt, ImmutableArray.Create(location), isIterator) { } protected SourceMemberMethodSymbol( NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, ImmutableArray<Location> locations, bool isIterator) : base(syntaxReferenceOpt) { Debug.Assert((object)containingType != null); Debug.Assert(!locations.IsEmpty); _containingType = containingType; this.locations = locations; if (isIterator) { _lazyIteratorElementType = TypeWithAnnotations.Boxed.Sentinel; } } protected void CheckEffectiveAccessibility(TypeWithAnnotations returnType, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics) { if (this.DeclaredAccessibility <= Accessibility.Private || MethodKind == MethodKind.ExplicitInterfaceImplementation) { return; } ErrorCode code = (this.MethodKind == MethodKind.Conversion || this.MethodKind == MethodKind.UserDefinedOperator) ? ErrorCode.ERR_BadVisOpReturn : ErrorCode.ERR_BadVisReturnType; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!this.IsNoMoreVisibleThan(returnType, ref useSiteInfo)) { // Inconsistent accessibility: return type '{1}' is less accessible than method '{0}' diagnostics.Add(code, Locations[0], this, returnType.Type); } code = (this.MethodKind == MethodKind.Conversion || this.MethodKind == MethodKind.UserDefinedOperator) ? ErrorCode.ERR_BadVisOpParam : ErrorCode.ERR_BadVisParamType; foreach (var parameter in parameters) { if (!parameter.TypeWithAnnotations.IsAtLeastAsVisibleAs(this, ref useSiteInfo)) { // Inconsistent accessibility: parameter type '{1}' is less accessible than method '{0}' diagnostics.Add(code, Locations[0], this, parameter.Type); } } diagnostics.Add(Locations[0], useSiteInfo); } protected void MakeFlags( MethodKind methodKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isMetadataVirtualIgnoringModifiers = false) { DeclarationModifiers = declarationModifiers; this.flags = new Flags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod, isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers); } protected void SetReturnsVoid(bool returnsVoid) { this.flags.SetReturnsVoid(returnsVoid); } /// <remarks> /// Implementers should assume that a lock has been taken on MethodChecksLockObject. /// In particular, it should not (generally) be necessary to use CompareExchange to /// protect assignments to fields. /// </remarks> protected abstract void MethodChecks(BindingDiagnosticBag diagnostics); /// <summary> /// We can usually lock on the syntax reference of this method, but it turns /// out that some synthesized methods (e.g. field-like event accessors) also /// need to do method checks. This property allows such methods to supply /// their own lock objects, so that we don't have to add a new field to every /// SourceMethodSymbol. /// </summary> protected virtual object MethodChecksLockObject { get { return this.syntaxReferenceOpt; } } protected void LazyMethodChecks() { if (!state.HasComplete(CompletionPart.FinishMethodChecks)) { // TODO: if this lock ever encloses a potential call to Debugger.NotifyOfCrossThreadDependency, // then we should call DebuggerUtilities.CallBeforeAcquiringLock() (see method comment for more // details). object lockObject = MethodChecksLockObject; Debug.Assert(lockObject != null); lock (lockObject) { if (state.NotePartComplete(CompletionPart.StartMethodChecks)) { // By setting StartMethodChecks, we've committed to doing the checks and setting // FinishMethodChecks. So there is no cancellation supported between one and the other. var diagnostics = BindingDiagnosticBag.GetInstance(); try { MethodChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); } finally { state.NotePartComplete(CompletionPart.FinishMethodChecks); diagnostics.Free(); } } else { // Either (1) this thread is in the process of completing the method, // or (2) some other thread has beat us to the punch and completed the method. // We can distinguish the two cases here by checking for the FinishMethodChecks // part to be complete, which would only occur if another thread completed this // method. // // The other case, in which this thread is in the process of completing the method, // requires that we return here even though the checks are not complete. That's because // methods are processed by first populating the return type and parameters by binding // the syntax from source. Those values are visible to the same thread for the purpose // of computing which methods are implemented and overridden. But then those values // may be rewritten (by the same thread) to copy down custom modifiers. In order to // allow the same thread to see the return type and parameters from the syntax (though // they do not yet take on their final values), we return here. // Due to the fact that LazyMethodChecks is potentially reentrant, we must use a // reentrant lock to avoid deadlock and cannot assert that at this point method checks // have completed (state.HasComplete(CompletionPart.FinishMethodChecks)). } } } } protected virtual void LazyAsyncMethodChecks(CancellationToken cancellationToken) { state.NotePartComplete(CompletionPart.StartAsyncMethodChecks); state.NotePartComplete(CompletionPart.FinishAsyncMethodChecks); } public sealed override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override Symbol AssociatedSymbol { get { return null; } } #region Flags public override bool ReturnsVoid { get { flags.TryGetReturnsVoid(out bool value); return value; } } public sealed override MethodKind MethodKind { get { return this.flags.MethodKind; } } public override bool IsExtensionMethod { get { return this.flags.IsExtensionMethod; } } // TODO (tomat): sealed internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { if (IsExplicitInterfaceImplementation && _containingType.IsInterface) { // All implementations of methods from base interfaces should omit the newslot bit to ensure no new vtable slot is allocated. return false; } // If C# and the runtime don't agree on the overridden method, // then we will mark the method as newslot and specify the // override explicitly (see GetExplicitImplementationOverrides // in NamedTypeSymbolAdapter.cs). return this.IsOverride ? this.RequiresExplicitOverride(out _) : !this.IsStatic && this.IsMetadataVirtual(ignoreInterfaceImplementationChanges); } // TODO (tomat): sealed? internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return this.flags.IsMetadataVirtual(ignoreInterfaceImplementationChanges); } internal void EnsureMetadataVirtual() { Debug.Assert(!this.IsStatic); this.flags.EnsureMetadataVirtual(); } public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(this.DeclarationModifiers); } } internal bool HasExternModifier { get { return (this.DeclarationModifiers & DeclarationModifiers.Extern) != 0; } } public override bool IsExtern { get { return HasExternModifier; } } public sealed override bool IsSealed { get { return (this.DeclarationModifiers & DeclarationModifiers.Sealed) != 0; } } public sealed override bool IsAbstract { get { return (this.DeclarationModifiers & DeclarationModifiers.Abstract) != 0; } } public sealed override bool IsOverride { get { return (this.DeclarationModifiers & DeclarationModifiers.Override) != 0; } } internal bool IsPartial { get { return (this.DeclarationModifiers & DeclarationModifiers.Partial) != 0; } } public sealed override bool IsVirtual { get { return (this.DeclarationModifiers & DeclarationModifiers.Virtual) != 0; } } internal bool IsNew { get { return (this.DeclarationModifiers & DeclarationModifiers.New) != 0; } } public sealed override bool IsStatic { get { return (this.DeclarationModifiers & DeclarationModifiers.Static) != 0; } } internal bool IsUnsafe { get { return (this.DeclarationModifiers & DeclarationModifiers.Unsafe) != 0; } } public sealed override bool IsAsync { get { return (this.DeclarationModifiers & DeclarationModifiers.Async) != 0; } } internal override bool IsDeclaredReadOnly { get { return (this.DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0; } } internal override bool IsInitOnly => false; internal sealed override Cci.CallingConvention CallingConvention { get { var cc = IsVararg ? Cci.CallingConvention.ExtraArguments : Cci.CallingConvention.Default; if (IsGenericMethod) { cc |= Cci.CallingConvention.Generic; } if (!IsStatic) { cc |= Cci.CallingConvention.HasThis; } return cc; } } #endregion #region Syntax internal (BlockSyntax blockBody, ArrowExpressionClauseSyntax arrowBody) Bodies { get { switch (SyntaxNode) { case BaseMethodDeclarationSyntax method: return (method.Body, method.ExpressionBody); case AccessorDeclarationSyntax accessor: return (accessor.Body, accessor.ExpressionBody); case ArrowExpressionClauseSyntax arrowExpression: Debug.Assert(arrowExpression.Parent.Kind() == SyntaxKind.PropertyDeclaration || arrowExpression.Parent.Kind() == SyntaxKind.IndexerDeclaration || this is SynthesizedClosureMethod); return (null, arrowExpression); case BlockSyntax block: Debug.Assert(this is SynthesizedClosureMethod); return (block, null); default: return (null, null); } } } private Binder TryGetInMethodBinder(BinderFactory binderFactoryOpt = null) { CSharpSyntaxNode contextNode = GetInMethodSyntaxNode(); if (contextNode == null) { return null; } Binder result = (binderFactoryOpt ?? this.DeclaringCompilation.GetBinderFactory(contextNode.SyntaxTree)).GetBinder(contextNode); #if DEBUG Binder current = result; do { if (current is InMethodBinder) { break; } current = current.Next; } while (current != null); Debug.Assert(current is InMethodBinder); #endif return result; } internal virtual ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) { Binder inMethod = TryGetInMethodBinder(binderFactoryOpt); return inMethod == null ? null : new ExecutableCodeBinder(SyntaxNode, this, inMethod.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None)); } /// <summary> /// Overridden by <see cref="SourceOrdinaryMethodSymbol"/>, /// which might return locations of partial methods. /// </summary> public override ImmutableArray<Location> Locations { get { return this.locations; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment); } #endregion public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return GetTypeParametersAsTypeArguments(); } } public sealed override int Arity { get { return TypeParameters.Length; } } internal sealed override bool TryGetThisParameter(out ParameterSymbol thisParameter) { thisParameter = _lazyThisParameter; if ((object)thisParameter != null || IsStatic) { return true; } Interlocked.CompareExchange(ref _lazyThisParameter, new ThisParameterSymbol(this), null); thisParameter = _lazyThisParameter; return true; } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { return _lazyIteratorElementType?.Value ?? default; } set { Debug.Assert(_lazyIteratorElementType == TypeWithAnnotations.Boxed.Sentinel || TypeSymbol.Equals(_lazyIteratorElementType.Value.Type, value.Type, TypeCompareKind.ConsiderEverything2)); Interlocked.CompareExchange(ref _lazyIteratorElementType, new TypeWithAnnotations.Boxed(value), TypeWithAnnotations.Boxed.Sentinel); } } internal override bool IsIterator => _lazyIteratorElementType is object; //overridden appropriately in SourceMemberMethodSymbol public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } internal sealed override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { this.LazyMethodChecks(); if (_lazyOverriddenOrHiddenMembers == null) { Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); } return _lazyOverriddenOrHiddenMembers; } } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.ReturnTypeAttributes: this.GetReturnTypeAttributes(); break; case CompletionPart.Type: var unusedType = this.ReturnTypeWithAnnotations; state.NotePartComplete(CompletionPart.Type); break; case CompletionPart.Parameters: foreach (var parameter in this.Parameters) { parameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.Parameters); break; case CompletionPart.TypeParameters: foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.StartAsyncMethodChecks: case CompletionPart.FinishAsyncMethodChecks: LazyAsyncMethodChecks(cancellationToken); break; case CompletionPart.StartMethodChecks: case CompletionPart.FinishMethodChecks: LazyMethodChecks(); goto done; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.MethodSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } done: // Don't return until we've seen all of the CompletionParts. This ensures all // diagnostics have been reported (not necessarily on this thread). CompletionPart allParts = CompletionPart.MethodSymbolAll; state.SpinWaitComplete(allParts, cancellationToken); } protected sealed override void NoteAttributesComplete(bool forReturnType) { var part = forReturnType ? CompletionPart.ReturnTypeAttributes : CompletionPart.Attributes; state.NotePartComplete(part); } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { base.AfterAddingTypeMembersChecks(conversions, diagnostics); var compilation = this.DeclaringCompilation; var location = locations[0]; if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } } // Consider moving this state to SourceMethodSymbol to emit NullableContextAttributes // on lambdas and local functions (see https://github.com/dotnet/roslyn/issues/36736). internal override byte? GetLocalNullableContextValue() { byte? value; if (!flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } builder.AddValue(ReturnTypeWithAnnotations); foreach (var parameter in Parameters) { parameter.GetCommonNullableValues(compilation, ref builder); } return builder.MostCommonValue; } internal override bool IsNullableAnalysisEnabled() { Debug.Assert(!this.IsConstructor()); // Constructors should use IsNullableEnabledForConstructorsAndInitializers() instead. return flags.IsNullableAnalysisEnabled; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } var compilation = this.DeclaringCompilation; if (compilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (this.RequiresExplicitOverride(out _)) { // On platforms where it is present, add PreserveBaseOverridesAttribute when a methodimpl is used to override a class method. AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizePreserveBaseOverridesAttribute()); } bool isAsync = this.IsAsync; bool isIterator = this.IsIterator; if (!isAsync && !isIterator) { return; } // The async state machine type is not synthesized until the async method body is rewritten. If we are // only emitting metadata the method body will not have been rewritten, and the async state machine // type will not have been created. In this case, omit the attribute. if (moduleBuilder.CompilationState.TryGetStateMachineType(this, out NamedTypeSymbol stateMachineType)) { var arg = new TypedConstant(compilation.GetWellKnownType(WellKnownType.System_Type), TypedConstantKind.Type, stateMachineType.GetUnboundGenericTypeOrSelf()); if (isAsync && isIterator) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } else if (isAsync) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } else if (isIterator) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } } if (isAsync && !isIterator) { // Regular async (not async-iterator) kick-off method calls MoveNext, which contains user code. // This means we need to emit DebuggerStepThroughAttribute in order // to have correct stepping behavior during debugging. AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDebuggerStepThroughAttribute()); } } /// <summary> /// Checks to see if a body is legal given the current modifiers. /// If it is not, a diagnostic is added with the current type. /// </summary> protected void CheckModifiersForBody(Location location, BindingDiagnosticBag diagnostics) { if (IsExtern && !IsAbstract) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } else if (IsAbstract && !IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractHasBody, location, this); } // Do not report error for IsAbstract && IsExtern. Dev10 reports CS0180 only // in that case ("member cannot be both extern and abstract"). } protected void CheckFeatureAvailabilityAndRuntimeSupport(SyntaxNode declarationSyntax, Location location, bool hasBody, BindingDiagnosticBag diagnostics) { if (_containingType.IsInterface) { if ((!IsStatic || MethodKind is MethodKind.StaticConstructor) && (hasBody || IsExplicitInterfaceImplementation)) { Binder.CheckFeatureAvailability(declarationSyntax, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, location); } if ((hasBody || IsExplicitInterfaceImplementation || IsExtern) && !ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, location); } if (!hasBody && IsAbstract && IsStatic && !ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, location); } } } /// <summary> /// Returns true if the method body is an expression, as expressed /// by the <see cref="ArrowExpressionClauseSyntax"/> syntax. False /// otherwise. /// </summary> /// <remarks> /// If the method has both block body and an expression body /// present, this is not treated as expression-bodied. /// </remarks> internal abstract bool IsExpressionBodied { get; } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { Debug.Assert(this.SyntaxNode.SyntaxTree == localTree); (BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody) = Bodies; CSharpSyntaxNode bodySyntax = null; // All locals are declared within the body of the method. if (blockBody?.Span.Contains(localPosition) == true) { bodySyntax = blockBody; } else if (expressionBody?.Span.Contains(localPosition) == true) { bodySyntax = expressionBody; } else { // Method without body doesn't declare locals. Debug.Assert(bodySyntax != null); return -1; } return localPosition - bodySyntax.SpanStart; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceMemberMethodSymbol : SourceMethodSymbolWithAttributes, IAttributeTargetSymbol { // The flags type is used to compact many different bits of information. protected struct Flags { // We currently pack everything into a 32 bit int with the following layout: // // | |n|vvv|yy|s|r|q|z|wwwww| // // w = method kind. 5 bits. // z = isExtensionMethod. 1 bit. // q = isMetadataVirtualIgnoringInterfaceChanges. 1 bit. // r = isMetadataVirtual. 1 bit. (At least as true as isMetadataVirtualIgnoringInterfaceChanges.) // s = isMetadataVirtualLocked. 1 bit. // y = ReturnsVoid. 2 bits. // v = NullableContext. 3 bits. // n = IsNullableAnalysisEnabled. 1 bit. private int _flags; private const int MethodKindOffset = 0; private const int MethodKindSize = 5; private const int IsExtensionMethodOffset = MethodKindOffset + MethodKindSize; private const int IsExtensionMethodSize = 1; private const int IsMetadataVirtualIgnoringInterfaceChangesOffset = IsExtensionMethodOffset + IsExtensionMethodSize; private const int IsMetadataVirtualIgnoringInterfaceChangesSize = 1; private const int IsMetadataVirtualOffset = IsMetadataVirtualIgnoringInterfaceChangesOffset + IsMetadataVirtualIgnoringInterfaceChangesSize; private const int IsMetadataVirtualSize = 1; private const int IsMetadataVirtualLockedOffset = IsMetadataVirtualOffset + IsMetadataVirtualSize; private const int IsMetadataVirtualLockedSize = 1; private const int ReturnsVoidOffset = IsMetadataVirtualLockedOffset + IsMetadataVirtualLockedSize; private const int ReturnsVoidSize = 2; private const int NullableContextOffset = ReturnsVoidOffset + ReturnsVoidSize; private const int NullableContextSize = 3; private const int IsNullableAnalysisEnabledOffset = NullableContextOffset + NullableContextSize; private const int IsNullableAnalysisEnabledSize = 1; private const int MethodKindMask = (1 << MethodKindSize) - 1; private const int IsExtensionMethodBit = 1 << IsExtensionMethodOffset; private const int IsMetadataVirtualIgnoringInterfaceChangesBit = 1 << IsMetadataVirtualIgnoringInterfaceChangesOffset; private const int IsMetadataVirtualBit = 1 << IsMetadataVirtualIgnoringInterfaceChangesOffset; private const int IsMetadataVirtualLockedBit = 1 << IsMetadataVirtualLockedOffset; private const int ReturnsVoidBit = 1 << ReturnsVoidOffset; private const int ReturnsVoidIsSetBit = 1 << ReturnsVoidOffset + 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int IsNullableAnalysisEnabledBit = 1 << IsNullableAnalysisEnabledOffset; public bool TryGetReturnsVoid(out bool value) { int bits = _flags; value = (bits & ReturnsVoidBit) != 0; return (bits & ReturnsVoidIsSetBit) != 0; } public void SetReturnsVoid(bool value) { ThreadSafeFlagOperations.Set(ref _flags, (int)(ReturnsVoidIsSetBit | (value ? ReturnsVoidBit : 0))); } public MethodKind MethodKind { get { return (MethodKind)((_flags >> MethodKindOffset) & MethodKindMask); } } public bool IsExtensionMethod { get { return (_flags & IsExtensionMethodBit) != 0; } } public bool IsNullableAnalysisEnabled { get { return (_flags & IsNullableAnalysisEnabledBit) != 0; } } public bool IsMetadataVirtualLocked { get { return (_flags & IsMetadataVirtualLockedBit) != 0; } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<MethodKind>(MethodKindMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif private static bool ModifiersRequireMetadataVirtual(DeclarationModifiers modifiers) { return (modifiers & (DeclarationModifiers.Abstract | DeclarationModifiers.Virtual | DeclarationModifiers.Override)) != 0; } public Flags( MethodKind methodKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isMetadataVirtualIgnoringModifiers = false) { bool isMetadataVirtual = isMetadataVirtualIgnoringModifiers || ModifiersRequireMetadataVirtual(declarationModifiers); int methodKindInt = ((int)methodKind & MethodKindMask) << MethodKindOffset; int isExtensionMethodInt = isExtensionMethod ? IsExtensionMethodBit : 0; int isNullableAnalysisEnabledInt = isNullableAnalysisEnabled ? IsNullableAnalysisEnabledBit : 0; int isMetadataVirtualIgnoringInterfaceImplementationChangesInt = isMetadataVirtual ? IsMetadataVirtualIgnoringInterfaceChangesBit : 0; int isMetadataVirtualInt = isMetadataVirtual ? IsMetadataVirtualBit : 0; _flags = methodKindInt | isExtensionMethodInt | isNullableAnalysisEnabledInt | isMetadataVirtualIgnoringInterfaceImplementationChangesInt | isMetadataVirtualInt | (returnsVoid ? ReturnsVoidBit : 0) | ReturnsVoidIsSetBit; } public bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { // This flag is immutable, so there's no reason to set a lock bit, as we do below. if (ignoreInterfaceImplementationChanges) { return (_flags & IsMetadataVirtualIgnoringInterfaceChangesBit) != 0; } if (!IsMetadataVirtualLocked) { ThreadSafeFlagOperations.Set(ref _flags, IsMetadataVirtualLockedBit); } return (_flags & IsMetadataVirtualBit) != 0; } public void EnsureMetadataVirtual() { // ACASEY: This assert is here to check that we're not mutating the value of IsMetadataVirtual after // someone has consumed it. The best practice is to not access IsMetadataVirtual before ForceComplete // has been called on all SourceNamedTypeSymbols. If it is necessary to do so, then you can pass // ignoreInterfaceImplementationChanges: true, but you must be conscious that seeing "false" may not // reflect the final, emitted modifier. Debug.Assert(!IsMetadataVirtualLocked); if ((_flags & IsMetadataVirtualBit) == 0) { ThreadSafeFlagOperations.Set(ref _flags, IsMetadataVirtualBit); } } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } protected SymbolCompletionState state; protected DeclarationModifiers DeclarationModifiers; protected Flags flags; private readonly NamedTypeSymbol _containingType; private ParameterSymbol _lazyThisParameter; private TypeWithAnnotations.Boxed _lazyIteratorElementType; private OverriddenOrHiddenMembersResult _lazyOverriddenOrHiddenMembers; protected ImmutableArray<Location> locations; protected string lazyDocComment; protected string lazyExpandedDocComment; //null if has never been computed. Initial binding diagnostics //are stashed here in service of API usage patterns //where method body diagnostics are requested multiple times. private ImmutableArray<Diagnostic> _cachedDiagnostics; internal ImmutableArray<Diagnostic> Diagnostics { get { return _cachedDiagnostics; } } internal ImmutableArray<Diagnostic> SetDiagnostics(ImmutableArray<Diagnostic> newSet, out bool diagsWritten) { //return the diagnostics that were actually saved in the event that there were two threads racing. diagsWritten = ImmutableInterlocked.InterlockedInitialize(ref _cachedDiagnostics, newSet); return _cachedDiagnostics; } protected SourceMemberMethodSymbol(NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, Location location, bool isIterator) : this(containingType, syntaxReferenceOpt, ImmutableArray.Create(location), isIterator) { } protected SourceMemberMethodSymbol( NamedTypeSymbol containingType, SyntaxReference syntaxReferenceOpt, ImmutableArray<Location> locations, bool isIterator) : base(syntaxReferenceOpt) { Debug.Assert((object)containingType != null); Debug.Assert(!locations.IsEmpty); _containingType = containingType; this.locations = locations; if (isIterator) { _lazyIteratorElementType = TypeWithAnnotations.Boxed.Sentinel; } } protected void CheckEffectiveAccessibility(TypeWithAnnotations returnType, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics) { if (this.DeclaredAccessibility <= Accessibility.Private || MethodKind == MethodKind.ExplicitInterfaceImplementation) { return; } ErrorCode code = (this.MethodKind == MethodKind.Conversion || this.MethodKind == MethodKind.UserDefinedOperator) ? ErrorCode.ERR_BadVisOpReturn : ErrorCode.ERR_BadVisReturnType; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!this.IsNoMoreVisibleThan(returnType, ref useSiteInfo)) { // Inconsistent accessibility: return type '{1}' is less accessible than method '{0}' diagnostics.Add(code, Locations[0], this, returnType.Type); } code = (this.MethodKind == MethodKind.Conversion || this.MethodKind == MethodKind.UserDefinedOperator) ? ErrorCode.ERR_BadVisOpParam : ErrorCode.ERR_BadVisParamType; foreach (var parameter in parameters) { if (!parameter.TypeWithAnnotations.IsAtLeastAsVisibleAs(this, ref useSiteInfo)) { // Inconsistent accessibility: parameter type '{1}' is less accessible than method '{0}' diagnostics.Add(code, Locations[0], this, parameter.Type); } } diagnostics.Add(Locations[0], useSiteInfo); } protected void MakeFlags( MethodKind methodKind, DeclarationModifiers declarationModifiers, bool returnsVoid, bool isExtensionMethod, bool isNullableAnalysisEnabled, bool isMetadataVirtualIgnoringModifiers = false) { DeclarationModifiers = declarationModifiers; this.flags = new Flags(methodKind, declarationModifiers, returnsVoid, isExtensionMethod, isNullableAnalysisEnabled, isMetadataVirtualIgnoringModifiers); } protected void SetReturnsVoid(bool returnsVoid) { this.flags.SetReturnsVoid(returnsVoid); } /// <remarks> /// Implementers should assume that a lock has been taken on MethodChecksLockObject. /// In particular, it should not (generally) be necessary to use CompareExchange to /// protect assignments to fields. /// </remarks> protected abstract void MethodChecks(BindingDiagnosticBag diagnostics); /// <summary> /// We can usually lock on the syntax reference of this method, but it turns /// out that some synthesized methods (e.g. field-like event accessors) also /// need to do method checks. This property allows such methods to supply /// their own lock objects, so that we don't have to add a new field to every /// SourceMethodSymbol. /// </summary> protected virtual object MethodChecksLockObject { get { return this.syntaxReferenceOpt; } } protected void LazyMethodChecks() { if (!state.HasComplete(CompletionPart.FinishMethodChecks)) { // TODO: if this lock ever encloses a potential call to Debugger.NotifyOfCrossThreadDependency, // then we should call DebuggerUtilities.CallBeforeAcquiringLock() (see method comment for more // details). object lockObject = MethodChecksLockObject; Debug.Assert(lockObject != null); lock (lockObject) { if (state.NotePartComplete(CompletionPart.StartMethodChecks)) { // By setting StartMethodChecks, we've committed to doing the checks and setting // FinishMethodChecks. So there is no cancellation supported between one and the other. var diagnostics = BindingDiagnosticBag.GetInstance(); try { MethodChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); } finally { state.NotePartComplete(CompletionPart.FinishMethodChecks); diagnostics.Free(); } } else { // Either (1) this thread is in the process of completing the method, // or (2) some other thread has beat us to the punch and completed the method. // We can distinguish the two cases here by checking for the FinishMethodChecks // part to be complete, which would only occur if another thread completed this // method. // // The other case, in which this thread is in the process of completing the method, // requires that we return here even though the checks are not complete. That's because // methods are processed by first populating the return type and parameters by binding // the syntax from source. Those values are visible to the same thread for the purpose // of computing which methods are implemented and overridden. But then those values // may be rewritten (by the same thread) to copy down custom modifiers. In order to // allow the same thread to see the return type and parameters from the syntax (though // they do not yet take on their final values), we return here. // Due to the fact that LazyMethodChecks is potentially reentrant, we must use a // reentrant lock to avoid deadlock and cannot assert that at this point method checks // have completed (state.HasComplete(CompletionPart.FinishMethodChecks)). } } } } protected virtual void LazyAsyncMethodChecks(CancellationToken cancellationToken) { state.NotePartComplete(CompletionPart.StartAsyncMethodChecks); state.NotePartComplete(CompletionPart.FinishAsyncMethodChecks); } public sealed override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override Symbol AssociatedSymbol { get { return null; } } #region Flags public override bool ReturnsVoid { get { flags.TryGetReturnsVoid(out bool value); return value; } } public sealed override MethodKind MethodKind { get { return this.flags.MethodKind; } } public override bool IsExtensionMethod { get { return this.flags.IsExtensionMethod; } } // TODO (tomat): sealed internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { if (IsExplicitInterfaceImplementation && _containingType.IsInterface) { // All implementations of methods from base interfaces should omit the newslot bit to ensure no new vtable slot is allocated. return false; } // If C# and the runtime don't agree on the overridden method, // then we will mark the method as newslot and specify the // override explicitly (see GetExplicitImplementationOverrides // in NamedTypeSymbolAdapter.cs). return this.IsOverride ? this.RequiresExplicitOverride(out _) : !this.IsStatic && this.IsMetadataVirtual(ignoreInterfaceImplementationChanges); } // TODO (tomat): sealed? internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return this.flags.IsMetadataVirtual(ignoreInterfaceImplementationChanges); } internal void EnsureMetadataVirtual() { Debug.Assert(!this.IsStatic); this.flags.EnsureMetadataVirtual(); } public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(this.DeclarationModifiers); } } internal bool HasExternModifier { get { return (this.DeclarationModifiers & DeclarationModifiers.Extern) != 0; } } public override bool IsExtern { get { return HasExternModifier; } } public sealed override bool IsSealed { get { return (this.DeclarationModifiers & DeclarationModifiers.Sealed) != 0; } } public sealed override bool IsAbstract { get { return (this.DeclarationModifiers & DeclarationModifiers.Abstract) != 0; } } public sealed override bool IsOverride { get { return (this.DeclarationModifiers & DeclarationModifiers.Override) != 0; } } internal bool IsPartial { get { return (this.DeclarationModifiers & DeclarationModifiers.Partial) != 0; } } public sealed override bool IsVirtual { get { return (this.DeclarationModifiers & DeclarationModifiers.Virtual) != 0; } } internal bool IsNew { get { return (this.DeclarationModifiers & DeclarationModifiers.New) != 0; } } public sealed override bool IsStatic { get { return (this.DeclarationModifiers & DeclarationModifiers.Static) != 0; } } internal bool IsUnsafe { get { return (this.DeclarationModifiers & DeclarationModifiers.Unsafe) != 0; } } public sealed override bool IsAsync { get { return (this.DeclarationModifiers & DeclarationModifiers.Async) != 0; } } internal override bool IsDeclaredReadOnly { get { return (this.DeclarationModifiers & DeclarationModifiers.ReadOnly) != 0; } } internal override bool IsInitOnly => false; internal sealed override Cci.CallingConvention CallingConvention { get { var cc = IsVararg ? Cci.CallingConvention.ExtraArguments : Cci.CallingConvention.Default; if (IsGenericMethod) { cc |= Cci.CallingConvention.Generic; } if (!IsStatic) { cc |= Cci.CallingConvention.HasThis; } return cc; } } #endregion #region Syntax internal (BlockSyntax blockBody, ArrowExpressionClauseSyntax arrowBody) Bodies { get { switch (SyntaxNode) { case BaseMethodDeclarationSyntax method: return (method.Body, method.ExpressionBody); case AccessorDeclarationSyntax accessor: return (accessor.Body, accessor.ExpressionBody); case ArrowExpressionClauseSyntax arrowExpression: Debug.Assert(arrowExpression.Parent.Kind() == SyntaxKind.PropertyDeclaration || arrowExpression.Parent.Kind() == SyntaxKind.IndexerDeclaration || this is SynthesizedClosureMethod); return (null, arrowExpression); case BlockSyntax block: Debug.Assert(this is SynthesizedClosureMethod); return (block, null); default: return (null, null); } } } private Binder TryGetInMethodBinder(BinderFactory binderFactoryOpt = null) { CSharpSyntaxNode contextNode = GetInMethodSyntaxNode(); if (contextNode == null) { return null; } Binder result = (binderFactoryOpt ?? this.DeclaringCompilation.GetBinderFactory(contextNode.SyntaxTree)).GetBinder(contextNode); #if DEBUG Binder current = result; do { if (current is InMethodBinder) { break; } current = current.Next; } while (current != null); Debug.Assert(current is InMethodBinder); #endif return result; } internal virtual ExecutableCodeBinder TryGetBodyBinder(BinderFactory binderFactoryOpt = null, bool ignoreAccessibility = false) { Binder inMethod = TryGetInMethodBinder(binderFactoryOpt); return inMethod == null ? null : new ExecutableCodeBinder(SyntaxNode, this, inMethod.WithAdditionalFlags(ignoreAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None)); } /// <summary> /// Overridden by <see cref="SourceOrdinaryMethodSymbol"/>, /// which might return locations of partial methods. /// </summary> public override ImmutableArray<Location> Locations { get { return this.locations; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment); } #endregion public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return GetTypeParametersAsTypeArguments(); } } public sealed override int Arity { get { return TypeParameters.Length; } } internal sealed override bool TryGetThisParameter(out ParameterSymbol thisParameter) { thisParameter = _lazyThisParameter; if ((object)thisParameter != null || IsStatic) { return true; } Interlocked.CompareExchange(ref _lazyThisParameter, new ThisParameterSymbol(this), null); thisParameter = _lazyThisParameter; return true; } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { return _lazyIteratorElementType?.Value ?? default; } set { Debug.Assert(_lazyIteratorElementType == TypeWithAnnotations.Boxed.Sentinel || TypeSymbol.Equals(_lazyIteratorElementType.Value.Type, value.Type, TypeCompareKind.ConsiderEverything2)); Interlocked.CompareExchange(ref _lazyIteratorElementType, new TypeWithAnnotations.Boxed(value), TypeWithAnnotations.Boxed.Sentinel); } } internal override bool IsIterator => _lazyIteratorElementType is object; //overridden appropriately in SourceMemberMethodSymbol public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } internal sealed override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers { get { this.LazyMethodChecks(); if (_lazyOverriddenOrHiddenMembers == null) { Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null); } return _lazyOverriddenOrHiddenMembers; } } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.ReturnTypeAttributes: this.GetReturnTypeAttributes(); break; case CompletionPart.Type: var unusedType = this.ReturnTypeWithAnnotations; state.NotePartComplete(CompletionPart.Type); break; case CompletionPart.Parameters: foreach (var parameter in this.Parameters) { parameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.Parameters); break; case CompletionPart.TypeParameters: foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.StartAsyncMethodChecks: case CompletionPart.FinishAsyncMethodChecks: LazyAsyncMethodChecks(cancellationToken); break; case CompletionPart.StartMethodChecks: case CompletionPart.FinishMethodChecks: LazyMethodChecks(); goto done; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.MethodSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } done: // Don't return until we've seen all of the CompletionParts. This ensures all // diagnostics have been reported (not necessarily on this thread). CompletionPart allParts = CompletionPart.MethodSymbolAll; state.SpinWaitComplete(allParts, cancellationToken); } protected sealed override void NoteAttributesComplete(bool forReturnType) { var part = forReturnType ? CompletionPart.ReturnTypeAttributes : CompletionPart.Attributes; state.NotePartComplete(part); } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { base.AfterAddingTypeMembersChecks(conversions, diagnostics); var compilation = this.DeclaringCompilation; var location = locations[0]; if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } } // Consider moving this state to SourceMethodSymbol to emit NullableContextAttributes // on lambdas and local functions (see https://github.com/dotnet/roslyn/issues/36736). internal override byte? GetLocalNullableContextValue() { byte? value; if (!flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } builder.AddValue(ReturnTypeWithAnnotations); foreach (var parameter in Parameters) { parameter.GetCommonNullableValues(compilation, ref builder); } return builder.MostCommonValue; } internal override bool IsNullableAnalysisEnabled() { Debug.Assert(!this.IsConstructor()); // Constructors should use IsNullableEnabledForConstructorsAndInitializers() instead. return flags.IsNullableAnalysisEnabled; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (IsDeclaredReadOnly && !ContainingType.IsReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } var compilation = this.DeclaringCompilation; if (compilation.ShouldEmitNullableAttributes(this) && ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (this.RequiresExplicitOverride(out _)) { // On platforms where it is present, add PreserveBaseOverridesAttribute when a methodimpl is used to override a class method. AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizePreserveBaseOverridesAttribute()); } bool isAsync = this.IsAsync; bool isIterator = this.IsIterator; if (!isAsync && !isIterator) { return; } // The async state machine type is not synthesized until the async method body is rewritten. If we are // only emitting metadata the method body will not have been rewritten, and the async state machine // type will not have been created. In this case, omit the attribute. if (moduleBuilder.CompilationState.TryGetStateMachineType(this, out NamedTypeSymbol stateMachineType)) { var arg = new TypedConstant(compilation.GetWellKnownType(WellKnownType.System_Type), TypedConstantKind.Type, stateMachineType.GetUnboundGenericTypeOrSelf()); if (isAsync && isIterator) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } else if (isAsync) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } else if (isIterator) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor, ImmutableArray.Create(arg))); } } if (isAsync && !isIterator) { // Regular async (not async-iterator) kick-off method calls MoveNext, which contains user code. // This means we need to emit DebuggerStepThroughAttribute in order // to have correct stepping behavior during debugging. AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDebuggerStepThroughAttribute()); } } /// <summary> /// Checks to see if a body is legal given the current modifiers. /// If it is not, a diagnostic is added with the current type. /// </summary> protected void CheckModifiersForBody(Location location, BindingDiagnosticBag diagnostics) { if (IsExtern && !IsAbstract) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } else if (IsAbstract && !IsExtern) { diagnostics.Add(ErrorCode.ERR_AbstractHasBody, location, this); } // Do not report error for IsAbstract && IsExtern. Dev10 reports CS0180 only // in that case ("member cannot be both extern and abstract"). } protected void CheckFeatureAvailabilityAndRuntimeSupport(SyntaxNode declarationSyntax, Location location, bool hasBody, BindingDiagnosticBag diagnostics) { if (_containingType.IsInterface) { if ((!IsStatic || MethodKind is MethodKind.StaticConstructor) && (hasBody || IsExplicitInterfaceImplementation)) { Binder.CheckFeatureAvailability(declarationSyntax, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, location); } if ((hasBody || IsExplicitInterfaceImplementation || IsExtern) && !ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, location); } if (!hasBody && IsAbstract && IsStatic && !ContainingAssembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, location); } } } /// <summary> /// Returns true if the method body is an expression, as expressed /// by the <see cref="ArrowExpressionClauseSyntax"/> syntax. False /// otherwise. /// </summary> /// <remarks> /// If the method has both block body and an expression body /// present, this is not treated as expression-bodied. /// </remarks> internal abstract bool IsExpressionBodied { get; } internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { Debug.Assert(this.SyntaxNode.SyntaxTree == localTree); (BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody) = Bodies; CSharpSyntaxNode bodySyntax = null; // All locals are declared within the body of the method. if (blockBody?.Span.Contains(localPosition) == true) { bodySyntax = blockBody; } else if (expressionBody?.Span.Contains(localPosition) == true) { bodySyntax = expressionBody; } else { // Method without body doesn't declare locals. Debug.Assert(bodySyntax != null); return -1; } return localPosition - bodySyntax.SpanStart; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/LanguageServices/SemanticsFactsService/SemanticFacts/ISemanticFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis.LanguageServices { internal partial interface ISemanticFacts { string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis.LanguageServices { internal partial interface ISemanticFacts { string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/SyntaxPath.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// Stores the "path" from the root of a tree to a node, allowing the node to be recovered in a /// later snapshot of the tree, under certain circumstances. /// /// The implementation stores the child indices to represent the path, so any edit which affects /// the child indices could render this object unable to recover its node. NOTE: One thing C# /// IDE has done in the past to do a better job of this is to store the fully qualified name of /// the member to at least be able to descend into the same member. We could apply the same sort /// of logic here. /// </summary> internal class SyntaxPath { // A path is made up of 'segments' that lead from root all the way down to the node. The // segment contains the index of the node in its parent, as well as the kind of the node. // The latter is not strictly necessary. However, it ensures that resolving the path against // a different tree will either return the same type of node as the original, or will fail. protected struct PathSegment { public int Ordinal { get; } public int Kind { get; } public PathSegment(int ordinal, int kind) : this() { this.Ordinal = ordinal; this.Kind = kind; } } private readonly List<PathSegment> _segments = new(); private readonly int _kind; private readonly bool _trackKinds; public SyntaxPath(SyntaxNodeOrToken nodeOrToken, bool trackKinds = true) { _trackKinds = trackKinds; _kind = nodeOrToken.RawKind; AddSegment(nodeOrToken); _segments.TrimExcess(); } private void AddSegment(SyntaxNodeOrToken nodeOrToken) { var parent = nodeOrToken.Parent; if (parent != null) { AddSegment(parent); // TODO(cyrusn): Is there any way to optimize this for large lists? I would like to // be able to do a binary search. However, there's no easy way to tell if a node // comes before or after another node when searching through a list. To determine // the location of a node, a linear walk is still needed to find it in its parent // collection. var ordinal = 0; var kind = nodeOrToken.RawKind; foreach (var child in parent.ChildNodesAndTokens()) { if (nodeOrToken == child) { _segments.Add(new PathSegment(ordinal, nodeOrToken.RawKind)); return; } if (!_trackKinds || child.RawKind == kind) { ordinal++; } } throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to recover the node at this path in the provided tree. If the node is found /// then 'true' is returned, otherwise the result is 'false' and 'node' will be null. /// </summary> public bool TryResolve(SyntaxNode? root, out SyntaxNodeOrToken nodeOrToken) { nodeOrToken = default; var current = (SyntaxNodeOrToken)root; foreach (var segment in _segments) { current = FindChild(current, segment); if (current.RawKind == 0) { return false; } } if (!_trackKinds || current.RawKind == _kind) { nodeOrToken = current; return true; } return false; } private SyntaxNodeOrToken FindChild(SyntaxNodeOrToken current, PathSegment segment) { var ordinal = segment.Ordinal; foreach (var child in current.ChildNodesAndTokens()) { if (!_trackKinds || child.RawKind == segment.Kind) { if (ordinal == 0) { return child; } else { ordinal--; } } } return default; } public bool TryResolve<TNode>(SyntaxTree syntaxTree, CancellationToken cancellationToken, [NotNullWhen(true)] out TNode? node) where TNode : SyntaxNode { return TryResolve(syntaxTree.GetRoot(cancellationToken), out node); } public bool TryResolve<TNode>(SyntaxNode? root, [NotNullWhen(true)] out TNode? node) where TNode : SyntaxNode { if (TryResolve(root, out var nodeOrToken) && nodeOrToken.IsNode && nodeOrToken.AsNode() is TNode n) { node = n; return true; } node = null; return false; } public static bool operator ==(SyntaxPath? left, SyntaxPath? right) => object.Equals(left, right); public static bool operator !=(SyntaxPath? left, SyntaxPath? right) => !object.Equals(left, right); public override bool Equals(object? obj) { var path = obj as SyntaxPath; if (path == null) { return false; } return Equals(path); } public bool Equals(SyntaxPath? other) { if (other == null) { return false; } if (object.ReferenceEquals(this, other)) { return true; } return _trackKinds == other._trackKinds && _kind == other._kind && _segments.SequenceEqual(other._segments, (x, y) => x.Equals(y)); } public override int GetHashCode() => Hash.Combine(_trackKinds, Hash.Combine(_kind, GetSegmentHashCode())); private int GetSegmentHashCode() { var hash = 1; for (var i = 0; i < _segments.Count; i++) { var segment = _segments[i]; hash = Hash.Combine(Hash.Combine(segment.Kind, segment.Ordinal), hash); } return hash; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// Stores the "path" from the root of a tree to a node, allowing the node to be recovered in a /// later snapshot of the tree, under certain circumstances. /// /// The implementation stores the child indices to represent the path, so any edit which affects /// the child indices could render this object unable to recover its node. NOTE: One thing C# /// IDE has done in the past to do a better job of this is to store the fully qualified name of /// the member to at least be able to descend into the same member. We could apply the same sort /// of logic here. /// </summary> internal class SyntaxPath { // A path is made up of 'segments' that lead from root all the way down to the node. The // segment contains the index of the node in its parent, as well as the kind of the node. // The latter is not strictly necessary. However, it ensures that resolving the path against // a different tree will either return the same type of node as the original, or will fail. protected struct PathSegment { public int Ordinal { get; } public int Kind { get; } public PathSegment(int ordinal, int kind) : this() { this.Ordinal = ordinal; this.Kind = kind; } } private readonly List<PathSegment> _segments = new(); private readonly int _kind; private readonly bool _trackKinds; public SyntaxPath(SyntaxNodeOrToken nodeOrToken, bool trackKinds = true) { _trackKinds = trackKinds; _kind = nodeOrToken.RawKind; AddSegment(nodeOrToken); _segments.TrimExcess(); } private void AddSegment(SyntaxNodeOrToken nodeOrToken) { var parent = nodeOrToken.Parent; if (parent != null) { AddSegment(parent); // TODO(cyrusn): Is there any way to optimize this for large lists? I would like to // be able to do a binary search. However, there's no easy way to tell if a node // comes before or after another node when searching through a list. To determine // the location of a node, a linear walk is still needed to find it in its parent // collection. var ordinal = 0; var kind = nodeOrToken.RawKind; foreach (var child in parent.ChildNodesAndTokens()) { if (nodeOrToken == child) { _segments.Add(new PathSegment(ordinal, nodeOrToken.RawKind)); return; } if (!_trackKinds || child.RawKind == kind) { ordinal++; } } throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to recover the node at this path in the provided tree. If the node is found /// then 'true' is returned, otherwise the result is 'false' and 'node' will be null. /// </summary> public bool TryResolve(SyntaxNode? root, out SyntaxNodeOrToken nodeOrToken) { nodeOrToken = default; var current = (SyntaxNodeOrToken)root; foreach (var segment in _segments) { current = FindChild(current, segment); if (current.RawKind == 0) { return false; } } if (!_trackKinds || current.RawKind == _kind) { nodeOrToken = current; return true; } return false; } private SyntaxNodeOrToken FindChild(SyntaxNodeOrToken current, PathSegment segment) { var ordinal = segment.Ordinal; foreach (var child in current.ChildNodesAndTokens()) { if (!_trackKinds || child.RawKind == segment.Kind) { if (ordinal == 0) { return child; } else { ordinal--; } } } return default; } public bool TryResolve<TNode>(SyntaxTree syntaxTree, CancellationToken cancellationToken, [NotNullWhen(true)] out TNode? node) where TNode : SyntaxNode { return TryResolve(syntaxTree.GetRoot(cancellationToken), out node); } public bool TryResolve<TNode>(SyntaxNode? root, [NotNullWhen(true)] out TNode? node) where TNode : SyntaxNode { if (TryResolve(root, out var nodeOrToken) && nodeOrToken.IsNode && nodeOrToken.AsNode() is TNode n) { node = n; return true; } node = null; return false; } public static bool operator ==(SyntaxPath? left, SyntaxPath? right) => object.Equals(left, right); public static bool operator !=(SyntaxPath? left, SyntaxPath? right) => !object.Equals(left, right); public override bool Equals(object? obj) { var path = obj as SyntaxPath; if (path == null) { return false; } return Equals(path); } public bool Equals(SyntaxPath? other) { if (other == null) { return false; } if (object.ReferenceEquals(this, other)) { return true; } return _trackKinds == other._trackKinds && _kind == other._kind && _segments.SequenceEqual(other._segments, (x, y) => x.Equals(y)); } public override int GetHashCode() => Hash.Combine(_trackKinds, Hash.Combine(_kind, GetSegmentHashCode())); private int GetSegmentHashCode() { var hash = 1; for (var i = 0; i < _segments.Count; i++) { var segment = _segments[i]; hash = Hash.Combine(Hash.Combine(segment.Kind, segment.Ordinal), hash); } return hash; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ObjectExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Shared.Extensions { internal static partial class ObjectExtensions { public static string GetTypeDisplayName(this object? obj) => obj == null ? "null" : obj.GetType().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. namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ObjectExtensions { public static string GetTypeDisplayName(this object? obj) => obj == null ? "null" : obj.GetType().Name; } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/CodeGeneration/ICodeGenerationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeGeneration { internal interface ICodeGenerationService : ILanguageService { /// <summary> /// Returns a newly created event declaration node from the provided event. /// </summary> SyntaxNode CreateEventDeclaration(IEventSymbol @event, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created field declaration node from the provided field. /// </summary> SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created method declaration node from the provided method. /// </summary> SyntaxNode CreateMethodDeclaration(IMethodSymbol method, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created property declaration node from the provided property. /// </summary> SyntaxNode CreatePropertyDeclaration(IPropertySymbol property, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created named type declaration node from the provided named type. /// </summary> SyntaxNode CreateNamedTypeDeclaration(INamedTypeSymbol namedType, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Returns a newly created namespace declaration node from the provided namespace. /// </summary> SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds an event into destination. /// </summary> TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a field into destination. /// </summary> TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a method into destination. /// </summary> TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a property into destination. /// </summary> TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a named type into destination. /// </summary> TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a namespace into destination. /// </summary> TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds members into destination. /// </summary> TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the parameters to destination. /// </summary> TDeclarationNode AddParameters<TDeclarationNode>(TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the attributes to destination. /// </summary> TDeclarationNode AddAttributes<TDeclarationNode>(TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target = null, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Remove the given attribute from destination. /// </summary> TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Remove the given attribute from destination. /// </summary> TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the modifiers list for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the accessibility modifiers for the given declaration node, retaining the trivia of the existing modifiers. /// </summary> TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the type for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Replace the existing members with the given newMembers for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the statements to destination. /// </summary> TDeclarationNode AddStatements<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> statements, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a field with the provided signature into destination. /// </summary> Task<Document> AddEventAsync(Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a field with the provided signature into destination. /// </summary> Task<Document> AddFieldAsync(Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a method with the provided signature into destination. /// </summary> Task<Document> AddMethodAsync(Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a property with the provided signature into destination. /// </summary> Task<Document> AddPropertyAsync(Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a named type into destination. /// </summary> Task<Document> AddNamedTypeAsync(Solution solution, INamedTypeSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a named type into destination. /// </summary> Task<Document> AddNamedTypeAsync(Solution solution, INamespaceSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a namespace into destination. /// </summary> Task<Document> AddNamespaceAsync(Solution solution, INamespaceSymbol destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a namespace or type into destination. /// </summary> Task<Document> AddNamespaceOrTypeAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds all the provided members into destination. /// </summary> Task<Document> AddMembersAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// <c>true</c> if destination is a location where other symbols can be added to. /// </summary> bool CanAddTo(ISymbol destination, Solution solution, CancellationToken cancellationToken = default); /// <summary> /// <c>true</c> if destination is a location where other symbols can be added to. /// </summary> bool CanAddTo(SyntaxNode destination, Solution solution, CancellationToken cancellationToken = default); /// <summary> /// Return the most relevant declaration to namespaceOrType, /// it will first search the context node contained within, /// then the declaration in the same file, then non auto-generated file, /// then all the potential location. Return null if no declaration. /// </summary> Task<SyntaxNode?> FindMostRelevantNameSpaceOrTypeDeclarationAsync(Solution solution, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeGeneration { internal interface ICodeGenerationService : ILanguageService { /// <summary> /// Returns a newly created event declaration node from the provided event. /// </summary> SyntaxNode CreateEventDeclaration(IEventSymbol @event, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created field declaration node from the provided field. /// </summary> SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created method declaration node from the provided method. /// </summary> SyntaxNode CreateMethodDeclaration(IMethodSymbol method, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created property declaration node from the provided property. /// </summary> SyntaxNode CreatePropertyDeclaration(IPropertySymbol property, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null); /// <summary> /// Returns a newly created named type declaration node from the provided named type. /// </summary> SyntaxNode CreateNamedTypeDeclaration(INamedTypeSymbol namedType, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Returns a newly created namespace declaration node from the provided namespace. /// </summary> SyntaxNode CreateNamespaceDeclaration(INamespaceSymbol @namespace, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds an event into destination. /// </summary> TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a field into destination. /// </summary> TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a method into destination. /// </summary> TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a property into destination. /// </summary> TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a named type into destination. /// </summary> TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a namespace into destination. /// </summary> TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds members into destination. /// </summary> TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the parameters to destination. /// </summary> TDeclarationNode AddParameters<TDeclarationNode>(TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the attributes to destination. /// </summary> TDeclarationNode AddAttributes<TDeclarationNode>(TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target = null, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Remove the given attribute from destination. /// </summary> TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Remove the given attribute from destination. /// </summary> TDeclarationNode RemoveAttribute<TDeclarationNode>(TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the modifiers list for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the accessibility modifiers for the given declaration node, retaining the trivia of the existing modifiers. /// </summary> TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Update the type for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Replace the existing members with the given newMembers for the given declaration node. /// </summary> TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds the statements to destination. /// </summary> TDeclarationNode AddStatements<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> statements, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default) where TDeclarationNode : SyntaxNode; /// <summary> /// Adds a field with the provided signature into destination. /// </summary> Task<Document> AddEventAsync(Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a field with the provided signature into destination. /// </summary> Task<Document> AddFieldAsync(Solution solution, INamedTypeSymbol destination, IFieldSymbol field, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a method with the provided signature into destination. /// </summary> Task<Document> AddMethodAsync(Solution solution, INamedTypeSymbol destination, IMethodSymbol method, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a property with the provided signature into destination. /// </summary> Task<Document> AddPropertyAsync(Solution solution, INamedTypeSymbol destination, IPropertySymbol property, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a named type into destination. /// </summary> Task<Document> AddNamedTypeAsync(Solution solution, INamedTypeSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a named type into destination. /// </summary> Task<Document> AddNamedTypeAsync(Solution solution, INamespaceSymbol destination, INamedTypeSymbol namedType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a namespace into destination. /// </summary> Task<Document> AddNamespaceAsync(Solution solution, INamespaceSymbol destination, INamespaceSymbol @namespace, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds a namespace or type into destination. /// </summary> Task<Document> AddNamespaceOrTypeAsync(Solution solution, INamespaceSymbol destination, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// Adds all the provided members into destination. /// </summary> Task<Document> AddMembersAsync(Solution solution, INamedTypeSymbol destination, IEnumerable<ISymbol> members, CodeGenerationOptions? options = null, CancellationToken cancellationToken = default); /// <summary> /// <c>true</c> if destination is a location where other symbols can be added to. /// </summary> bool CanAddTo(ISymbol destination, Solution solution, CancellationToken cancellationToken = default); /// <summary> /// <c>true</c> if destination is a location where other symbols can be added to. /// </summary> bool CanAddTo(SyntaxNode destination, Solution solution, CancellationToken cancellationToken = default); /// <summary> /// Return the most relevant declaration to namespaceOrType, /// it will first search the context node contained within, /// then the declaration in the same file, then non auto-generated file, /// then all the potential location. Return null if no declaration. /// </summary> Task<SyntaxNode?> FindMostRelevantNameSpaceOrTypeDeclarationAsync(Solution solution, INamespaceOrTypeSymbol namespaceOrType, CodeGenerationOptions options, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncExceptionHandlerRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The purpose of this rewriter is to replace await-containing catch and finally handlers /// with surrogate replacements that keep actual handler code in regular code blocks. /// That allows these constructs to be further lowered at the async lowering pass. /// </summary> internal sealed class AsyncExceptionHandlerRewriter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private readonly SyntheticBoundNodeFactory _F; private readonly AwaitInFinallyAnalysis _analysis; private AwaitCatchFrame _currentAwaitCatchFrame; private AwaitFinallyFrame _currentAwaitFinallyFrame = new AwaitFinallyFrame(); private AsyncExceptionHandlerRewriter( MethodSymbol containingMethod, NamedTypeSymbol containingType, SyntheticBoundNodeFactory factory, AwaitInFinallyAnalysis analysis) { _F = factory; _F.CurrentFunction = containingMethod; Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2)); _analysis = analysis; } /// <summary> /// Lower a block of code by performing local rewritings. /// The goal is to not have exception handlers that contain awaits in them. /// /// 1) Await containing finally blocks: /// The general strategy is to rewrite await containing handlers into synthetic handlers. /// Synthetic handlers are not handlers in IL sense so it is ok to have awaits in them. /// Since synthetic handlers are just blocks, we have to deal with pending exception/branch/return manually /// (this is the hard part of the rewrite). /// /// try{ /// code; /// }finally{ /// handler; /// } /// /// Into ===> /// /// Exception ex = null; /// int pendingBranch = 0; /// /// try{ /// code; // any gotos/returns are rewritten to code that pends the necessary info and goes to finallyLabel /// goto finallyLabel; /// }catch (ex){ // essentially pend the currently active exception /// }; /// /// finallyLabel: /// { /// handler; /// if (ex != null) throw ex; // unpend the exception /// unpend branches/return /// } /// /// 2) Await containing catches: /// try{ /// code; /// }catch (Exception ex){ /// handler; /// throw; /// } /// /// /// Into ===> /// /// Object pendingException; /// int pendingCatch = 0; /// /// try{ /// code; /// }catch (Exception temp){ // essentially pend the currently active exception /// pendingException = temp; /// pendingCatch = 1; /// }; /// /// switch(pendingCatch): /// { /// case 1: /// { /// Exception ex = (Exception)pendingException; /// handler; /// throw pendingException /// } /// } /// </summary> public static BoundStatement Rewrite( MethodSymbol containingSymbol, NamedTypeSymbol containingType, BoundStatement statement, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { Debug.Assert(containingSymbol != null); Debug.Assert((object)containingType != null); Debug.Assert(statement != null); Debug.Assert(compilationState != null); Debug.Assert(diagnostics != null); var analysis = new AwaitInFinallyAnalysis(statement); if (!analysis.ContainsAwaitInHandlers()) { return statement; } var factory = new SyntheticBoundNodeFactory(containingSymbol, statement.Syntax, compilationState, diagnostics); var rewriter = new AsyncExceptionHandlerRewriter(containingSymbol, containingType, factory, analysis); var loweredStatement = (BoundStatement)rewriter.Visit(statement); return loweredStatement; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var tryStatementSyntax = node.Syntax; // If you add a syntax kind to the assertion below, please also ensure // that the scenario has been tested with Edit-and-Continue. Debug.Assert( tryStatementSyntax.IsKind(SyntaxKind.TryStatement) || tryStatementSyntax.IsKind(SyntaxKind.UsingStatement) || tryStatementSyntax.IsKind(SyntaxKind.ForEachStatement) || tryStatementSyntax.IsKind(SyntaxKind.ForEachVariableStatement) || tryStatementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) || tryStatementSyntax.IsKind(SyntaxKind.LockStatement)); BoundStatement finalizedRegion; BoundBlock rewrittenFinally; var finallyContainsAwaits = _analysis.FinallyContainsAwaits(node); if (!finallyContainsAwaits) { finalizedRegion = RewriteFinalizedRegion(node); rewrittenFinally = (BoundBlock)this.Visit(node.FinallyBlockOpt); if (rewrittenFinally == null) { return finalizedRegion; } var asTry = finalizedRegion as BoundTryStatement; if (asTry != null) { // since finalized region is a try we can just attach finally to it Debug.Assert(asTry.FinallyBlockOpt == null); return asTry.Update(asTry.TryBlock, asTry.CatchBlocks, rewrittenFinally, asTry.FinallyLabelOpt, asTry.PreferFaultHandler); } else { // wrap finalizedRegion into a Try with a finally. return _F.Try((BoundBlock)finalizedRegion, ImmutableArray<BoundCatchBlock>.Empty, rewrittenFinally); } } // rewrite finalized region (try and catches) in the current frame var frame = PushFrame(node); finalizedRegion = RewriteFinalizedRegion(node); rewrittenFinally = (BoundBlock)this.VisitBlock(node.FinallyBlockOpt); PopFrame(); var exceptionType = _F.SpecialType(SpecialType.System_Object); var pendingExceptionLocal = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(exceptionType), SynthesizedLocalKind.TryAwaitPendingException, tryStatementSyntax); var finallyLabel = _F.GenerateLabel("finallyLabel"); var pendingBranchVar = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(_F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingBranch, tryStatementSyntax); var catchAll = _F.Catch(_F.Local(pendingExceptionLocal), _F.Block()); var catchAndPendException = _F.Try( _F.Block( finalizedRegion, _F.HiddenSequencePoint(), _F.Goto(finallyLabel), PendBranches(frame, pendingBranchVar, finallyLabel)), ImmutableArray.Create(catchAll), finallyLabel: finallyLabel); BoundBlock syntheticFinallyBlock = _F.Block( _F.HiddenSequencePoint(), _F.Label(finallyLabel), rewrittenFinally, _F.HiddenSequencePoint(), UnpendException(pendingExceptionLocal), UnpendBranches( frame, pendingBranchVar, pendingExceptionLocal)); BoundStatement syntheticFinally = syntheticFinallyBlock; if (_F.CurrentFunction.IsAsync && _F.CurrentFunction.IsIterator) { // We wrap this block so that it can be processed as a finally block by async-iterator rewriting syntheticFinally = _F.ExtractedFinallyBlock(syntheticFinallyBlock); } var locals = ArrayBuilder<LocalSymbol>.GetInstance(); var statements = ArrayBuilder<BoundStatement>.GetInstance(); statements.Add(_F.HiddenSequencePoint()); locals.Add(pendingExceptionLocal); statements.Add(_F.Assignment(_F.Local(pendingExceptionLocal), _F.Default(pendingExceptionLocal.Type))); locals.Add(pendingBranchVar); statements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Default(pendingBranchVar.Type))); LocalSymbol returnLocal = frame.returnValue; if (returnLocal != null) { locals.Add(returnLocal); } statements.Add(catchAndPendException); statements.Add(syntheticFinally); var completeTry = _F.Block( locals.ToImmutableAndFree(), statements.ToImmutableAndFree()); return completeTry; } private BoundBlock PendBranches( AwaitFinallyFrame frame, LocalSymbol pendingBranchVar, LabelSymbol finallyLabel) { var bodyStatements = ArrayBuilder<BoundStatement>.GetInstance(); // handle proxy labels if have any var proxiedLabels = frame.proxiedLabels; var proxyLabels = frame.proxyLabels; // skip 0 - it means we took no explicit branches int i = 1; if (proxiedLabels != null) { for (int cnt = proxiedLabels.Count; i <= cnt; i++) { var proxied = proxiedLabels[i - 1]; var proxy = proxyLabels[proxied]; PendBranch(bodyStatements, proxy, i, pendingBranchVar, finallyLabel); } } var returnProxy = frame.returnProxyLabel; if (returnProxy != null) { PendBranch(bodyStatements, returnProxy, i, pendingBranchVar, finallyLabel); } return _F.Block(bodyStatements.ToImmutableAndFree()); } private void PendBranch( ArrayBuilder<BoundStatement> bodyStatements, LabelSymbol proxy, int i, LocalSymbol pendingBranchVar, LabelSymbol finallyLabel) { // branch lands here bodyStatements.Add(_F.Label(proxy)); // pend the branch bodyStatements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Literal(i))); // skip other proxies bodyStatements.Add(_F.Goto(finallyLabel)); } private BoundStatement UnpendBranches( AwaitFinallyFrame frame, SynthesizedLocal pendingBranchVar, SynthesizedLocal pendingException) { var parent = frame.ParentOpt; // handle proxy labels if have any var proxiedLabels = frame.proxiedLabels; // skip 0 - it means we took no explicit branches int i = 1; var cases = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance(); if (proxiedLabels != null) { for (int cnt = proxiedLabels.Count; i <= cnt; i++) { var target = proxiedLabels[i - 1]; var parentProxy = parent.ProxyLabelIfNeeded(target); var caseStatement = _F.SwitchSection(i, _F.Goto(parentProxy)); cases.Add(caseStatement); } } if (frame.returnProxyLabel != null) { BoundLocal pendingValue = null; if (frame.returnValue != null) { pendingValue = _F.Local(frame.returnValue); } SynthesizedLocal returnValue; BoundStatement unpendReturn; var returnLabel = parent.ProxyReturnIfNeeded(_F.CurrentFunction, pendingValue, out returnValue); if (returnLabel == null) { unpendReturn = new BoundReturnStatement(_F.Syntax, RefKind.None, pendingValue); } else { if (pendingValue == null) { unpendReturn = _F.Goto(returnLabel); } else { unpendReturn = _F.Block( _F.Assignment( _F.Local(returnValue), pendingValue), _F.Goto(returnLabel)); } } var caseStatement = _F.SwitchSection(i, unpendReturn); cases.Add(caseStatement); } return _F.Switch(_F.Local(pendingBranchVar), cases.ToImmutableAndFree()); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { BoundExpression caseExpressionOpt = (BoundExpression)this.Visit(node.CaseExpressionOpt); BoundLabel labelExpressionOpt = (BoundLabel)this.Visit(node.LabelExpressionOpt); var proxyLabel = _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label); return node.Update(proxyLabel, caseExpressionOpt, labelExpressionOpt); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { Debug.Assert(node.Label == _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label), "conditional leave?"); return base.VisitConditionalGoto(node); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { SynthesizedLocal returnValue; var returnLabel = _currentAwaitFinallyFrame.ProxyReturnIfNeeded( _F.CurrentFunction, node.ExpressionOpt, out returnValue); if (returnLabel == null) { return base.VisitReturnStatement(node); } var returnExpr = (BoundExpression)(this.Visit(node.ExpressionOpt)); if (returnExpr != null) { return _F.Block( _F.Assignment( _F.Local(returnValue), returnExpr), _F.Goto( returnLabel)); } else { return _F.Goto(returnLabel); } } private BoundStatement UnpendException(LocalSymbol pendingExceptionLocal) { // create a temp. // pendingExceptionLocal will certainly be captured, no need to access it over and over. LocalSymbol obj = _F.SynthesizedLocal(_F.SpecialType(SpecialType.System_Object)); var objInit = _F.Assignment(_F.Local(obj), _F.Local(pendingExceptionLocal)); // throw pendingExceptionLocal; BoundStatement rethrow = Rethrow(obj); return _F.Block( ImmutableArray.Create<LocalSymbol>(obj), objInit, _F.If( _F.ObjectNotEqual( _F.Local(obj), _F.Null(obj.Type)), rethrow)); } private BoundStatement Rethrow(LocalSymbol obj) { // conservative rethrow BoundStatement rethrow = _F.Throw(_F.Local(obj)); var exceptionDispatchInfoCapture = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, isOptional: true); var exceptionDispatchInfoThrow = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, isOptional: true); // if these helpers are available, we can rethrow with original stack info // as long as it derives from Exception if (exceptionDispatchInfoCapture != null && exceptionDispatchInfoThrow != null) { var ex = _F.SynthesizedLocal(_F.WellKnownType(WellKnownType.System_Exception)); var assignment = _F.Assignment( _F.Local(ex), _F.As(_F.Local(obj), ex.Type)); // better rethrow rethrow = _F.Block( ImmutableArray.Create(ex), assignment, _F.If(_F.ObjectEqual(_F.Local(ex), _F.Null(ex.Type)), rethrow), // ExceptionDispatchInfo.Capture(pendingExceptionLocal).Throw(); _F.ExpressionStatement( _F.Call( _F.StaticCall( exceptionDispatchInfoCapture.ContainingType, exceptionDispatchInfoCapture, _F.Local(ex)), exceptionDispatchInfoThrow))); } return rethrow; } /// <summary> /// Rewrites Try/Catch part of the Try/Catch/Finally /// </summary> private BoundStatement RewriteFinalizedRegion(BoundTryStatement node) { var rewrittenTry = (BoundBlock)this.VisitBlock(node.TryBlock); var catches = node.CatchBlocks; if (catches.IsDefaultOrEmpty) { return rewrittenTry; } var origAwaitCatchFrame = _currentAwaitCatchFrame; _currentAwaitCatchFrame = null; var rewrittenCatches = this.VisitList(node.CatchBlocks); BoundStatement tryWithCatches = _F.Try(rewrittenTry, rewrittenCatches); var currentAwaitCatchFrame = _currentAwaitCatchFrame; if (currentAwaitCatchFrame != null) { var handledLabel = _F.GenerateLabel("handled"); var handlersList = currentAwaitCatchFrame.handlers; var handlers = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance(handlersList.Count); for (int i = 0, l = handlersList.Count; i < l; i++) { handlers.Add(_F.SwitchSection( i + 1, _F.Block( handlersList[i], _F.Goto(handledLabel)))); } tryWithCatches = _F.Block( ImmutableArray.Create<LocalSymbol>( currentAwaitCatchFrame.pendingCaughtException, currentAwaitCatchFrame.pendingCatch). AddRange(currentAwaitCatchFrame.GetHoistedLocals()), _F.HiddenSequencePoint(), _F.Assignment( _F.Local(currentAwaitCatchFrame.pendingCatch), _F.Default(currentAwaitCatchFrame.pendingCatch.Type)), tryWithCatches, _F.HiddenSequencePoint(), _F.Switch( _F.Local(currentAwaitCatchFrame.pendingCatch), handlers.ToImmutableAndFree()), _F.HiddenSequencePoint(), _F.Label(handledLabel)); } _currentAwaitCatchFrame = origAwaitCatchFrame; return tryWithCatches; } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { if (!_analysis.CatchContainsAwait(node)) { var origCurrentAwaitCatchFrame = _currentAwaitCatchFrame; _currentAwaitCatchFrame = null; var result = base.VisitCatchBlock(node); _currentAwaitCatchFrame = origCurrentAwaitCatchFrame; return result; } var currentAwaitCatchFrame = _currentAwaitCatchFrame; if (currentAwaitCatchFrame == null) { Debug.Assert(node.Syntax.IsKind(SyntaxKind.CatchClause)); var tryStatementSyntax = (TryStatementSyntax)node.Syntax.Parent; currentAwaitCatchFrame = _currentAwaitCatchFrame = new AwaitCatchFrame(_F, tryStatementSyntax); } var catchType = node.ExceptionTypeOpt ?? _F.SpecialType(SpecialType.System_Object); var catchTemp = _F.SynthesizedLocal(catchType); var storePending = _F.AssignmentExpression( _F.Local(currentAwaitCatchFrame.pendingCaughtException), _F.Convert(currentAwaitCatchFrame.pendingCaughtException.Type, _F.Local(catchTemp))); var setPendingCatchNum = _F.Assignment( _F.Local(currentAwaitCatchFrame.pendingCatch), _F.Literal(currentAwaitCatchFrame.handlers.Count + 1)); // catch (ExType exTemp) // { // pendingCaughtException = exTemp; // catchNo = X; // } BoundCatchBlock catchAndPend; ImmutableArray<LocalSymbol> handlerLocals; var filterPrologueOpt = node.ExceptionFilterPrologueOpt; var filterOpt = node.ExceptionFilterOpt; if (filterOpt == null) { Debug.Assert(filterPrologueOpt is null); // store pending exception // as the first statement in a catch catchAndPend = node.Update( ImmutableArray.Create(catchTemp), _F.Local(catchTemp), catchType, exceptionFilterPrologueOpt: filterPrologueOpt, exceptionFilterOpt: null, body: _F.Block( _F.HiddenSequencePoint(), _F.ExpressionStatement(storePending), setPendingCatchNum), isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll); // catch locals live on the synthetic catch handler block handlerLocals = node.Locals; } else { handlerLocals = ImmutableArray<LocalSymbol>.Empty; // catch locals move up into hoisted locals // since we might need to access them from both the filter and the catch foreach (var local in node.Locals) { currentAwaitCatchFrame.HoistLocal(local, _F); } // store pending exception // as the first expression in a filter var sourceOpt = node.ExceptionSourceOpt; var rewrittenPrologue = (BoundStatementList)this.Visit(filterPrologueOpt); var rewrittenFilter = (BoundExpression)this.Visit(filterOpt); var newFilter = sourceOpt == null ? _F.MakeSequence( storePending, rewrittenFilter) : _F.MakeSequence( storePending, AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame), rewrittenFilter); catchAndPend = node.Update( ImmutableArray.Create(catchTemp), _F.Local(catchTemp), catchType, exceptionFilterPrologueOpt: rewrittenPrologue, exceptionFilterOpt: newFilter, body: _F.Block( _F.HiddenSequencePoint(), setPendingCatchNum), isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll); } var handlerStatements = ArrayBuilder<BoundStatement>.GetInstance(); handlerStatements.Add(_F.HiddenSequencePoint()); if (filterOpt == null) { var sourceOpt = node.ExceptionSourceOpt; if (sourceOpt != null) { BoundExpression assignSource = AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame); handlerStatements.Add(_F.ExpressionStatement(assignSource)); } } handlerStatements.Add((BoundStatement)this.Visit(node.Body)); var handler = _F.Block( handlerLocals, handlerStatements.ToImmutableAndFree() ); currentAwaitCatchFrame.handlers.Add(handler); return catchAndPend; } private BoundExpression AssignCatchSource(BoundExpression rewrittenSource, AwaitCatchFrame currentAwaitCatchFrame) { BoundExpression assignSource = null; if (rewrittenSource != null) { // exceptionSource = (exceptionSourceType)pendingCaughtException; assignSource = _F.AssignmentExpression( rewrittenSource, _F.Convert( rewrittenSource.Type, _F.Local(currentAwaitCatchFrame.pendingCaughtException))); } return assignSource; } public override BoundNode VisitLocal(BoundLocal node) { var catchFrame = _currentAwaitCatchFrame; LocalSymbol hoistedLocal; if (catchFrame == null || !catchFrame.TryGetHoistedLocal(node.LocalSymbol, out hoistedLocal)) { return base.VisitLocal(node); } return node.Update(hoistedLocal, node.ConstantValueOpt, hoistedLocal.Type); } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { if (node.ExpressionOpt != null || _currentAwaitCatchFrame == null) { return base.VisitThrowStatement(node); } return Rethrow(_currentAwaitCatchFrame.pendingCaughtException); } public override BoundNode VisitLambda(BoundLambda node) { var oldContainingSymbol = _F.CurrentFunction; var oldAwaitFinallyFrame = _currentAwaitFinallyFrame; _F.CurrentFunction = node.Symbol; _currentAwaitFinallyFrame = new AwaitFinallyFrame(); var result = base.VisitLambda(node); _F.CurrentFunction = oldContainingSymbol; _currentAwaitFinallyFrame = oldAwaitFinallyFrame; return result; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var oldContainingSymbol = _F.CurrentFunction; var oldAwaitFinallyFrame = _currentAwaitFinallyFrame; _F.CurrentFunction = node.Symbol; _currentAwaitFinallyFrame = new AwaitFinallyFrame(); var result = base.VisitLocalFunctionStatement(node); _F.CurrentFunction = oldContainingSymbol; _currentAwaitFinallyFrame = oldAwaitFinallyFrame; return result; } private AwaitFinallyFrame PushFrame(BoundTryStatement statement) { var newFrame = new AwaitFinallyFrame(_currentAwaitFinallyFrame, _analysis.Labels(statement), (StatementSyntax)statement.Syntax); _currentAwaitFinallyFrame = newFrame; return newFrame; } private void PopFrame() { var result = _currentAwaitFinallyFrame; _currentAwaitFinallyFrame = result.ParentOpt; } /// <summary> /// Analyzes method body for try blocks with awaits in finally blocks /// Also collects labels that such blocks contain. /// </summary> private sealed class AwaitInFinallyAnalysis : LabelCollector { // all try blocks with yields in them and complete set of labels inside those try blocks // NOTE: non-yielding try blocks are transparently ignored - i.e. their labels are included // in the label set of the nearest yielding-try parent private Dictionary<BoundTryStatement, HashSet<LabelSymbol>> _labelsInInterestingTry; private HashSet<BoundCatchBlock> _awaitContainingCatches; // transient accumulators. private bool _seenAwait; public AwaitInFinallyAnalysis(BoundStatement body) { _seenAwait = false; this.Visit(body); } /// <summary> /// Returns true if a finally of the given try contains awaits /// </summary> public bool FinallyContainsAwaits(BoundTryStatement statement) { return _labelsInInterestingTry != null && _labelsInInterestingTry.ContainsKey(statement); } /// <summary> /// Returns true if a catch contains awaits /// </summary> internal bool CatchContainsAwait(BoundCatchBlock node) { return _awaitContainingCatches != null && _awaitContainingCatches.Contains(node); } /// <summary> /// Returns true if body contains await in a finally block. /// </summary> public bool ContainsAwaitInHandlers() { return _labelsInInterestingTry != null || _awaitContainingCatches != null; } /// <summary> /// Labels reachable from within this frame without invoking its finally. /// null if there are no such labels. /// </summary> internal HashSet<LabelSymbol> Labels(BoundTryStatement statement) { return _labelsInInterestingTry[statement]; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var origLabels = this.currentLabels; this.currentLabels = null; Visit(node.TryBlock); VisitList(node.CatchBlocks); var origSeenAwait = _seenAwait; _seenAwait = false; Visit(node.FinallyBlockOpt); if (_seenAwait) { // this try has awaits in the finally ! var labelsInInterestingTry = _labelsInInterestingTry; if (labelsInInterestingTry == null) { _labelsInInterestingTry = labelsInInterestingTry = new Dictionary<BoundTryStatement, HashSet<LabelSymbol>>(); } labelsInInterestingTry.Add(node, currentLabels); currentLabels = origLabels; } else { // this is a boring try without awaits in finally // currentLabels = currentLabels U origLabels ; if (currentLabels == null) { currentLabels = origLabels; } else if (origLabels != null) { currentLabels.UnionWith(origLabels); } } _seenAwait = _seenAwait | origSeenAwait; return null; } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { var origSeenAwait = _seenAwait; _seenAwait = false; var result = base.VisitCatchBlock(node); if (_seenAwait) { var awaitContainingCatches = _awaitContainingCatches; if (awaitContainingCatches == null) { _awaitContainingCatches = awaitContainingCatches = new HashSet<BoundCatchBlock>(); } _awaitContainingCatches.Add(node); } _seenAwait |= origSeenAwait; return result; } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { _seenAwait = true; return base.VisitAwaitExpression(node); } public override BoundNode VisitLambda(BoundLambda node) { var origLabels = this.currentLabels; var origSeenAwait = _seenAwait; this.currentLabels = null; _seenAwait = false; base.VisitLambda(node); this.currentLabels = origLabels; _seenAwait = origSeenAwait; return null; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var origLabels = this.currentLabels; var origSeenAwait = _seenAwait; this.currentLabels = null; _seenAwait = false; base.VisitLocalFunctionStatement(node); this.currentLabels = origLabels; _seenAwait = origSeenAwait; return null; } } // storage of various information about a given finally frame private sealed class AwaitFinallyFrame { // Enclosing frame. Root frame does not have parent. public readonly AwaitFinallyFrame ParentOpt; // labels within this frame (branching to these labels does not go through finally). public readonly HashSet<LabelSymbol> LabelsOpt; // the try or using-await statement the frame is associated with private readonly StatementSyntax _statementSyntaxOpt; // proxy labels for branches leaving the frame. // we build this on demand once we encounter leaving branches. // subsequent leaves to an already proxied label redirected to the proxy. // At the proxy label we will execute finally and forward the control flow // to the actual destination. (which could be proxied again in the parent) public Dictionary<LabelSymbol, LabelSymbol> proxyLabels; public List<LabelSymbol> proxiedLabels; public GeneratedLabelSymbol returnProxyLabel; public SynthesizedLocal returnValue; public AwaitFinallyFrame() { // root frame } public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet<LabelSymbol> labelsOpt, StatementSyntax statementSyntax) { Debug.Assert(parent != null); Debug.Assert(statementSyntax != null); Debug.Assert(statementSyntax.Kind() == SyntaxKind.TryStatement || (statementSyntax.Kind() == SyntaxKind.UsingStatement && ((UsingStatementSyntax)statementSyntax).AwaitKeyword != default) || (statementSyntax.Kind() == SyntaxKind.ForEachStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) || (statementSyntax.Kind() == SyntaxKind.ForEachVariableStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) || (statementSyntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)statementSyntax).AwaitKeyword != default)); this.ParentOpt = parent; this.LabelsOpt = labelsOpt; _statementSyntaxOpt = statementSyntax; } public bool IsRoot() { return this.ParentOpt == null; } // returns a proxy for a label if branch must be hijacked to run finally // otherwise returns same label back public LabelSymbol ProxyLabelIfNeeded(LabelSymbol label) { // no need to proxy a label in the current frame or when we are at the root if (this.IsRoot() || (LabelsOpt != null && LabelsOpt.Contains(label))) { return label; } var proxyLabels = this.proxyLabels; var proxiedLabels = this.proxiedLabels; if (proxyLabels == null) { this.proxyLabels = proxyLabels = new Dictionary<LabelSymbol, LabelSymbol>(); this.proxiedLabels = proxiedLabels = new List<LabelSymbol>(); } LabelSymbol proxy; if (!proxyLabels.TryGetValue(label, out proxy)) { proxy = new GeneratedLabelSymbol("proxy" + label.Name); proxyLabels.Add(label, proxy); proxiedLabels.Add(label); } return proxy; } public LabelSymbol ProxyReturnIfNeeded( MethodSymbol containingMethod, BoundExpression valueOpt, out SynthesizedLocal returnValue) { returnValue = null; // no need to proxy returns at the root if (this.IsRoot()) { return null; } var returnProxy = this.returnProxyLabel; if (returnProxy == null) { this.returnProxyLabel = returnProxy = new GeneratedLabelSymbol("returnProxy"); } if (valueOpt != null) { returnValue = this.returnValue; if (returnValue == null) { Debug.Assert(_statementSyntaxOpt != null); this.returnValue = returnValue = new SynthesizedLocal(containingMethod, TypeWithAnnotations.Create(valueOpt.Type), SynthesizedLocalKind.AsyncMethodReturnValue, _statementSyntaxOpt); } } return returnProxy; } } private sealed class AwaitCatchFrame { // object, stores the original caught exception // used to initialize the exception source inside the handler // also used in rethrow statements public readonly SynthesizedLocal pendingCaughtException; // int, stores the number of pending catch // 0 - means no catches are pending. public readonly SynthesizedLocal pendingCatch; // synthetic handlers produced by catch rewrite. // they will become switch sections when pending exception is dispatched. public readonly List<BoundBlock> handlers; // when catch local must be used from a filter // we need to "hoist" it up to ensure that both the filter // and the catch access the same variable. // NOTE: it must be the same variable, not just same value. // The difference would be observable if filter mutates the variable // or/and if a variable gets lifted into a closure. private readonly Dictionary<LocalSymbol, LocalSymbol> _hoistedLocals; private readonly List<LocalSymbol> _orderedHoistedLocals; public AwaitCatchFrame(SyntheticBoundNodeFactory F, TryStatementSyntax tryStatementSyntax) { this.pendingCaughtException = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Object)), SynthesizedLocalKind.TryAwaitPendingCaughtException, tryStatementSyntax); this.pendingCatch = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingCatch, tryStatementSyntax); this.handlers = new List<BoundBlock>(); _hoistedLocals = new Dictionary<LocalSymbol, LocalSymbol>(); _orderedHoistedLocals = new List<LocalSymbol>(); } public void HoistLocal(LocalSymbol local, SyntheticBoundNodeFactory F) { if (!_hoistedLocals.Keys.Any(l => l.Name == local.Name && TypeSymbol.Equals(l.Type, local.Type, TypeCompareKind.ConsiderEverything2))) { _hoistedLocals.Add(local, local); _orderedHoistedLocals.Add(local); return; } // code uses "await" in two sibling catches with exception filters // locals with same names and types may cause problems if they are lifted // and become fields with identical signatures. // To avoid such problems we will mangle the name of the second local. // This will only affect debugging of this extremely rare case. Debug.Assert(pendingCatch.SyntaxOpt.IsKind(SyntaxKind.TryStatement)); var newLocal = F.SynthesizedLocal(local.Type, pendingCatch.SyntaxOpt, kind: SynthesizedLocalKind.ExceptionFilterAwaitHoistedExceptionLocal); _hoistedLocals.Add(local, newLocal); _orderedHoistedLocals.Add(newLocal); } public IEnumerable<LocalSymbol> GetHoistedLocals() { return _orderedHoistedLocals; } public bool TryGetHoistedLocal(LocalSymbol originalLocal, out LocalSymbol hoistedLocal) { return _hoistedLocals.TryGetValue(originalLocal, out hoistedLocal); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The purpose of this rewriter is to replace await-containing catch and finally handlers /// with surrogate replacements that keep actual handler code in regular code blocks. /// That allows these constructs to be further lowered at the async lowering pass. /// </summary> internal sealed class AsyncExceptionHandlerRewriter : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private readonly SyntheticBoundNodeFactory _F; private readonly AwaitInFinallyAnalysis _analysis; private AwaitCatchFrame _currentAwaitCatchFrame; private AwaitFinallyFrame _currentAwaitFinallyFrame = new AwaitFinallyFrame(); private AsyncExceptionHandlerRewriter( MethodSymbol containingMethod, NamedTypeSymbol containingType, SyntheticBoundNodeFactory factory, AwaitInFinallyAnalysis analysis) { _F = factory; _F.CurrentFunction = containingMethod; Debug.Assert(TypeSymbol.Equals(factory.CurrentType, (containingType ?? containingMethod.ContainingType), TypeCompareKind.ConsiderEverything2)); _analysis = analysis; } /// <summary> /// Lower a block of code by performing local rewritings. /// The goal is to not have exception handlers that contain awaits in them. /// /// 1) Await containing finally blocks: /// The general strategy is to rewrite await containing handlers into synthetic handlers. /// Synthetic handlers are not handlers in IL sense so it is ok to have awaits in them. /// Since synthetic handlers are just blocks, we have to deal with pending exception/branch/return manually /// (this is the hard part of the rewrite). /// /// try{ /// code; /// }finally{ /// handler; /// } /// /// Into ===> /// /// Exception ex = null; /// int pendingBranch = 0; /// /// try{ /// code; // any gotos/returns are rewritten to code that pends the necessary info and goes to finallyLabel /// goto finallyLabel; /// }catch (ex){ // essentially pend the currently active exception /// }; /// /// finallyLabel: /// { /// handler; /// if (ex != null) throw ex; // unpend the exception /// unpend branches/return /// } /// /// 2) Await containing catches: /// try{ /// code; /// }catch (Exception ex){ /// handler; /// throw; /// } /// /// /// Into ===> /// /// Object pendingException; /// int pendingCatch = 0; /// /// try{ /// code; /// }catch (Exception temp){ // essentially pend the currently active exception /// pendingException = temp; /// pendingCatch = 1; /// }; /// /// switch(pendingCatch): /// { /// case 1: /// { /// Exception ex = (Exception)pendingException; /// handler; /// throw pendingException /// } /// } /// </summary> public static BoundStatement Rewrite( MethodSymbol containingSymbol, NamedTypeSymbol containingType, BoundStatement statement, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { Debug.Assert(containingSymbol != null); Debug.Assert((object)containingType != null); Debug.Assert(statement != null); Debug.Assert(compilationState != null); Debug.Assert(diagnostics != null); var analysis = new AwaitInFinallyAnalysis(statement); if (!analysis.ContainsAwaitInHandlers()) { return statement; } var factory = new SyntheticBoundNodeFactory(containingSymbol, statement.Syntax, compilationState, diagnostics); var rewriter = new AsyncExceptionHandlerRewriter(containingSymbol, containingType, factory, analysis); var loweredStatement = (BoundStatement)rewriter.Visit(statement); return loweredStatement; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var tryStatementSyntax = node.Syntax; // If you add a syntax kind to the assertion below, please also ensure // that the scenario has been tested with Edit-and-Continue. Debug.Assert( tryStatementSyntax.IsKind(SyntaxKind.TryStatement) || tryStatementSyntax.IsKind(SyntaxKind.UsingStatement) || tryStatementSyntax.IsKind(SyntaxKind.ForEachStatement) || tryStatementSyntax.IsKind(SyntaxKind.ForEachVariableStatement) || tryStatementSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) || tryStatementSyntax.IsKind(SyntaxKind.LockStatement)); BoundStatement finalizedRegion; BoundBlock rewrittenFinally; var finallyContainsAwaits = _analysis.FinallyContainsAwaits(node); if (!finallyContainsAwaits) { finalizedRegion = RewriteFinalizedRegion(node); rewrittenFinally = (BoundBlock)this.Visit(node.FinallyBlockOpt); if (rewrittenFinally == null) { return finalizedRegion; } var asTry = finalizedRegion as BoundTryStatement; if (asTry != null) { // since finalized region is a try we can just attach finally to it Debug.Assert(asTry.FinallyBlockOpt == null); return asTry.Update(asTry.TryBlock, asTry.CatchBlocks, rewrittenFinally, asTry.FinallyLabelOpt, asTry.PreferFaultHandler); } else { // wrap finalizedRegion into a Try with a finally. return _F.Try((BoundBlock)finalizedRegion, ImmutableArray<BoundCatchBlock>.Empty, rewrittenFinally); } } // rewrite finalized region (try and catches) in the current frame var frame = PushFrame(node); finalizedRegion = RewriteFinalizedRegion(node); rewrittenFinally = (BoundBlock)this.VisitBlock(node.FinallyBlockOpt); PopFrame(); var exceptionType = _F.SpecialType(SpecialType.System_Object); var pendingExceptionLocal = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(exceptionType), SynthesizedLocalKind.TryAwaitPendingException, tryStatementSyntax); var finallyLabel = _F.GenerateLabel("finallyLabel"); var pendingBranchVar = new SynthesizedLocal(_F.CurrentFunction, TypeWithAnnotations.Create(_F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingBranch, tryStatementSyntax); var catchAll = _F.Catch(_F.Local(pendingExceptionLocal), _F.Block()); var catchAndPendException = _F.Try( _F.Block( finalizedRegion, _F.HiddenSequencePoint(), _F.Goto(finallyLabel), PendBranches(frame, pendingBranchVar, finallyLabel)), ImmutableArray.Create(catchAll), finallyLabel: finallyLabel); BoundBlock syntheticFinallyBlock = _F.Block( _F.HiddenSequencePoint(), _F.Label(finallyLabel), rewrittenFinally, _F.HiddenSequencePoint(), UnpendException(pendingExceptionLocal), UnpendBranches( frame, pendingBranchVar, pendingExceptionLocal)); BoundStatement syntheticFinally = syntheticFinallyBlock; if (_F.CurrentFunction.IsAsync && _F.CurrentFunction.IsIterator) { // We wrap this block so that it can be processed as a finally block by async-iterator rewriting syntheticFinally = _F.ExtractedFinallyBlock(syntheticFinallyBlock); } var locals = ArrayBuilder<LocalSymbol>.GetInstance(); var statements = ArrayBuilder<BoundStatement>.GetInstance(); statements.Add(_F.HiddenSequencePoint()); locals.Add(pendingExceptionLocal); statements.Add(_F.Assignment(_F.Local(pendingExceptionLocal), _F.Default(pendingExceptionLocal.Type))); locals.Add(pendingBranchVar); statements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Default(pendingBranchVar.Type))); LocalSymbol returnLocal = frame.returnValue; if (returnLocal != null) { locals.Add(returnLocal); } statements.Add(catchAndPendException); statements.Add(syntheticFinally); var completeTry = _F.Block( locals.ToImmutableAndFree(), statements.ToImmutableAndFree()); return completeTry; } private BoundBlock PendBranches( AwaitFinallyFrame frame, LocalSymbol pendingBranchVar, LabelSymbol finallyLabel) { var bodyStatements = ArrayBuilder<BoundStatement>.GetInstance(); // handle proxy labels if have any var proxiedLabels = frame.proxiedLabels; var proxyLabels = frame.proxyLabels; // skip 0 - it means we took no explicit branches int i = 1; if (proxiedLabels != null) { for (int cnt = proxiedLabels.Count; i <= cnt; i++) { var proxied = proxiedLabels[i - 1]; var proxy = proxyLabels[proxied]; PendBranch(bodyStatements, proxy, i, pendingBranchVar, finallyLabel); } } var returnProxy = frame.returnProxyLabel; if (returnProxy != null) { PendBranch(bodyStatements, returnProxy, i, pendingBranchVar, finallyLabel); } return _F.Block(bodyStatements.ToImmutableAndFree()); } private void PendBranch( ArrayBuilder<BoundStatement> bodyStatements, LabelSymbol proxy, int i, LocalSymbol pendingBranchVar, LabelSymbol finallyLabel) { // branch lands here bodyStatements.Add(_F.Label(proxy)); // pend the branch bodyStatements.Add(_F.Assignment(_F.Local(pendingBranchVar), _F.Literal(i))); // skip other proxies bodyStatements.Add(_F.Goto(finallyLabel)); } private BoundStatement UnpendBranches( AwaitFinallyFrame frame, SynthesizedLocal pendingBranchVar, SynthesizedLocal pendingException) { var parent = frame.ParentOpt; // handle proxy labels if have any var proxiedLabels = frame.proxiedLabels; // skip 0 - it means we took no explicit branches int i = 1; var cases = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance(); if (proxiedLabels != null) { for (int cnt = proxiedLabels.Count; i <= cnt; i++) { var target = proxiedLabels[i - 1]; var parentProxy = parent.ProxyLabelIfNeeded(target); var caseStatement = _F.SwitchSection(i, _F.Goto(parentProxy)); cases.Add(caseStatement); } } if (frame.returnProxyLabel != null) { BoundLocal pendingValue = null; if (frame.returnValue != null) { pendingValue = _F.Local(frame.returnValue); } SynthesizedLocal returnValue; BoundStatement unpendReturn; var returnLabel = parent.ProxyReturnIfNeeded(_F.CurrentFunction, pendingValue, out returnValue); if (returnLabel == null) { unpendReturn = new BoundReturnStatement(_F.Syntax, RefKind.None, pendingValue); } else { if (pendingValue == null) { unpendReturn = _F.Goto(returnLabel); } else { unpendReturn = _F.Block( _F.Assignment( _F.Local(returnValue), pendingValue), _F.Goto(returnLabel)); } } var caseStatement = _F.SwitchSection(i, unpendReturn); cases.Add(caseStatement); } return _F.Switch(_F.Local(pendingBranchVar), cases.ToImmutableAndFree()); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { BoundExpression caseExpressionOpt = (BoundExpression)this.Visit(node.CaseExpressionOpt); BoundLabel labelExpressionOpt = (BoundLabel)this.Visit(node.LabelExpressionOpt); var proxyLabel = _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label); return node.Update(proxyLabel, caseExpressionOpt, labelExpressionOpt); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { Debug.Assert(node.Label == _currentAwaitFinallyFrame.ProxyLabelIfNeeded(node.Label), "conditional leave?"); return base.VisitConditionalGoto(node); } public override BoundNode VisitReturnStatement(BoundReturnStatement node) { SynthesizedLocal returnValue; var returnLabel = _currentAwaitFinallyFrame.ProxyReturnIfNeeded( _F.CurrentFunction, node.ExpressionOpt, out returnValue); if (returnLabel == null) { return base.VisitReturnStatement(node); } var returnExpr = (BoundExpression)(this.Visit(node.ExpressionOpt)); if (returnExpr != null) { return _F.Block( _F.Assignment( _F.Local(returnValue), returnExpr), _F.Goto( returnLabel)); } else { return _F.Goto(returnLabel); } } private BoundStatement UnpendException(LocalSymbol pendingExceptionLocal) { // create a temp. // pendingExceptionLocal will certainly be captured, no need to access it over and over. LocalSymbol obj = _F.SynthesizedLocal(_F.SpecialType(SpecialType.System_Object)); var objInit = _F.Assignment(_F.Local(obj), _F.Local(pendingExceptionLocal)); // throw pendingExceptionLocal; BoundStatement rethrow = Rethrow(obj); return _F.Block( ImmutableArray.Create<LocalSymbol>(obj), objInit, _F.If( _F.ObjectNotEqual( _F.Local(obj), _F.Null(obj.Type)), rethrow)); } private BoundStatement Rethrow(LocalSymbol obj) { // conservative rethrow BoundStatement rethrow = _F.Throw(_F.Local(obj)); var exceptionDispatchInfoCapture = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, isOptional: true); var exceptionDispatchInfoThrow = _F.WellKnownMethod(WellKnownMember.System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, isOptional: true); // if these helpers are available, we can rethrow with original stack info // as long as it derives from Exception if (exceptionDispatchInfoCapture != null && exceptionDispatchInfoThrow != null) { var ex = _F.SynthesizedLocal(_F.WellKnownType(WellKnownType.System_Exception)); var assignment = _F.Assignment( _F.Local(ex), _F.As(_F.Local(obj), ex.Type)); // better rethrow rethrow = _F.Block( ImmutableArray.Create(ex), assignment, _F.If(_F.ObjectEqual(_F.Local(ex), _F.Null(ex.Type)), rethrow), // ExceptionDispatchInfo.Capture(pendingExceptionLocal).Throw(); _F.ExpressionStatement( _F.Call( _F.StaticCall( exceptionDispatchInfoCapture.ContainingType, exceptionDispatchInfoCapture, _F.Local(ex)), exceptionDispatchInfoThrow))); } return rethrow; } /// <summary> /// Rewrites Try/Catch part of the Try/Catch/Finally /// </summary> private BoundStatement RewriteFinalizedRegion(BoundTryStatement node) { var rewrittenTry = (BoundBlock)this.VisitBlock(node.TryBlock); var catches = node.CatchBlocks; if (catches.IsDefaultOrEmpty) { return rewrittenTry; } var origAwaitCatchFrame = _currentAwaitCatchFrame; _currentAwaitCatchFrame = null; var rewrittenCatches = this.VisitList(node.CatchBlocks); BoundStatement tryWithCatches = _F.Try(rewrittenTry, rewrittenCatches); var currentAwaitCatchFrame = _currentAwaitCatchFrame; if (currentAwaitCatchFrame != null) { var handledLabel = _F.GenerateLabel("handled"); var handlersList = currentAwaitCatchFrame.handlers; var handlers = ArrayBuilder<SyntheticBoundNodeFactory.SyntheticSwitchSection>.GetInstance(handlersList.Count); for (int i = 0, l = handlersList.Count; i < l; i++) { handlers.Add(_F.SwitchSection( i + 1, _F.Block( handlersList[i], _F.Goto(handledLabel)))); } tryWithCatches = _F.Block( ImmutableArray.Create<LocalSymbol>( currentAwaitCatchFrame.pendingCaughtException, currentAwaitCatchFrame.pendingCatch). AddRange(currentAwaitCatchFrame.GetHoistedLocals()), _F.HiddenSequencePoint(), _F.Assignment( _F.Local(currentAwaitCatchFrame.pendingCatch), _F.Default(currentAwaitCatchFrame.pendingCatch.Type)), tryWithCatches, _F.HiddenSequencePoint(), _F.Switch( _F.Local(currentAwaitCatchFrame.pendingCatch), handlers.ToImmutableAndFree()), _F.HiddenSequencePoint(), _F.Label(handledLabel)); } _currentAwaitCatchFrame = origAwaitCatchFrame; return tryWithCatches; } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { if (!_analysis.CatchContainsAwait(node)) { var origCurrentAwaitCatchFrame = _currentAwaitCatchFrame; _currentAwaitCatchFrame = null; var result = base.VisitCatchBlock(node); _currentAwaitCatchFrame = origCurrentAwaitCatchFrame; return result; } var currentAwaitCatchFrame = _currentAwaitCatchFrame; if (currentAwaitCatchFrame == null) { Debug.Assert(node.Syntax.IsKind(SyntaxKind.CatchClause)); var tryStatementSyntax = (TryStatementSyntax)node.Syntax.Parent; currentAwaitCatchFrame = _currentAwaitCatchFrame = new AwaitCatchFrame(_F, tryStatementSyntax); } var catchType = node.ExceptionTypeOpt ?? _F.SpecialType(SpecialType.System_Object); var catchTemp = _F.SynthesizedLocal(catchType); var storePending = _F.AssignmentExpression( _F.Local(currentAwaitCatchFrame.pendingCaughtException), _F.Convert(currentAwaitCatchFrame.pendingCaughtException.Type, _F.Local(catchTemp))); var setPendingCatchNum = _F.Assignment( _F.Local(currentAwaitCatchFrame.pendingCatch), _F.Literal(currentAwaitCatchFrame.handlers.Count + 1)); // catch (ExType exTemp) // { // pendingCaughtException = exTemp; // catchNo = X; // } BoundCatchBlock catchAndPend; ImmutableArray<LocalSymbol> handlerLocals; var filterPrologueOpt = node.ExceptionFilterPrologueOpt; var filterOpt = node.ExceptionFilterOpt; if (filterOpt == null) { Debug.Assert(filterPrologueOpt is null); // store pending exception // as the first statement in a catch catchAndPend = node.Update( ImmutableArray.Create(catchTemp), _F.Local(catchTemp), catchType, exceptionFilterPrologueOpt: filterPrologueOpt, exceptionFilterOpt: null, body: _F.Block( _F.HiddenSequencePoint(), _F.ExpressionStatement(storePending), setPendingCatchNum), isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll); // catch locals live on the synthetic catch handler block handlerLocals = node.Locals; } else { handlerLocals = ImmutableArray<LocalSymbol>.Empty; // catch locals move up into hoisted locals // since we might need to access them from both the filter and the catch foreach (var local in node.Locals) { currentAwaitCatchFrame.HoistLocal(local, _F); } // store pending exception // as the first expression in a filter var sourceOpt = node.ExceptionSourceOpt; var rewrittenPrologue = (BoundStatementList)this.Visit(filterPrologueOpt); var rewrittenFilter = (BoundExpression)this.Visit(filterOpt); var newFilter = sourceOpt == null ? _F.MakeSequence( storePending, rewrittenFilter) : _F.MakeSequence( storePending, AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame), rewrittenFilter); catchAndPend = node.Update( ImmutableArray.Create(catchTemp), _F.Local(catchTemp), catchType, exceptionFilterPrologueOpt: rewrittenPrologue, exceptionFilterOpt: newFilter, body: _F.Block( _F.HiddenSequencePoint(), setPendingCatchNum), isSynthesizedAsyncCatchAll: node.IsSynthesizedAsyncCatchAll); } var handlerStatements = ArrayBuilder<BoundStatement>.GetInstance(); handlerStatements.Add(_F.HiddenSequencePoint()); if (filterOpt == null) { var sourceOpt = node.ExceptionSourceOpt; if (sourceOpt != null) { BoundExpression assignSource = AssignCatchSource((BoundExpression)this.Visit(sourceOpt), currentAwaitCatchFrame); handlerStatements.Add(_F.ExpressionStatement(assignSource)); } } handlerStatements.Add((BoundStatement)this.Visit(node.Body)); var handler = _F.Block( handlerLocals, handlerStatements.ToImmutableAndFree() ); currentAwaitCatchFrame.handlers.Add(handler); return catchAndPend; } private BoundExpression AssignCatchSource(BoundExpression rewrittenSource, AwaitCatchFrame currentAwaitCatchFrame) { BoundExpression assignSource = null; if (rewrittenSource != null) { // exceptionSource = (exceptionSourceType)pendingCaughtException; assignSource = _F.AssignmentExpression( rewrittenSource, _F.Convert( rewrittenSource.Type, _F.Local(currentAwaitCatchFrame.pendingCaughtException))); } return assignSource; } public override BoundNode VisitLocal(BoundLocal node) { var catchFrame = _currentAwaitCatchFrame; LocalSymbol hoistedLocal; if (catchFrame == null || !catchFrame.TryGetHoistedLocal(node.LocalSymbol, out hoistedLocal)) { return base.VisitLocal(node); } return node.Update(hoistedLocal, node.ConstantValueOpt, hoistedLocal.Type); } public override BoundNode VisitThrowStatement(BoundThrowStatement node) { if (node.ExpressionOpt != null || _currentAwaitCatchFrame == null) { return base.VisitThrowStatement(node); } return Rethrow(_currentAwaitCatchFrame.pendingCaughtException); } public override BoundNode VisitLambda(BoundLambda node) { var oldContainingSymbol = _F.CurrentFunction; var oldAwaitFinallyFrame = _currentAwaitFinallyFrame; _F.CurrentFunction = node.Symbol; _currentAwaitFinallyFrame = new AwaitFinallyFrame(); var result = base.VisitLambda(node); _F.CurrentFunction = oldContainingSymbol; _currentAwaitFinallyFrame = oldAwaitFinallyFrame; return result; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var oldContainingSymbol = _F.CurrentFunction; var oldAwaitFinallyFrame = _currentAwaitFinallyFrame; _F.CurrentFunction = node.Symbol; _currentAwaitFinallyFrame = new AwaitFinallyFrame(); var result = base.VisitLocalFunctionStatement(node); _F.CurrentFunction = oldContainingSymbol; _currentAwaitFinallyFrame = oldAwaitFinallyFrame; return result; } private AwaitFinallyFrame PushFrame(BoundTryStatement statement) { var newFrame = new AwaitFinallyFrame(_currentAwaitFinallyFrame, _analysis.Labels(statement), (StatementSyntax)statement.Syntax); _currentAwaitFinallyFrame = newFrame; return newFrame; } private void PopFrame() { var result = _currentAwaitFinallyFrame; _currentAwaitFinallyFrame = result.ParentOpt; } /// <summary> /// Analyzes method body for try blocks with awaits in finally blocks /// Also collects labels that such blocks contain. /// </summary> private sealed class AwaitInFinallyAnalysis : LabelCollector { // all try blocks with yields in them and complete set of labels inside those try blocks // NOTE: non-yielding try blocks are transparently ignored - i.e. their labels are included // in the label set of the nearest yielding-try parent private Dictionary<BoundTryStatement, HashSet<LabelSymbol>> _labelsInInterestingTry; private HashSet<BoundCatchBlock> _awaitContainingCatches; // transient accumulators. private bool _seenAwait; public AwaitInFinallyAnalysis(BoundStatement body) { _seenAwait = false; this.Visit(body); } /// <summary> /// Returns true if a finally of the given try contains awaits /// </summary> public bool FinallyContainsAwaits(BoundTryStatement statement) { return _labelsInInterestingTry != null && _labelsInInterestingTry.ContainsKey(statement); } /// <summary> /// Returns true if a catch contains awaits /// </summary> internal bool CatchContainsAwait(BoundCatchBlock node) { return _awaitContainingCatches != null && _awaitContainingCatches.Contains(node); } /// <summary> /// Returns true if body contains await in a finally block. /// </summary> public bool ContainsAwaitInHandlers() { return _labelsInInterestingTry != null || _awaitContainingCatches != null; } /// <summary> /// Labels reachable from within this frame without invoking its finally. /// null if there are no such labels. /// </summary> internal HashSet<LabelSymbol> Labels(BoundTryStatement statement) { return _labelsInInterestingTry[statement]; } public override BoundNode VisitTryStatement(BoundTryStatement node) { var origLabels = this.currentLabels; this.currentLabels = null; Visit(node.TryBlock); VisitList(node.CatchBlocks); var origSeenAwait = _seenAwait; _seenAwait = false; Visit(node.FinallyBlockOpt); if (_seenAwait) { // this try has awaits in the finally ! var labelsInInterestingTry = _labelsInInterestingTry; if (labelsInInterestingTry == null) { _labelsInInterestingTry = labelsInInterestingTry = new Dictionary<BoundTryStatement, HashSet<LabelSymbol>>(); } labelsInInterestingTry.Add(node, currentLabels); currentLabels = origLabels; } else { // this is a boring try without awaits in finally // currentLabels = currentLabels U origLabels ; if (currentLabels == null) { currentLabels = origLabels; } else if (origLabels != null) { currentLabels.UnionWith(origLabels); } } _seenAwait = _seenAwait | origSeenAwait; return null; } public override BoundNode VisitCatchBlock(BoundCatchBlock node) { var origSeenAwait = _seenAwait; _seenAwait = false; var result = base.VisitCatchBlock(node); if (_seenAwait) { var awaitContainingCatches = _awaitContainingCatches; if (awaitContainingCatches == null) { _awaitContainingCatches = awaitContainingCatches = new HashSet<BoundCatchBlock>(); } _awaitContainingCatches.Add(node); } _seenAwait |= origSeenAwait; return result; } public override BoundNode VisitAwaitExpression(BoundAwaitExpression node) { _seenAwait = true; return base.VisitAwaitExpression(node); } public override BoundNode VisitLambda(BoundLambda node) { var origLabels = this.currentLabels; var origSeenAwait = _seenAwait; this.currentLabels = null; _seenAwait = false; base.VisitLambda(node); this.currentLabels = origLabels; _seenAwait = origSeenAwait; return null; } public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { var origLabels = this.currentLabels; var origSeenAwait = _seenAwait; this.currentLabels = null; _seenAwait = false; base.VisitLocalFunctionStatement(node); this.currentLabels = origLabels; _seenAwait = origSeenAwait; return null; } } // storage of various information about a given finally frame private sealed class AwaitFinallyFrame { // Enclosing frame. Root frame does not have parent. public readonly AwaitFinallyFrame ParentOpt; // labels within this frame (branching to these labels does not go through finally). public readonly HashSet<LabelSymbol> LabelsOpt; // the try or using-await statement the frame is associated with private readonly StatementSyntax _statementSyntaxOpt; // proxy labels for branches leaving the frame. // we build this on demand once we encounter leaving branches. // subsequent leaves to an already proxied label redirected to the proxy. // At the proxy label we will execute finally and forward the control flow // to the actual destination. (which could be proxied again in the parent) public Dictionary<LabelSymbol, LabelSymbol> proxyLabels; public List<LabelSymbol> proxiedLabels; public GeneratedLabelSymbol returnProxyLabel; public SynthesizedLocal returnValue; public AwaitFinallyFrame() { // root frame } public AwaitFinallyFrame(AwaitFinallyFrame parent, HashSet<LabelSymbol> labelsOpt, StatementSyntax statementSyntax) { Debug.Assert(parent != null); Debug.Assert(statementSyntax != null); Debug.Assert(statementSyntax.Kind() == SyntaxKind.TryStatement || (statementSyntax.Kind() == SyntaxKind.UsingStatement && ((UsingStatementSyntax)statementSyntax).AwaitKeyword != default) || (statementSyntax.Kind() == SyntaxKind.ForEachStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) || (statementSyntax.Kind() == SyntaxKind.ForEachVariableStatement && ((CommonForEachStatementSyntax)statementSyntax).AwaitKeyword != default) || (statementSyntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)statementSyntax).AwaitKeyword != default)); this.ParentOpt = parent; this.LabelsOpt = labelsOpt; _statementSyntaxOpt = statementSyntax; } public bool IsRoot() { return this.ParentOpt == null; } // returns a proxy for a label if branch must be hijacked to run finally // otherwise returns same label back public LabelSymbol ProxyLabelIfNeeded(LabelSymbol label) { // no need to proxy a label in the current frame or when we are at the root if (this.IsRoot() || (LabelsOpt != null && LabelsOpt.Contains(label))) { return label; } var proxyLabels = this.proxyLabels; var proxiedLabels = this.proxiedLabels; if (proxyLabels == null) { this.proxyLabels = proxyLabels = new Dictionary<LabelSymbol, LabelSymbol>(); this.proxiedLabels = proxiedLabels = new List<LabelSymbol>(); } LabelSymbol proxy; if (!proxyLabels.TryGetValue(label, out proxy)) { proxy = new GeneratedLabelSymbol("proxy" + label.Name); proxyLabels.Add(label, proxy); proxiedLabels.Add(label); } return proxy; } public LabelSymbol ProxyReturnIfNeeded( MethodSymbol containingMethod, BoundExpression valueOpt, out SynthesizedLocal returnValue) { returnValue = null; // no need to proxy returns at the root if (this.IsRoot()) { return null; } var returnProxy = this.returnProxyLabel; if (returnProxy == null) { this.returnProxyLabel = returnProxy = new GeneratedLabelSymbol("returnProxy"); } if (valueOpt != null) { returnValue = this.returnValue; if (returnValue == null) { Debug.Assert(_statementSyntaxOpt != null); this.returnValue = returnValue = new SynthesizedLocal(containingMethod, TypeWithAnnotations.Create(valueOpt.Type), SynthesizedLocalKind.AsyncMethodReturnValue, _statementSyntaxOpt); } } return returnProxy; } } private sealed class AwaitCatchFrame { // object, stores the original caught exception // used to initialize the exception source inside the handler // also used in rethrow statements public readonly SynthesizedLocal pendingCaughtException; // int, stores the number of pending catch // 0 - means no catches are pending. public readonly SynthesizedLocal pendingCatch; // synthetic handlers produced by catch rewrite. // they will become switch sections when pending exception is dispatched. public readonly List<BoundBlock> handlers; // when catch local must be used from a filter // we need to "hoist" it up to ensure that both the filter // and the catch access the same variable. // NOTE: it must be the same variable, not just same value. // The difference would be observable if filter mutates the variable // or/and if a variable gets lifted into a closure. private readonly Dictionary<LocalSymbol, LocalSymbol> _hoistedLocals; private readonly List<LocalSymbol> _orderedHoistedLocals; public AwaitCatchFrame(SyntheticBoundNodeFactory F, TryStatementSyntax tryStatementSyntax) { this.pendingCaughtException = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Object)), SynthesizedLocalKind.TryAwaitPendingCaughtException, tryStatementSyntax); this.pendingCatch = new SynthesizedLocal(F.CurrentFunction, TypeWithAnnotations.Create(F.SpecialType(SpecialType.System_Int32)), SynthesizedLocalKind.TryAwaitPendingCatch, tryStatementSyntax); this.handlers = new List<BoundBlock>(); _hoistedLocals = new Dictionary<LocalSymbol, LocalSymbol>(); _orderedHoistedLocals = new List<LocalSymbol>(); } public void HoistLocal(LocalSymbol local, SyntheticBoundNodeFactory F) { if (!_hoistedLocals.Keys.Any(l => l.Name == local.Name && TypeSymbol.Equals(l.Type, local.Type, TypeCompareKind.ConsiderEverything2))) { _hoistedLocals.Add(local, local); _orderedHoistedLocals.Add(local); return; } // code uses "await" in two sibling catches with exception filters // locals with same names and types may cause problems if they are lifted // and become fields with identical signatures. // To avoid such problems we will mangle the name of the second local. // This will only affect debugging of this extremely rare case. Debug.Assert(pendingCatch.SyntaxOpt.IsKind(SyntaxKind.TryStatement)); var newLocal = F.SynthesizedLocal(local.Type, pendingCatch.SyntaxOpt, kind: SynthesizedLocalKind.ExceptionFilterAwaitHoistedExceptionLocal); _hoistedLocals.Add(local, newLocal); _orderedHoistedLocals.Add(newLocal); } public IEnumerable<LocalSymbol> GetHoistedLocals() { return _orderedHoistedLocals; } public bool TryGetHoistedLocal(LocalSymbol originalLocal, out LocalSymbol hoistedLocal) { return _hoistedLocals.TryGetValue(originalLocal, out hoistedLocal); } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Remote/Core/SolutionAssetStorageProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Remote { internal sealed class SolutionAssetStorageProvider : ISolutionAssetStorageProvider { [ExportWorkspaceServiceFactory(typeof(ISolutionAssetStorageProvider)), Shared] internal sealed class Factory : IWorkspaceServiceFactory { private readonly SolutionAssetStorage _storage = new SolutionAssetStorage(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SolutionAssetStorageProvider(_storage); } public SolutionAssetStorage AssetStorage { get; private set; } private SolutionAssetStorageProvider(SolutionAssetStorage storage) { AssetStorage = storage; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Remote { internal sealed class SolutionAssetStorageProvider : ISolutionAssetStorageProvider { [ExportWorkspaceServiceFactory(typeof(ISolutionAssetStorageProvider)), Shared] internal sealed class Factory : IWorkspaceServiceFactory { private readonly SolutionAssetStorage _storage = new SolutionAssetStorage(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new SolutionAssetStorageProvider(_storage); } public SolutionAssetStorage AssetStorage { get; private set; } private SolutionAssetStorageProvider(SolutionAssetStorage storage) { AssetStorage = storage; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/Core/Shared/Utilities/ThreadingContextTaskSchedulerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { [ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared] internal sealed class ThreadingContextTaskSchedulerProvider : ITaskSchedulerProvider { public TaskScheduler CurrentContextScheduler { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ThreadingContextTaskSchedulerProvider(IThreadingContext threadingContext) { CurrentContextScheduler = threadingContext.HasMainThread ? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory) : TaskScheduler.Default; } private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler { private readonly JoinableTaskFactory _joinableTaskFactory; public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory) => _joinableTaskFactory = joinableTaskFactory; public override int MaximumConcurrencyLevel => 1; protected override IEnumerable<Task> GetScheduledTasks() => SpecializedCollections.EmptyEnumerable<Task>(); protected override void QueueTask(Task task) { _joinableTaskFactory.RunAsync(async () => { await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); TryExecuteTask(task); }); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (_joinableTaskFactory.Context.IsOnMainThread) { return TryExecuteTask(task); } 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.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { [ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared] internal sealed class ThreadingContextTaskSchedulerProvider : ITaskSchedulerProvider { public TaskScheduler CurrentContextScheduler { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ThreadingContextTaskSchedulerProvider(IThreadingContext threadingContext) { CurrentContextScheduler = threadingContext.HasMainThread ? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory) : TaskScheduler.Default; } private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler { private readonly JoinableTaskFactory _joinableTaskFactory; public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory) => _joinableTaskFactory = joinableTaskFactory; public override int MaximumConcurrencyLevel => 1; protected override IEnumerable<Task> GetScheduledTasks() => SpecializedCollections.EmptyEnumerable<Task>(); protected override void QueueTask(Task task) { _joinableTaskFactory.RunAsync(async () => { await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); TryExecuteTask(task); }); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (_joinableTaskFactory.Context.IsOnMainThread) { return TryExecuteTask(task); } return false; } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/LiveShare/Impl/LiveShareConstants.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.LiveShare { internal class LiveShareConstants { // The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client public const string RoslynContractName = "Roslyn"; // The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client public const string RoslynLSPSDKContractName = "RoslynLSPSDK"; public const string TypeScriptLanguageName = "TypeScript"; public const string CSharpContractName = "CSharp"; public const string VisualBasicContractName = "VisualBasic"; public const string TypeScriptContractName = "TypeScript"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.VisualStudio.LanguageServices.LiveShare { internal class LiveShareConstants { // The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client public const string RoslynContractName = "Roslyn"; // The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client public const string RoslynLSPSDKContractName = "RoslynLSPSDK"; public const string TypeScriptLanguageName = "TypeScript"; public const string CSharpContractName = "CSharp"; public const string VisualBasicContractName = "VisualBasic"; public const string TypeScriptContractName = "TypeScript"; } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Portable/Syntax/SimpleLambdaExpressionSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SimpleLambdaExpressionSyntax { public new SimpleLambdaExpressionSyntax WithBody(CSharpSyntaxNode body) => body is BlockSyntax block ? WithBlock(block).WithExpressionBody(null) : WithExpressionBody((ExpressionSyntax)body).WithBlock(null); public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body) => body is BlockSyntax block ? Update(asyncKeyword, parameter, arrowToken, block, null) : Update(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body); public override SyntaxToken AsyncKeyword => this.Modifiers.FirstOrDefault(SyntaxKind.AsyncKeyword); internal override AnonymousFunctionExpressionSyntax WithAsyncKeywordCore(SyntaxToken asyncKeyword) => WithAsyncKeyword(asyncKeyword); public new SimpleLambdaExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) => this.Update(asyncKeyword, this.Parameter, this.ArrowToken, this.Block, this.ExpressionBody); public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => Update(SyntaxFactory.TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); public SimpleLambdaExpressionSyntax Update(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => Update(this.AttributeLists, modifiers, parameter, arrowToken, block, expressionBody); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, default(SyntaxTokenList), parameter, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, modifiers, parameter, arrowToken, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, ParameterSyntax parameter, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, modifiers, parameter, block, expressionBody); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SimpleLambdaExpressionSyntax { public new SimpleLambdaExpressionSyntax WithBody(CSharpSyntaxNode body) => body is BlockSyntax block ? WithBlock(block).WithExpressionBody(null) : WithExpressionBody((ExpressionSyntax)body).WithBlock(null); public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body) => body is BlockSyntax block ? Update(asyncKeyword, parameter, arrowToken, block, null) : Update(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body); public override SyntaxToken AsyncKeyword => this.Modifiers.FirstOrDefault(SyntaxKind.AsyncKeyword); internal override AnonymousFunctionExpressionSyntax WithAsyncKeywordCore(SyntaxToken asyncKeyword) => WithAsyncKeyword(asyncKeyword); public new SimpleLambdaExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) => this.Update(asyncKeyword, this.Parameter, this.ArrowToken, this.Block, this.ExpressionBody); public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => Update(SyntaxFactory.TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); public SimpleLambdaExpressionSyntax Update(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => Update(this.AttributeLists, modifiers, parameter, arrowToken, block, expressionBody); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, default(SyntaxTokenList), parameter, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, modifiers, parameter, arrowToken, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, ParameterSyntax parameter, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, modifiers, parameter, block, expressionBody); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/Storage/CloudCache/ICloudCacheStorageServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Storage.CloudCache { internal interface ICloudCacheStorageServiceFactory : IWorkspaceService { AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Storage.CloudCache { internal interface ICloudCacheStorageServiceFactory : IWorkspaceService { AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/VirtualChars/AbstractVirtualCharService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { internal abstract class AbstractVirtualCharService : IVirtualCharService { public abstract bool TryGetEscapeCharacter(VirtualChar ch, out char escapedChar); protected abstract bool IsStringOrCharLiteralToken(SyntaxToken token); protected abstract VirtualCharSequence TryConvertToVirtualCharsWorker(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if the next two characters at <c>tokenText[index]</c> are <c>{{</c> or /// <c>}}</c>. If so, <paramref name="span"/> will contain the span of those two characters (based on <paramref /// name="tokenText"/> starting at <paramref name="offset"/>). /// </summary> protected static bool IsLegalBraceEscape( string tokenText, int index, int offset, out TextSpan span) { if (index + 1 < tokenText.Length) { var ch = tokenText[index]; var next = tokenText[index + 1]; if ((ch == '{' && next == '{') || (ch == '}' && next == '}')) { span = new TextSpan(offset + index, 2); return true; } } span = default; return false; } public VirtualCharSequence TryConvertToVirtualChars(SyntaxToken token) { // We don't process any strings that contain diagnostics in it. That means that we can // trust that all the string's contents (most importantly, the escape sequences) are well // formed. if (token.ContainsDiagnostics) { return default; } var result = TryConvertToVirtualCharsWorker(token); CheckInvariants(token, result); return result; } [Conditional("DEBUG")] private void CheckInvariants(SyntaxToken token, VirtualCharSequence result) { // Do some invariant checking to make sure we processed the string token the same // way the C# and VB compilers did. if (!result.IsDefault) { // Ensure that we properly broke up the token into a sequence of characters that // matches what the compiler did. if (IsStringOrCharLiteralToken(token)) { var expectedValueText = token.ValueText; var actualValueText = result.CreateString(); Debug.Assert(expectedValueText == actualValueText); } if (result.Length > 0) { var currentVC = result[0]; Debug.Assert(currentVC.Span.Start >= token.SpanStart, "First span has to start after the start of the string token"); if (IsStringOrCharLiteralToken(token)) { Debug.Assert(currentVC.Span.Start == token.SpanStart + 1 || currentVC.Span.Start == token.SpanStart + 2, "First span should start on the second or third char of the string."); } else { Debug.Assert(currentVC.Span.Start == token.SpanStart, "First span should start on the first char of the string."); } for (var i = 1; i < result.Length; i++) { var nextVC = result[i]; Debug.Assert(currentVC.Span.End == nextVC.Span.Start, "Virtual character spans have to be touching."); currentVC = nextVC; } var lastVC = result.Last(); if (IsStringOrCharLiteralToken(token)) { Debug.Assert(lastVC.Span.End == token.Span.End - 1, "Last span has to end right before the end of the string token."); } else { Debug.Assert(lastVC.Span.End == token.Span.End, "Last span has to end right before the end of the string token."); } } } } /// <summary> /// Helper to convert simple string literals that escape quotes by doubling them. This is /// how normal VB literals and c# verbatim string literals work. /// </summary> /// <param name="startDelimiter">The start characters string. " in VB and @" in C#</param> protected static VirtualCharSequence TryConvertSimpleDoubleQuoteString( SyntaxToken token, string startDelimiter, string endDelimiter, bool escapeBraces) { Debug.Assert(!token.ContainsDiagnostics); if (escapeBraces) { Debug.Assert(startDelimiter == ""); Debug.Assert(endDelimiter == ""); } var tokenText = token.Text; if (startDelimiter.Length > 0 && !tokenText.StartsWith(startDelimiter)) { Debug.Assert(false, "This should not be reachable as long as the compiler added no diagnostics."); return default; } if (endDelimiter.Length > 0 && !tokenText.EndsWith(endDelimiter)) { Debug.Assert(false, "This should not be reachable as long as the compiler added no diagnostics."); return default; } var startIndexInclusive = startDelimiter.Length; var endIndexExclusive = tokenText.Length - endDelimiter.Length; using var _ = ArrayBuilder<VirtualChar>.GetInstance(out var result); var offset = token.SpanStart; for (var index = startIndexInclusive; index < endIndexExclusive;) { if (tokenText[index] == '"' && tokenText[index + 1] == '"') { result.Add(VirtualChar.Create(new Rune('"'), new TextSpan(offset + index, 2))); index += 2; } else if (escapeBraces && IsOpenOrCloseBrace(tokenText[index])) { if (!IsLegalBraceEscape(tokenText, index, offset, out var span)) return default; result.Add(VirtualChar.Create(new Rune(tokenText[index]), span)); index += result.Last().Span.Length; } else if (Rune.TryCreate(tokenText[index], out var rune)) { // First, see if this was a single char that can become a rune (the common case). result.Add(VirtualChar.Create(rune, new TextSpan(offset + index, 1))); index += 1; } else if (index + 1 < tokenText.Length && Rune.TryCreate(tokenText[index], tokenText[index + 1], out rune)) { // Otherwise, see if we have a surrogate pair (less common, but possible). result.Add(VirtualChar.Create(rune, new TextSpan(offset + index, 2))); index += 2; } else { // Something that couldn't be encoded as runes. Debug.Assert(char.IsSurrogate(tokenText[index])); result.Add(VirtualChar.Create(tokenText[index], new TextSpan(offset + index, 1))); index += 1; } } return CreateVirtualCharSequence( tokenText, offset, startIndexInclusive, endIndexExclusive, result); } protected static bool IsOpenOrCloseBrace(char ch) => ch == '{' || ch == '}'; protected static VirtualCharSequence CreateVirtualCharSequence( string tokenText, int offset, int startIndexInclusive, int endIndexExclusive, ArrayBuilder<VirtualChar> result) { // Check if we actually needed to create any special virtual chars. // if not, we can avoid the entire array allocation and just wrap // the text of the token and pass that back. var textLength = endIndexExclusive - startIndexInclusive; if (textLength == result.Count) { var sequence = VirtualCharSequence.Create(offset, tokenText); return sequence.GetSubSequence(TextSpan.FromBounds(startIndexInclusive, endIndexExclusive)); } return VirtualCharSequence.Create(result.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.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars { internal abstract class AbstractVirtualCharService : IVirtualCharService { public abstract bool TryGetEscapeCharacter(VirtualChar ch, out char escapedChar); protected abstract bool IsStringOrCharLiteralToken(SyntaxToken token); protected abstract VirtualCharSequence TryConvertToVirtualCharsWorker(SyntaxToken token); /// <summary> /// Returns <see langword="true"/> if the next two characters at <c>tokenText[index]</c> are <c>{{</c> or /// <c>}}</c>. If so, <paramref name="span"/> will contain the span of those two characters (based on <paramref /// name="tokenText"/> starting at <paramref name="offset"/>). /// </summary> protected static bool IsLegalBraceEscape( string tokenText, int index, int offset, out TextSpan span) { if (index + 1 < tokenText.Length) { var ch = tokenText[index]; var next = tokenText[index + 1]; if ((ch == '{' && next == '{') || (ch == '}' && next == '}')) { span = new TextSpan(offset + index, 2); return true; } } span = default; return false; } public VirtualCharSequence TryConvertToVirtualChars(SyntaxToken token) { // We don't process any strings that contain diagnostics in it. That means that we can // trust that all the string's contents (most importantly, the escape sequences) are well // formed. if (token.ContainsDiagnostics) { return default; } var result = TryConvertToVirtualCharsWorker(token); CheckInvariants(token, result); return result; } [Conditional("DEBUG")] private void CheckInvariants(SyntaxToken token, VirtualCharSequence result) { // Do some invariant checking to make sure we processed the string token the same // way the C# and VB compilers did. if (!result.IsDefault) { // Ensure that we properly broke up the token into a sequence of characters that // matches what the compiler did. if (IsStringOrCharLiteralToken(token)) { var expectedValueText = token.ValueText; var actualValueText = result.CreateString(); Debug.Assert(expectedValueText == actualValueText); } if (result.Length > 0) { var currentVC = result[0]; Debug.Assert(currentVC.Span.Start >= token.SpanStart, "First span has to start after the start of the string token"); if (IsStringOrCharLiteralToken(token)) { Debug.Assert(currentVC.Span.Start == token.SpanStart + 1 || currentVC.Span.Start == token.SpanStart + 2, "First span should start on the second or third char of the string."); } else { Debug.Assert(currentVC.Span.Start == token.SpanStart, "First span should start on the first char of the string."); } for (var i = 1; i < result.Length; i++) { var nextVC = result[i]; Debug.Assert(currentVC.Span.End == nextVC.Span.Start, "Virtual character spans have to be touching."); currentVC = nextVC; } var lastVC = result.Last(); if (IsStringOrCharLiteralToken(token)) { Debug.Assert(lastVC.Span.End == token.Span.End - 1, "Last span has to end right before the end of the string token."); } else { Debug.Assert(lastVC.Span.End == token.Span.End, "Last span has to end right before the end of the string token."); } } } } /// <summary> /// Helper to convert simple string literals that escape quotes by doubling them. This is /// how normal VB literals and c# verbatim string literals work. /// </summary> /// <param name="startDelimiter">The start characters string. " in VB and @" in C#</param> protected static VirtualCharSequence TryConvertSimpleDoubleQuoteString( SyntaxToken token, string startDelimiter, string endDelimiter, bool escapeBraces) { Debug.Assert(!token.ContainsDiagnostics); if (escapeBraces) { Debug.Assert(startDelimiter == ""); Debug.Assert(endDelimiter == ""); } var tokenText = token.Text; if (startDelimiter.Length > 0 && !tokenText.StartsWith(startDelimiter)) { Debug.Assert(false, "This should not be reachable as long as the compiler added no diagnostics."); return default; } if (endDelimiter.Length > 0 && !tokenText.EndsWith(endDelimiter)) { Debug.Assert(false, "This should not be reachable as long as the compiler added no diagnostics."); return default; } var startIndexInclusive = startDelimiter.Length; var endIndexExclusive = tokenText.Length - endDelimiter.Length; using var _ = ArrayBuilder<VirtualChar>.GetInstance(out var result); var offset = token.SpanStart; for (var index = startIndexInclusive; index < endIndexExclusive;) { if (tokenText[index] == '"' && tokenText[index + 1] == '"') { result.Add(VirtualChar.Create(new Rune('"'), new TextSpan(offset + index, 2))); index += 2; } else if (escapeBraces && IsOpenOrCloseBrace(tokenText[index])) { if (!IsLegalBraceEscape(tokenText, index, offset, out var span)) return default; result.Add(VirtualChar.Create(new Rune(tokenText[index]), span)); index += result.Last().Span.Length; } else if (Rune.TryCreate(tokenText[index], out var rune)) { // First, see if this was a single char that can become a rune (the common case). result.Add(VirtualChar.Create(rune, new TextSpan(offset + index, 1))); index += 1; } else if (index + 1 < tokenText.Length && Rune.TryCreate(tokenText[index], tokenText[index + 1], out rune)) { // Otherwise, see if we have a surrogate pair (less common, but possible). result.Add(VirtualChar.Create(rune, new TextSpan(offset + index, 2))); index += 2; } else { // Something that couldn't be encoded as runes. Debug.Assert(char.IsSurrogate(tokenText[index])); result.Add(VirtualChar.Create(tokenText[index], new TextSpan(offset + index, 1))); index += 1; } } return CreateVirtualCharSequence( tokenText, offset, startIndexInclusive, endIndexExclusive, result); } protected static bool IsOpenOrCloseBrace(char ch) => ch == '{' || ch == '}'; protected static VirtualCharSequence CreateVirtualCharSequence( string tokenText, int offset, int startIndexInclusive, int endIndexExclusive, ArrayBuilder<VirtualChar> result) { // Check if we actually needed to create any special virtual chars. // if not, we can avoid the entire array allocation and just wrap // the text of the token and pass that back. var textLength = endIndexExclusive - startIndexInclusive; if (textLength == result.Count) { var sequence = VirtualCharSequence.Create(offset, tokenText); return sequence.GetSubSequence(TextSpan.FromBounds(startIndexInclusive, endIndexExclusive)); } return VirtualCharSequence.Create(result.ToImmutable()); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Test/Emit/PDB/PDBConstantTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Globalization; using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBConstantTests : CSharpTestBase { [Fact] public void StringsWithSurrogateChar() { var source = @" using System; public class T { public static void Main() { const string HighSurrogateCharacter = ""\uD800""; const string LowSurrogateCharacter = ""\uDC00""; const string MatchedSurrogateCharacters = ""\uD800\uDC00""; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Note: U+FFFD is the Unicode 'replacement character' point and is used to replace an incoming character // whose value is unknown or unrepresentable in Unicode. This is what our pdb writer does with // unpaired surrogates. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <constant name=""HighSurrogateCharacter"" value=""\uFFFD"" type=""String"" /> <constant name=""LowSurrogateCharacter"" value=""\uFFFD"" type=""String"" /> <constant name=""MatchedSurrogateCharacters"" value=""\uD800\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""HighSurrogateCharacter"" value=""\uD800"" type=""String"" /> <constant name=""LowSurrogateCharacter"" value=""\uDC00"" type=""String"" /> <constant name=""MatchedSurrogateCharacters"" value=""\uD800\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(546862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546862")] [Fact] public void InvalidUnicodeString() { var source = @" using System; public class T { public static void Main() { const string invalidUnicodeString = ""\uD800\0\uDC00""; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Note: U+FFFD is the Unicode 'replacement character' point and is used to replace an incoming character // whose value is unknown or unrepresentable in Unicode. This is what our pdb writer does with // unpaired surrogates. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <constant name=""invalidUnicodeString"" value=""\uFFFD\u0000\uFFFD"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""invalidUnicodeString"" value=""\uD800\u0000\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] public void AllTypes() { var source = @" using System; using System.Collections.Generic; class X {} public class C<S> { enum EnumI1 : sbyte { A } enum EnumU1 : byte { A } enum EnumI2 : short { A } enum EnumU2 : ushort { A } enum EnumI4 : int { A } enum EnumU4 : uint { A } enum EnumI8 : long { A } enum EnumU8 : ulong { A } public static void F<T>() { const bool B = false; const char C = '\0'; const sbyte I1 = 0; const byte U1 = 0; const short I2 = 0; const ushort U2 = 0; const int I4 = 0; const uint U4 = 0; const long I8 = 0; const ulong U8 = 0; const float R4 = 0; const double R8 = 0; const C<int>.EnumI1 EI1 = 0; const C<int>.EnumU1 EU1 = 0; const C<int>.EnumI2 EI2 = 0; const C<int>.EnumU2 EU2 = 0; const C<int>.EnumI4 EI4 = 0; const C<int>.EnumU4 EU4 = 0; const C<int>.EnumI8 EI8 = 0; const C<int>.EnumU8 EU8 = 0; const string StrWithNul = ""\0""; const string EmptyStr = """"; const string NullStr = null; const object NullObject = null; const dynamic NullDynamic = null; const X NullTypeDef = null; const Action NullTypeRef = null; const Func<Dictionary<int, C<int>>, dynamic, T, List<S>> NullTypeSpec = null; const object[] Array1 = null; const object[,] Array2 = null; const object[][] Array3 = null; const decimal D = 0M; // DateTime const not expressible in C# } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C`1.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C`1"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""NullDynamic"" /> <bucket flags=""000001000"" slotId=""0"" localName=""NullTypeSpec"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <constant name=""B"" value=""0"" type=""Boolean"" /> <constant name=""C"" value=""0"" type=""Char"" /> <constant name=""I1"" value=""0"" type=""SByte"" /> <constant name=""U1"" value=""0"" type=""Byte"" /> <constant name=""I2"" value=""0"" type=""Int16"" /> <constant name=""U2"" value=""0"" type=""UInt16"" /> <constant name=""I4"" value=""0"" type=""Int32"" /> <constant name=""U4"" value=""0"" type=""UInt32"" /> <constant name=""I8"" value=""0"" type=""Int64"" /> <constant name=""U8"" value=""0"" type=""UInt64"" /> <constant name=""R4"" value=""0x00000000"" type=""Single"" /> <constant name=""R8"" value=""0x0000000000000000"" type=""Double"" /> <constant name=""EI1"" value=""0"" signature=""EnumI1{Int32}"" /> <constant name=""EU1"" value=""0"" signature=""EnumU1{Int32}"" /> <constant name=""EI2"" value=""0"" signature=""EnumI2{Int32}"" /> <constant name=""EU2"" value=""0"" signature=""EnumU2{Int32}"" /> <constant name=""EI4"" value=""0"" signature=""EnumI4{Int32}"" /> <constant name=""EU4"" value=""0"" signature=""EnumU4{Int32}"" /> <constant name=""EI8"" value=""0"" signature=""EnumI8{Int32}"" /> <constant name=""EU8"" value=""0"" signature=""EnumU8{Int32}"" /> <constant name=""StrWithNul"" value=""\u0000"" type=""String"" /> <constant name=""EmptyStr"" value="""" type=""String"" /> <constant name=""NullStr"" value=""null"" type=""String"" /> <constant name=""NullObject"" value=""null"" type=""Object"" /> <constant name=""NullDynamic"" value=""null"" type=""Object"" /> <constant name=""NullTypeDef"" value=""null"" signature=""X"" /> <constant name=""NullTypeRef"" value=""null"" signature=""System.Action"" /> <constant name=""NullTypeSpec"" value=""null"" signature=""System.Func`4{System.Collections.Generic.Dictionary`2{Int32, C`1{Int32}}, Object, !!0, System.Collections.Generic.List`1{!0}}"" /> <constant name=""Array1"" value=""null"" signature=""Object[]"" /> <constant name=""Array2"" value=""null"" signature=""Object[,,]"" /> <constant name=""Array3"" value=""null"" signature=""Object[][]"" /> <constant name=""D"" value=""0"" type=""Decimal"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SimpleLocalConstant() { var text = @" class C { void M() { const int x = 1; { const int y = 2; } } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <constant name=""x"" value=""1"" type=""Int32"" /> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""y"" value=""2"" type=""Int32"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void LambdaLocalConstants() { var text = WithWindowsLineBreaks(@" using System; class C { void M(Action a) { const int x = 1; M(() => { const int y = 2; { const int z = 3; } }); } } "); var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""a""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""54"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""15"" endColumn=""12"" document=""1"" /> <entry offset=""0x27"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <namespace name=""System"" /> <constant name=""x"" value=""1"" type=""Int32"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" parameterNames=""a"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x2"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x3"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <constant name=""y"" value=""2"" type=""Int32"" /> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""z"" value=""3"" type=""Int32"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(543342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543342")] [Fact] public void IteratorLocalConstants() { var source = WithWindowsLineBreaks(@" using System.Collections.Generic; class C { IEnumerable<int> M() { const int x = 1; for (int i = 0; i < 10; i++) { const int y = 2; yield return x + y + i; } } } "); // NOTE: Roslyn's output is somewhat different than Dev10's in this case, but // all of the changes look reasonable. The main thing for this test is that // Dev10 creates fields for the locals in the iterator class. Roslyn doesn't // do that - the <constant> in the <scope> is sufficient. var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>4__this", "<i>5__1" }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x20"" endOffset=""0x67"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> <slot kind=""1"" offset=""37"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x20"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x27"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x2a"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""36"" document=""1"" /> <entry offset=""0x41"" hidden=""true"" document=""1"" /> <entry offset=""0x48"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x49"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x59"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""31"" document=""1"" /> <entry offset=""0x64"" hidden=""true"" document=""1"" /> <entry offset=""0x67"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x69""> <namespace name=""System.Collections.Generic"" /> <scope startOffset=""0x1f"" endOffset=""0x69""> <constant name=""x"" value=""1"" type=""Int32"" /> <scope startOffset=""0x29"" endOffset=""0x49""> <constant name=""y"" value=""2"" type=""Int32"" /> </scope> </scope> </scope> </method> </methods> </symbols>"); } [Fact] [WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")] public void LocalConstantsTypes() { var text = @" class C { void M() { const object o = null; const string s = ""hello""; const float f = float.MinValue; const double d = double.MaxValue; } } "; using (new CultureContext(new CultureInfo("en-US", useUserOverride: false))) { CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""o"" value=""null"" type=""Object"" /> <constant name=""s"" value=""hello"" type=""String"" /> <constant name=""f"" value=""0xFF7FFFFF"" type=""Single"" /> <constant name=""d"" value=""0x7FEFFFFFFFFFFFFF"" type=""Double"" /> </scope> </method> </methods> </symbols>"); } } [Fact] public void WRN_PDBConstantStringValueTooLong() { var longStringValue = new string('a', 2049); var source = @" using System; class C { static void Main() { const string goo = """ + longStringValue + @"""; Console.Write(goo); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); var exebits = new MemoryStream(); var pdbbits = new MemoryStream(); var result = compilation.Emit(exebits, pdbbits); result.Diagnostics.Verify(); // old behavior. This new warning was abandoned // // result.Diagnostics.Verify(// warning CS7063: Constant string value of 'goo' is too long to be used in a PDB file. Only the debug experience may be affected. // Diagnostic(ErrorCode.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) + "...")); // // //make sure that this warning is suppressable // compilation = CreateCompilationWithMscorlib(text, compOptions: Options.Exe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(false). // WithSpecificDiagnosticOptions(new Dictionary<int, ReportWarning>(){ {(int)ErrorCode.WRN_PDBConstantStringValueTooLong, ReportWarning.Suppress} })); // // result = compilation.Emit(exebits, null, "DontCare", pdbbits, null); // result.Diagnostics.Verify(); // // //make sure that this warning can be turned into an error. // compilation = CreateCompilationWithMscorlib(text, compOptions: Options.Exe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(false). // WithSpecificDiagnosticOptions(new Dictionary<int, ReportWarning>() { { (int)ErrorCode.WRN_PDBConstantStringValueTooLong, ReportWarning.Error } })); // // result = compilation.Emit(exebits, null, "DontCare", pdbbits, null); // Assert.False(result.Success); // result.Diagnostics.Verify( // Diagnostic(ErrorCode.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) + "...").WithWarningAsError(true)); } [Fact] public void StringConstantTooLong() { var text = WithWindowsLineBreaks(@" class C { void M() { const string text = @"" this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB""; } } "); var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""43"" startColumn=""5"" endLine=""43"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""43"" startColumn=""5"" endLine=""43"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""text"" value=""\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(178988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988")] [Fact] public void StringWithNulCharacter_MaxSupportedLength() { const int length = 2031; string str = new string('x', 9) + "\0" + new string('x', length - 10); string text = @" class C { void M() { const string x = """ + str + @"""; } } "; var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(178988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988")] [Fact] public void StringWithNulCharacter_OverSupportedLength() { const int length = 2032; string str = new string('x', 9) + "\0" + new string('x', length - 10); string text = @" class C { void M() { const string x = """ + str + @"""; } } "; var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] public void DecimalLocalConstants() { var text = @" class C { void M() { const decimal d = (decimal)1.5; } } "; using (new CultureContext(new CultureInfo("en-US", useUserOverride: false))) { CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""d"" value=""1.5"" type=""Decimal"" /> </scope> </method> </methods> </symbols>"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Globalization; using System.IO; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBConstantTests : CSharpTestBase { [Fact] public void StringsWithSurrogateChar() { var source = @" using System; public class T { public static void Main() { const string HighSurrogateCharacter = ""\uD800""; const string LowSurrogateCharacter = ""\uDC00""; const string MatchedSurrogateCharacters = ""\uD800\uDC00""; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Note: U+FFFD is the Unicode 'replacement character' point and is used to replace an incoming character // whose value is unknown or unrepresentable in Unicode. This is what our pdb writer does with // unpaired surrogates. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <constant name=""HighSurrogateCharacter"" value=""\uFFFD"" type=""String"" /> <constant name=""LowSurrogateCharacter"" value=""\uFFFD"" type=""String"" /> <constant name=""MatchedSurrogateCharacters"" value=""\uD800\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""HighSurrogateCharacter"" value=""\uD800"" type=""String"" /> <constant name=""LowSurrogateCharacter"" value=""\uDC00"" type=""String"" /> <constant name=""MatchedSurrogateCharacters"" value=""\uD800\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(546862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546862")] [Fact] public void InvalidUnicodeString() { var source = @" using System; public class T { public static void Main() { const string invalidUnicodeString = ""\uD800\0\uDC00""; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Note: U+FFFD is the Unicode 'replacement character' point and is used to replace an incoming character // whose value is unknown or unrepresentable in Unicode. This is what our pdb writer does with // unpaired surrogates. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <constant name=""invalidUnicodeString"" value=""\uFFFD\u0000\uFFFD"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""T"" name=""Main""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""invalidUnicodeString"" value=""\uD800\u0000\uDC00"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] public void AllTypes() { var source = @" using System; using System.Collections.Generic; class X {} public class C<S> { enum EnumI1 : sbyte { A } enum EnumU1 : byte { A } enum EnumI2 : short { A } enum EnumU2 : ushort { A } enum EnumI4 : int { A } enum EnumU4 : uint { A } enum EnumI8 : long { A } enum EnumU8 : ulong { A } public static void F<T>() { const bool B = false; const char C = '\0'; const sbyte I1 = 0; const byte U1 = 0; const short I2 = 0; const ushort U2 = 0; const int I4 = 0; const uint U4 = 0; const long I8 = 0; const ulong U8 = 0; const float R4 = 0; const double R8 = 0; const C<int>.EnumI1 EI1 = 0; const C<int>.EnumU1 EU1 = 0; const C<int>.EnumI2 EI2 = 0; const C<int>.EnumU2 EU2 = 0; const C<int>.EnumI4 EI4 = 0; const C<int>.EnumU4 EU4 = 0; const C<int>.EnumI8 EI8 = 0; const C<int>.EnumU8 EU8 = 0; const string StrWithNul = ""\0""; const string EmptyStr = """"; const string NullStr = null; const object NullObject = null; const dynamic NullDynamic = null; const X NullTypeDef = null; const Action NullTypeRef = null; const Func<Dictionary<int, C<int>>, dynamic, T, List<S>> NullTypeSpec = null; const object[] Array1 = null; const object[,] Array2 = null; const object[][] Array3 = null; const decimal D = 0M; // DateTime const not expressible in C# } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C`1.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C`1"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""NullDynamic"" /> <bucket flags=""000001000"" slotId=""0"" localName=""NullTypeSpec"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <constant name=""B"" value=""0"" type=""Boolean"" /> <constant name=""C"" value=""0"" type=""Char"" /> <constant name=""I1"" value=""0"" type=""SByte"" /> <constant name=""U1"" value=""0"" type=""Byte"" /> <constant name=""I2"" value=""0"" type=""Int16"" /> <constant name=""U2"" value=""0"" type=""UInt16"" /> <constant name=""I4"" value=""0"" type=""Int32"" /> <constant name=""U4"" value=""0"" type=""UInt32"" /> <constant name=""I8"" value=""0"" type=""Int64"" /> <constant name=""U8"" value=""0"" type=""UInt64"" /> <constant name=""R4"" value=""0x00000000"" type=""Single"" /> <constant name=""R8"" value=""0x0000000000000000"" type=""Double"" /> <constant name=""EI1"" value=""0"" signature=""EnumI1{Int32}"" /> <constant name=""EU1"" value=""0"" signature=""EnumU1{Int32}"" /> <constant name=""EI2"" value=""0"" signature=""EnumI2{Int32}"" /> <constant name=""EU2"" value=""0"" signature=""EnumU2{Int32}"" /> <constant name=""EI4"" value=""0"" signature=""EnumI4{Int32}"" /> <constant name=""EU4"" value=""0"" signature=""EnumU4{Int32}"" /> <constant name=""EI8"" value=""0"" signature=""EnumI8{Int32}"" /> <constant name=""EU8"" value=""0"" signature=""EnumU8{Int32}"" /> <constant name=""StrWithNul"" value=""\u0000"" type=""String"" /> <constant name=""EmptyStr"" value="""" type=""String"" /> <constant name=""NullStr"" value=""null"" type=""String"" /> <constant name=""NullObject"" value=""null"" type=""Object"" /> <constant name=""NullDynamic"" value=""null"" type=""Object"" /> <constant name=""NullTypeDef"" value=""null"" signature=""X"" /> <constant name=""NullTypeRef"" value=""null"" signature=""System.Action"" /> <constant name=""NullTypeSpec"" value=""null"" signature=""System.Func`4{System.Collections.Generic.Dictionary`2{Int32, C`1{Int32}}, Object, !!0, System.Collections.Generic.List`1{!0}}"" /> <constant name=""Array1"" value=""null"" signature=""Object[]"" /> <constant name=""Array2"" value=""null"" signature=""Object[,,]"" /> <constant name=""Array3"" value=""null"" signature=""Object[][]"" /> <constant name=""D"" value=""0"" type=""Decimal"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SimpleLocalConstant() { var text = @" class C { void M() { const int x = 1; { const int y = 2; } } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <constant name=""x"" value=""1"" type=""Int32"" /> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""y"" value=""2"" type=""Int32"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void LambdaLocalConstants() { var text = WithWindowsLineBreaks(@" using System; class C { void M(Action a) { const int x = 1; M(() => { const int y = 2; { const int z = 3; } }); } } "); var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""a""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""54"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""15"" endColumn=""12"" document=""1"" /> <entry offset=""0x27"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <namespace name=""System"" /> <constant name=""x"" value=""1"" type=""Int32"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" parameterNames=""a"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x2"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x3"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <constant name=""y"" value=""2"" type=""Int32"" /> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""z"" value=""3"" type=""Int32"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(543342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543342")] [Fact] public void IteratorLocalConstants() { var source = WithWindowsLineBreaks(@" using System.Collections.Generic; class C { IEnumerable<int> M() { const int x = 1; for (int i = 0; i < 10; i++) { const int y = 2; yield return x + y + i; } } } "); // NOTE: Roslyn's output is somewhat different than Dev10's in this case, but // all of the changes look reasonable. The main thing for this test is that // Dev10 creates fields for the locals in the iterator class. Roslyn doesn't // do that - the <constant> in the <scope> is sufficient. var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(new[] { "<>1__state", "<>2__current", "<>l__initialThreadId", "<>4__this", "<i>5__1" }, module.GetFieldNames("C.<M>d__0")); }); v.VerifyPdb("C+<M>d__0.MoveNext", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;M&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x20"" endOffset=""0x67"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> <slot kind=""1"" offset=""37"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x20"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x27"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x2a"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""36"" document=""1"" /> <entry offset=""0x41"" hidden=""true"" document=""1"" /> <entry offset=""0x48"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x49"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x59"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""31"" document=""1"" /> <entry offset=""0x64"" hidden=""true"" document=""1"" /> <entry offset=""0x67"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x69""> <namespace name=""System.Collections.Generic"" /> <scope startOffset=""0x1f"" endOffset=""0x69""> <constant name=""x"" value=""1"" type=""Int32"" /> <scope startOffset=""0x29"" endOffset=""0x49""> <constant name=""y"" value=""2"" type=""Int32"" /> </scope> </scope> </scope> </method> </methods> </symbols>"); } [Fact] [WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")] public void LocalConstantsTypes() { var text = @" class C { void M() { const object o = null; const string s = ""hello""; const float f = float.MinValue; const double d = double.MaxValue; } } "; using (new CultureContext(new CultureInfo("en-US", useUserOverride: false))) { CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""o"" value=""null"" type=""Object"" /> <constant name=""s"" value=""hello"" type=""String"" /> <constant name=""f"" value=""0xFF7FFFFF"" type=""Single"" /> <constant name=""d"" value=""0x7FEFFFFFFFFFFFFF"" type=""Double"" /> </scope> </method> </methods> </symbols>"); } } [Fact] public void WRN_PDBConstantStringValueTooLong() { var longStringValue = new string('a', 2049); var source = @" using System; class C { static void Main() { const string goo = """ + longStringValue + @"""; Console.Write(goo); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); var exebits = new MemoryStream(); var pdbbits = new MemoryStream(); var result = compilation.Emit(exebits, pdbbits); result.Diagnostics.Verify(); // old behavior. This new warning was abandoned // // result.Diagnostics.Verify(// warning CS7063: Constant string value of 'goo' is too long to be used in a PDB file. Only the debug experience may be affected. // Diagnostic(ErrorCode.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) + "...")); // // //make sure that this warning is suppressable // compilation = CreateCompilationWithMscorlib(text, compOptions: Options.Exe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(false). // WithSpecificDiagnosticOptions(new Dictionary<int, ReportWarning>(){ {(int)ErrorCode.WRN_PDBConstantStringValueTooLong, ReportWarning.Suppress} })); // // result = compilation.Emit(exebits, null, "DontCare", pdbbits, null); // result.Diagnostics.Verify(); // // //make sure that this warning can be turned into an error. // compilation = CreateCompilationWithMscorlib(text, compOptions: Options.Exe.WithDebugInformationKind(Common.DebugInformationKind.Full).WithOptimizations(false). // WithSpecificDiagnosticOptions(new Dictionary<int, ReportWarning>() { { (int)ErrorCode.WRN_PDBConstantStringValueTooLong, ReportWarning.Error } })); // // result = compilation.Emit(exebits, null, "DontCare", pdbbits, null); // Assert.False(result.Success); // result.Diagnostics.Verify( // Diagnostic(ErrorCode.WRN_PDBConstantStringValueTooLong).WithArguments("goo", longStringValue.Substring(0, 20) + "...").WithWarningAsError(true)); } [Fact] public void StringConstantTooLong() { var text = WithWindowsLineBreaks(@" class C { void M() { const string text = @"" this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB this is a string constant that is too long to fit into the PDB""; } } "); var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""43"" startColumn=""5"" endLine=""43"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""43"" startColumn=""5"" endLine=""43"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""text"" value=""\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB\u000D\u000Athis is a string constant that is too long to fit into the PDB"" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(178988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988")] [Fact] public void StringWithNulCharacter_MaxSupportedLength() { const int length = 2031; string str = new string('x', 9) + "\0" + new string('x', length - 10); string text = @" class C { void M() { const string x = """ + str + @"""; } } "; var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(178988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/178988")] [Fact] public void StringWithNulCharacter_OverSupportedLength() { const int length = 2032; string str = new string('x', 9) + "\0" + new string('x', length - 10); string text = @" class C { void M() { const string x = """ + str + @"""; } } "; var c = CompileAndVerify(text, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""x"" value=""" + str.Replace("\0", @"\u0000") + @""" type=""String"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] public void DecimalLocalConstants() { var text = @" class C { void M() { const decimal d = (decimal)1.5; } } "; using (new CultureContext(new CultureInfo("en-US", useUserOverride: false))) { CompileAndVerify(text, options: TestOptions.DebugDll).VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <constant name=""d"" value=""1.5"" type=""Decimal"" /> </scope> </method> </methods> </symbols>"); } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Portable/Symbols/Attributes/AttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Reflection; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using Microsoft.CodeAnalysis; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an attribute applied to a Symbol. /// </summary> internal abstract partial class CSharpAttributeData : AttributeData { private ThreeState _lazyIsSecurityAttribute = ThreeState.Unknown; /// <summary> /// Gets the attribute class being applied. /// </summary> public new abstract NamedTypeSymbol? AttributeClass { get; } /// <summary> /// Gets the constructor used in this application of the attribute. /// </summary> public new abstract MethodSymbol? AttributeConstructor { get; } /// <summary> /// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols. /// </summary> public new abstract SyntaxReference? ApplicationSyntaxReference { get; } // Overridden to be able to apply MemberNotNull to the new members [MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))] internal override bool HasErrors { get { var hasErrors = base.HasErrors; if (!hasErrors) { Debug.Assert(AttributeClass is not null); Debug.Assert(AttributeConstructor is not null); } return hasErrors; } } /// <summary> /// Gets the list of constructor arguments specified by this application of the attribute. This list contains both positional arguments /// and named arguments that are formal parameters to the constructor. /// </summary> public new IEnumerable<TypedConstant> ConstructorArguments { get { return this.CommonConstructorArguments; } } /// <summary> /// Gets the list of named field or property value arguments specified by this application of the attribute. /// </summary> public new IEnumerable<KeyValuePair<string, TypedConstant>> NamedArguments { get { return this.CommonNamedArguments; } } /// <summary> /// Compares the namespace and type name with the attribute's namespace and type name. /// Returns true if they are the same. /// </summary> internal virtual bool IsTargetAttribute(string namespaceName, string typeName) { Debug.Assert(this.AttributeClass is object); if (!this.AttributeClass.Name.Equals(typeName)) { return false; } if (this.AttributeClass.IsErrorType() && !(this.AttributeClass is MissingMetadataTypeSymbol)) { // Can't guarantee complete name information. return false; } return this.AttributeClass.HasNameQualifier(namespaceName); } internal bool IsTargetAttribute(Symbol targetSymbol, AttributeDescription description) { return GetTargetAttributeSignatureIndex(targetSymbol, description) != -1; } internal abstract int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description); /// <summary> /// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description /// and the attribute description has a signature with parameter count equal to the given attribute syntax's argument list count. /// NOTE: We don't allow early decoded attributes to have optional parameters. /// </summary> internal static bool IsTargetEarlyAttribute(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax, AttributeDescription description) { Debug.Assert(!attributeType.IsErrorType()); int argumentCount = (attributeSyntax.ArgumentList != null) ? attributeSyntax.ArgumentList.Arguments.Count<AttributeArgumentSyntax>((arg) => arg.NameEquals == null) : 0; return AttributeData.IsTargetEarlyAttribute(attributeType, argumentCount, description); } // Security attributes, i.e. attributes derived from well-known SecurityAttribute, are matched by type, not constructor signature. internal bool IsSecurityAttribute(CSharpCompilation compilation) { if (_lazyIsSecurityAttribute == ThreeState.Unknown) { Debug.Assert(!this.HasErrors); // CLI spec (Partition II Metadata), section 21.11 "DeclSecurity : 0x0E" states: // SPEC: If the attribute's type is derived (directly or indirectly) from System.Security.Permissions.SecurityAttribute then // SPEC: it is a security custom attribute and requires special treatment. // NOTE: The native C# compiler violates the above and considers only those attributes whose type derives from // NOTE: System.Security.Permissions.CodeAccessSecurityAttribute as security custom attributes. // NOTE: We will follow the specification. // NOTE: See Devdiv Bug #13762 "Custom security attributes deriving from SecurityAttribute are not treated as security attributes" for details. // Well-known type SecurityAttribute is optional. // Native compiler doesn't generate a use-site error if it is not found, we do the same. var wellKnownType = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAttribute); Debug.Assert(AttributeClass is object); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _lazyIsSecurityAttribute = AttributeClass.IsDerivedFrom(wellKnownType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo).ToThreeState(); } return _lazyIsSecurityAttribute.Value(); } // for testing and debugging only /// <summary> /// Returns the <see cref="System.String"/> that represents the current AttributeData. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current AttributeData.</returns> public override string? ToString() { if (this.AttributeClass is object) { string className = this.AttributeClass.ToDisplayString(SymbolDisplayFormat.TestFormat); if (!this.CommonConstructorArguments.Any() & !this.CommonNamedArguments.Any()) { return className; } var pooledStrbuilder = PooledStringBuilder.GetInstance(); StringBuilder stringBuilder = pooledStrbuilder.Builder; stringBuilder.Append(className); stringBuilder.Append("("); bool first = true; foreach (var constructorArgument in this.CommonConstructorArguments) { if (!first) { stringBuilder.Append(", "); } stringBuilder.Append(constructorArgument.ToCSharpString()); first = false; } foreach (var namedArgument in this.CommonNamedArguments) { if (!first) { stringBuilder.Append(", "); } stringBuilder.Append(namedArgument.Key); stringBuilder.Append(" = "); stringBuilder.Append(namedArgument.Value.ToCSharpString()); first = false; } stringBuilder.Append(")"); return pooledStrbuilder.ToStringAndFree(); } return base.ToString(); } #region AttributeData Implementation /// <summary> /// Gets the attribute class being applied as an <see cref="INamedTypeSymbol"/> /// </summary> protected override INamedTypeSymbol? CommonAttributeClass { get { return this.AttributeClass.GetPublicSymbol(); } } /// <summary> /// Gets the constructor used in this application of the attribute as an <see cref="IMethodSymbol"/>. /// </summary> protected override IMethodSymbol? CommonAttributeConstructor { get { return this.AttributeConstructor.GetPublicSymbol(); } } /// <summary> /// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols. /// </summary> protected override SyntaxReference? CommonApplicationSyntaxReference { get { return this.ApplicationSyntaxReference; } } #endregion #region Attribute Decoding internal void DecodeSecurityAttribute<T>(Symbol targetSymbol, CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, ISecurityAttributeTarget, new() { Debug.Assert(!this.HasErrors); Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag); bool hasErrors; DeclarativeSecurityAction action = DecodeSecurityAttributeAction(targetSymbol, compilation, arguments.AttributeSyntaxOpt, out hasErrors, (BindingDiagnosticBag)arguments.Diagnostics); if (!hasErrors) { T data = arguments.GetOrCreateData<T>(); SecurityWellKnownAttributeData securityData = data.GetOrCreateData(); securityData.SetSecurityAttribute(arguments.Index, action, arguments.AttributesCount); if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PermissionSetAttribute)) { string? resolvedPathForFixup = DecodePermissionSetAttribute(compilation, arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics); if (resolvedPathForFixup != null) { securityData.SetPathForPermissionSetAttributeFixup(arguments.Index, resolvedPathForFixup, arguments.AttributesCount); } } } } internal static void DecodeSkipLocalsInitAttribute<T>(CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, ISkipLocalsInitAttributeTarget, new() { arguments.GetOrCreateData<T>().HasSkipLocalsInitAttribute = true; if (!compilation.Options.AllowUnsafe) { Debug.Assert(arguments.AttributeSyntaxOpt is object); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_IllegalUnsafe, arguments.AttributeSyntaxOpt.Location); } } internal static void DecodeMemberNotNullAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() { var value = arguments.Attribute.CommonConstructorArguments[0]; if (value.IsNull) { return; } if (value.Kind != TypedConstantKind.Array) { string? memberName = value.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { arguments.GetOrCreateData<T>().AddNotNullMember(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } else { var builder = ArrayBuilder<string>.GetInstance(); foreach (var member in value.Values) { var memberName = member.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { builder.Add(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } arguments.GetOrCreateData<T>().AddNotNullMember(builder); builder.Free(); } } private static void ReportBadNotNullMemberIfNeeded(TypeSymbol type, DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, string memberName) { foreach (Symbol foundMember in type.GetMembers(memberName)) { if (foundMember.Kind == SymbolKind.Field || foundMember.Kind == SymbolKind.Property) { return; } } Debug.Assert(arguments.AttributeSyntaxOpt is object); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.WRN_MemberNotNullBadMember, arguments.AttributeSyntaxOpt.Location, memberName); } internal static void DecodeMemberNotNullWhenAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() { var value = arguments.Attribute.CommonConstructorArguments[1]; if (value.IsNull) { return; } var sense = arguments.Attribute.CommonConstructorArguments[0].DecodeValue<bool>(SpecialType.System_Boolean); if (value.Kind != TypedConstantKind.Array) { var memberName = value.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } else { var builder = ArrayBuilder<string>.GetInstance(); foreach (var member in value.Values) { var memberName = member.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { builder.Add(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, builder); builder.Free(); } } private DeclarativeSecurityAction DecodeSecurityAttributeAction(Symbol targetSymbol, CSharpCompilation compilation, AttributeSyntax? nodeOpt, out bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert((object)targetSymbol != null); Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method); Debug.Assert(this.IsSecurityAttribute(compilation)); var ctorArgs = this.CommonConstructorArguments; if (!ctorArgs.Any()) { // NOTE: Security custom attributes must have a valid SecurityAction as its first argument, we have none here. // NOTE: Ideally, we should always generate 'CS7048: First argument to a security attribute must be a valid SecurityAction' for this case. // NOTE: However, native compiler allows applying System.Security.Permissions.HostProtectionAttribute attribute without any argument and uses // NOTE: SecurityAction.LinkDemand as the default SecurityAction in this case. We maintain compatibility with the native compiler for this case. // BREAKING CHANGE: Even though the native compiler intends to allow only HostProtectionAttribute to be applied without any arguments, // it doesn't quite do this correctly // The implementation issue leads to the native compiler allowing any user defined security attribute with a parameterless constructor and a named property argument as the first // attribute argument to have the above mentioned behavior, even though the comment clearly mentions that this behavior was intended only for the HostProtectionAttribute. // We currently allow this case only for the HostProtectionAttribute. In future if need arises, we can exactly match native compiler's behavior. if (this.IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute)) { hasErrors = false; return DeclarativeSecurityAction.LinkDemand; } } else { TypedConstant firstArg = ctorArgs.First(); var firstArgType = (TypeSymbol?)firstArg.TypeInternal; if (firstArgType is object && firstArgType.Equals(compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction))) { return DecodeSecurityAction(firstArg, targetSymbol, nodeOpt, diagnostics, out hasErrors); } } // CS7048: First argument to a security attribute must be a valid SecurityAction diagnostics.Add(ErrorCode.ERR_SecurityAttributeMissingAction, nodeOpt != null ? nodeOpt.Name.Location : NoLocation.Singleton); hasErrors = true; return DeclarativeSecurityAction.None; } private DeclarativeSecurityAction DecodeSecurityAction(TypedConstant typedValue, Symbol targetSymbol, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics, out bool hasErrors) { Debug.Assert((object)targetSymbol != null); Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method); Debug.Assert(typedValue.ValueInternal is object); int securityAction = (int)typedValue.ValueInternal; bool isPermissionRequestAction; switch (securityAction) { case (int)DeclarativeSecurityAction.InheritanceDemand: case (int)DeclarativeSecurityAction.LinkDemand: if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PrincipalPermissionAttribute)) { // CS7052: SecurityAction value '{0}' is invalid for PrincipalPermission attribute object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_PrincipalPermissionInvalidAction, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } isPermissionRequestAction = false; break; case 1: // Native compiler allows security action value 1 for security attributes on types/methods, even though there is no corresponding field in System.Security.Permissions.SecurityAction enum. // We will maintain compatibility. case (int)DeclarativeSecurityAction.Assert: case (int)DeclarativeSecurityAction.Demand: case (int)DeclarativeSecurityAction.PermitOnly: case (int)DeclarativeSecurityAction.Deny: isPermissionRequestAction = false; break; case (int)DeclarativeSecurityAction.RequestMinimum: case (int)DeclarativeSecurityAction.RequestOptional: case (int)DeclarativeSecurityAction.RequestRefuse: isPermissionRequestAction = true; break; default: { // CS7049: Security attribute '{0}' has an invalid SecurityAction value '{1}' object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidAction, syntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "", displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } // Validate security action for symbol kind if (isPermissionRequestAction) { if (targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method) { // Types and methods cannot take permission requests. // CS7051: SecurityAction value '{0}' is invalid for security attributes applied to a type or a method object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } else { if (targetSymbol.Kind == SymbolKind.Assembly) { // Assemblies cannot take declarative security. // CS7050: SecurityAction value '{0}' is invalid for security attributes applied to an assembly object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } hasErrors = false; return (DeclarativeSecurityAction)securityAction; } private static Location GetSecurityAttributeActionSyntaxLocation(AttributeSyntax? nodeOpt, TypedConstant typedValue, out object displayString) { if (nodeOpt == null) { displayString = ""; return NoLocation.Singleton; } var argList = nodeOpt.ArgumentList; if (argList == null || argList.Arguments.IsEmpty()) { // Optional SecurityAction parameter with default value. displayString = (FormattableString)$"{typedValue.ValueInternal}"; return nodeOpt.Location; } AttributeArgumentSyntax argSyntax = argList.Arguments[0]; displayString = argSyntax.ToString(); return argSyntax.Location; } /// <summary> /// Decodes PermissionSetAttribute applied in source to determine if it needs any fixup during codegen. /// </summary> /// <remarks> /// PermissionSetAttribute needs fixup when it contains an assignment to the 'File' property as a single named attribute argument. /// Fixup performed is ported from SecurityAttributes::FixUpPermissionSetAttribute. /// It involves following steps: /// 1) Verifying that the specified file name resolves to a valid path. /// 2) Reading the contents of the file into a byte array. /// 3) Convert each byte in the file content into two bytes containing hexadecimal characters. /// 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above. /// /// Step 1) is performed in this method, i.e. during binding. /// Remaining steps are performed during serialization as we want to avoid retaining the entire file contents throughout the binding/codegen pass. /// See <see cref="Microsoft.CodeAnalysis.CodeGen.PermissionSetAttributeWithFileReference"/> for remaining fixup steps. /// </remarks> /// <returns>String containing the resolved file path if PermissionSetAttribute needs fixup during codegen, null otherwise.</returns> private string? DecodePermissionSetAttribute(CSharpCompilation compilation, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); string? resolvedFilePath = null; var namedArgs = this.CommonNamedArguments; if (namedArgs.Length == 1) { var namedArg = namedArgs[0]; Debug.Assert(AttributeClass is object); NamedTypeSymbol attrType = this.AttributeClass; string filePropName = PermissionSetAttributeWithFileReference.FilePropertyName; string hexPropName = PermissionSetAttributeWithFileReference.HexPropertyName; if (namedArg.Key == filePropName && PermissionSetAttributeTypeHasRequiredProperty(attrType, filePropName)) { // resolve file prop path var fileName = (string?)namedArg.Value.ValueInternal; var resolver = compilation.Options.XmlReferenceResolver; resolvedFilePath = (resolver != null && fileName != null) ? resolver.ResolveReference(fileName, baseFilePath: null) : null; if (resolvedFilePath == null) { // CS7053: Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute Location argSyntaxLocation = nodeOpt?.GetNamedArgumentSyntax(filePropName)?.Location ?? NoLocation.Singleton; diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeInvalidFile, argSyntaxLocation, fileName ?? "<null>", filePropName); } else if (!PermissionSetAttributeTypeHasRequiredProperty(attrType, hexPropName)) { // PermissionSetAttribute was defined in user source, but doesn't have the required Hex property. // Native compiler still emits the file content as named assignment to 'Hex' property, but this leads to a runtime exception. // We instead skip the fixup and emit the file property. // CONSIDER: We may want to consider taking a breaking change and generating an error here. return null; } } } return resolvedFilePath; } // This method checks if the given PermissionSetAttribute type has a property member with the given propName which is writable, non-generic, public and of string type. private static bool PermissionSetAttributeTypeHasRequiredProperty(NamedTypeSymbol permissionSetType, string propName) { var members = permissionSetType.GetMembers(propName); if (members.Length == 1 && members[0].Kind == SymbolKind.Property) { var property = (PropertySymbol)members[0]; if (property.TypeWithAnnotations.HasType && property.Type.SpecialType == SpecialType.System_String && property.DeclaredAccessibility == Accessibility.Public && property.GetMemberArity() == 0 && (object)property.SetMethod != null && property.SetMethod.DeclaredAccessibility == Accessibility.Public) { return true; } } return false; } internal void DecodeClassInterfaceAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); TypedConstant ctorArgument = this.CommonConstructorArguments[0]; Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive); ClassInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ? ctorArgument.DecodeValue<ClassInterfaceType>(SpecialType.System_Enum) : (ClassInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16); switch (interfaceType) { case ClassInterfaceType.None: case Cci.Constants.ClassInterfaceType_AutoDispatch: case Cci.Constants.ClassInterfaceType_AutoDual: break; default: // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); break; } } internal void DecodeInterfaceTypeAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); TypedConstant ctorArgument = this.CommonConstructorArguments[0]; Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive); ComInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ? ctorArgument.DecodeValue<ComInterfaceType>(SpecialType.System_Enum) : (ComInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16); switch (interfaceType) { case Cci.Constants.ComInterfaceType_InterfaceIsDual: case Cci.Constants.ComInterfaceType_InterfaceIsIDispatch: case ComInterfaceType.InterfaceIsIInspectable: case ComInterfaceType.InterfaceIsIUnknown: break; default: // CS0591: Invalid value for argument to '{0}' attribute CSharpSyntaxNode attributeArgumentSyntax = this.GetAttributeArgumentSyntax(0, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); break; } } internal string DecodeGuidAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); var guidString = (string?)this.CommonConstructorArguments[0].ValueInternal; // Native compiler allows only a specific GUID format: "D" format (32 digits separated by hyphens) Guid guid; if (!Guid.TryParseExact(guidString, "D", out guid)) { // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); guidString = String.Empty; } return guidString!; } private protected sealed override bool IsStringProperty(string memberName) { if (AttributeClass is object) { foreach (var member in AttributeClass.GetMembers(memberName)) { if (member is PropertySymbol { Type: { SpecialType: SpecialType.System_String } }) { return true; } } } return false; } #endregion /// <summary> /// This method determines if an applied attribute must be emitted. /// Some attributes appear in symbol model to reflect the source code, /// but should not be emitted. /// </summary> internal bool ShouldEmitAttribute(Symbol target, bool isReturnType, bool emittingAssemblyAttributesInNetModule) { Debug.Assert(target is SourceAssemblySymbol || target.ContainingAssembly is SourceAssemblySymbol); if (HasErrors) { throw ExceptionUtilities.Unreachable; } // Attribute type is conditionally omitted if both the following are true: // (a) It has at least one applied/inherited conditional attribute AND // (b) None of conditional symbols are defined in the source file where the given attribute was defined. if (this.IsConditionallyOmitted) { return false; } switch (target.Kind) { case SymbolKind.Assembly: if ((!emittingAssemblyAttributesInNetModule && (IsTargetAttribute(target, AttributeDescription.AssemblyCultureAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyVersionAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyFlagsAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyAlgorithmIdAttribute))) || IsTargetAttribute(target, AttributeDescription.TypeForwardedToAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } break; case SymbolKind.Event: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute)) { return false; } break; case SymbolKind.Field: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) || IsTargetAttribute(target, AttributeDescription.FieldOffsetAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } break; case SymbolKind.Method: if (isReturnType) { if (IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } } else { if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.MethodImplAttribute) || IsTargetAttribute(target, AttributeDescription.DllImportAttribute) || IsTargetAttribute(target, AttributeDescription.PreserveSigAttribute) || IsTargetAttribute(target, AttributeDescription.DynamicSecurityMethodAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } } break; case SymbolKind.NetModule: // Note that DefaultCharSetAttribute is emitted to metadata, although it's also decoded and used when emitting P/Invoke break; case SymbolKind.NamedType: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.ComImportAttribute) || IsTargetAttribute(target, AttributeDescription.SerializableAttribute) || IsTargetAttribute(target, AttributeDescription.StructLayoutAttribute) || IsTargetAttribute(target, AttributeDescription.WindowsRuntimeImportAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } break; case SymbolKind.Parameter: if (IsTargetAttribute(target, AttributeDescription.OptionalAttribute) || IsTargetAttribute(target, AttributeDescription.DefaultParameterValueAttribute) || IsTargetAttribute(target, AttributeDescription.InAttribute) || IsTargetAttribute(target, AttributeDescription.OutAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } break; case SymbolKind.Property: if (IsTargetAttribute(target, AttributeDescription.IndexerNameAttribute) || IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.DisallowNullAttribute) || IsTargetAttribute(target, AttributeDescription.AllowNullAttribute) || IsTargetAttribute(target, AttributeDescription.MaybeNullAttribute) || IsTargetAttribute(target, AttributeDescription.NotNullAttribute)) { return false; } break; } return true; } } internal static class AttributeDataExtensions { internal static int IndexOfAttribute(this ImmutableArray<CSharpAttributeData> attributes, Symbol targetSymbol, AttributeDescription description) { for (int i = 0; i < attributes.Length; i++) { if (attributes[i].IsTargetAttribute(targetSymbol, description)) { return i; } } return -1; } internal static CSharpSyntaxNode GetAttributeArgumentSyntax(this AttributeData attribute, int parameterIndex, AttributeSyntax attributeSyntax) { Debug.Assert(attribute is SourceAttributeData); return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntax); } internal static string? DecodeNotNullIfNotNullAttribute(this CSharpAttributeData attribute) { var arguments = attribute.CommonConstructorArguments; return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_String, out string? value) ? value : null; } internal static Location GetAttributeArgumentSyntaxLocation(this AttributeData attribute, int parameterIndex, AttributeSyntax? attributeSyntaxOpt) { if (attributeSyntaxOpt == null) { return NoLocation.Singleton; } Debug.Assert(attribute is SourceAttributeData); return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntaxOpt).Location; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Reflection; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using Microsoft.CodeAnalysis; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents an attribute applied to a Symbol. /// </summary> internal abstract partial class CSharpAttributeData : AttributeData { private ThreeState _lazyIsSecurityAttribute = ThreeState.Unknown; /// <summary> /// Gets the attribute class being applied. /// </summary> public new abstract NamedTypeSymbol? AttributeClass { get; } /// <summary> /// Gets the constructor used in this application of the attribute. /// </summary> public new abstract MethodSymbol? AttributeConstructor { get; } /// <summary> /// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols. /// </summary> public new abstract SyntaxReference? ApplicationSyntaxReference { get; } // Overridden to be able to apply MemberNotNull to the new members [MemberNotNullWhen(true, nameof(AttributeClass), nameof(AttributeConstructor))] internal override bool HasErrors { get { var hasErrors = base.HasErrors; if (!hasErrors) { Debug.Assert(AttributeClass is not null); Debug.Assert(AttributeConstructor is not null); } return hasErrors; } } /// <summary> /// Gets the list of constructor arguments specified by this application of the attribute. This list contains both positional arguments /// and named arguments that are formal parameters to the constructor. /// </summary> public new IEnumerable<TypedConstant> ConstructorArguments { get { return this.CommonConstructorArguments; } } /// <summary> /// Gets the list of named field or property value arguments specified by this application of the attribute. /// </summary> public new IEnumerable<KeyValuePair<string, TypedConstant>> NamedArguments { get { return this.CommonNamedArguments; } } /// <summary> /// Compares the namespace and type name with the attribute's namespace and type name. /// Returns true if they are the same. /// </summary> internal virtual bool IsTargetAttribute(string namespaceName, string typeName) { Debug.Assert(this.AttributeClass is object); if (!this.AttributeClass.Name.Equals(typeName)) { return false; } if (this.AttributeClass.IsErrorType() && !(this.AttributeClass is MissingMetadataTypeSymbol)) { // Can't guarantee complete name information. return false; } return this.AttributeClass.HasNameQualifier(namespaceName); } internal bool IsTargetAttribute(Symbol targetSymbol, AttributeDescription description) { return GetTargetAttributeSignatureIndex(targetSymbol, description) != -1; } internal abstract int GetTargetAttributeSignatureIndex(Symbol targetSymbol, AttributeDescription description); /// <summary> /// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description /// and the attribute description has a signature with parameter count equal to the given attribute syntax's argument list count. /// NOTE: We don't allow early decoded attributes to have optional parameters. /// </summary> internal static bool IsTargetEarlyAttribute(NamedTypeSymbol attributeType, AttributeSyntax attributeSyntax, AttributeDescription description) { Debug.Assert(!attributeType.IsErrorType()); int argumentCount = (attributeSyntax.ArgumentList != null) ? attributeSyntax.ArgumentList.Arguments.Count<AttributeArgumentSyntax>((arg) => arg.NameEquals == null) : 0; return AttributeData.IsTargetEarlyAttribute(attributeType, argumentCount, description); } // Security attributes, i.e. attributes derived from well-known SecurityAttribute, are matched by type, not constructor signature. internal bool IsSecurityAttribute(CSharpCompilation compilation) { if (_lazyIsSecurityAttribute == ThreeState.Unknown) { Debug.Assert(!this.HasErrors); // CLI spec (Partition II Metadata), section 21.11 "DeclSecurity : 0x0E" states: // SPEC: If the attribute's type is derived (directly or indirectly) from System.Security.Permissions.SecurityAttribute then // SPEC: it is a security custom attribute and requires special treatment. // NOTE: The native C# compiler violates the above and considers only those attributes whose type derives from // NOTE: System.Security.Permissions.CodeAccessSecurityAttribute as security custom attributes. // NOTE: We will follow the specification. // NOTE: See Devdiv Bug #13762 "Custom security attributes deriving from SecurityAttribute are not treated as security attributes" for details. // Well-known type SecurityAttribute is optional. // Native compiler doesn't generate a use-site error if it is not found, we do the same. var wellKnownType = compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAttribute); Debug.Assert(AttributeClass is object); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _lazyIsSecurityAttribute = AttributeClass.IsDerivedFrom(wellKnownType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo).ToThreeState(); } return _lazyIsSecurityAttribute.Value(); } // for testing and debugging only /// <summary> /// Returns the <see cref="System.String"/> that represents the current AttributeData. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current AttributeData.</returns> public override string? ToString() { if (this.AttributeClass is object) { string className = this.AttributeClass.ToDisplayString(SymbolDisplayFormat.TestFormat); if (!this.CommonConstructorArguments.Any() & !this.CommonNamedArguments.Any()) { return className; } var pooledStrbuilder = PooledStringBuilder.GetInstance(); StringBuilder stringBuilder = pooledStrbuilder.Builder; stringBuilder.Append(className); stringBuilder.Append("("); bool first = true; foreach (var constructorArgument in this.CommonConstructorArguments) { if (!first) { stringBuilder.Append(", "); } stringBuilder.Append(constructorArgument.ToCSharpString()); first = false; } foreach (var namedArgument in this.CommonNamedArguments) { if (!first) { stringBuilder.Append(", "); } stringBuilder.Append(namedArgument.Key); stringBuilder.Append(" = "); stringBuilder.Append(namedArgument.Value.ToCSharpString()); first = false; } stringBuilder.Append(")"); return pooledStrbuilder.ToStringAndFree(); } return base.ToString(); } #region AttributeData Implementation /// <summary> /// Gets the attribute class being applied as an <see cref="INamedTypeSymbol"/> /// </summary> protected override INamedTypeSymbol? CommonAttributeClass { get { return this.AttributeClass.GetPublicSymbol(); } } /// <summary> /// Gets the constructor used in this application of the attribute as an <see cref="IMethodSymbol"/>. /// </summary> protected override IMethodSymbol? CommonAttributeConstructor { get { return this.AttributeConstructor.GetPublicSymbol(); } } /// <summary> /// Gets a reference to the source for this application of the attribute. Returns null for applications of attributes on metadata Symbols. /// </summary> protected override SyntaxReference? CommonApplicationSyntaxReference { get { return this.ApplicationSyntaxReference; } } #endregion #region Attribute Decoding internal void DecodeSecurityAttribute<T>(Symbol targetSymbol, CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, ISecurityAttributeTarget, new() { Debug.Assert(!this.HasErrors); Debug.Assert(arguments.Diagnostics is BindingDiagnosticBag); bool hasErrors; DeclarativeSecurityAction action = DecodeSecurityAttributeAction(targetSymbol, compilation, arguments.AttributeSyntaxOpt, out hasErrors, (BindingDiagnosticBag)arguments.Diagnostics); if (!hasErrors) { T data = arguments.GetOrCreateData<T>(); SecurityWellKnownAttributeData securityData = data.GetOrCreateData(); securityData.SetSecurityAttribute(arguments.Index, action, arguments.AttributesCount); if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PermissionSetAttribute)) { string? resolvedPathForFixup = DecodePermissionSetAttribute(compilation, arguments.AttributeSyntaxOpt, (BindingDiagnosticBag)arguments.Diagnostics); if (resolvedPathForFixup != null) { securityData.SetPathForPermissionSetAttributeFixup(arguments.Index, resolvedPathForFixup, arguments.AttributesCount); } } } } internal static void DecodeSkipLocalsInitAttribute<T>(CSharpCompilation compilation, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, ISkipLocalsInitAttributeTarget, new() { arguments.GetOrCreateData<T>().HasSkipLocalsInitAttribute = true; if (!compilation.Options.AllowUnsafe) { Debug.Assert(arguments.AttributeSyntaxOpt is object); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_IllegalUnsafe, arguments.AttributeSyntaxOpt.Location); } } internal static void DecodeMemberNotNullAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() { var value = arguments.Attribute.CommonConstructorArguments[0]; if (value.IsNull) { return; } if (value.Kind != TypedConstantKind.Array) { string? memberName = value.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { arguments.GetOrCreateData<T>().AddNotNullMember(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } else { var builder = ArrayBuilder<string>.GetInstance(); foreach (var member in value.Values) { var memberName = member.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { builder.Add(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } arguments.GetOrCreateData<T>().AddNotNullMember(builder); builder.Free(); } } private static void ReportBadNotNullMemberIfNeeded(TypeSymbol type, DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, string memberName) { foreach (Symbol foundMember in type.GetMembers(memberName)) { if (foundMember.Kind == SymbolKind.Field || foundMember.Kind == SymbolKind.Property) { return; } } Debug.Assert(arguments.AttributeSyntaxOpt is object); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.WRN_MemberNotNullBadMember, arguments.AttributeSyntaxOpt.Location, memberName); } internal static void DecodeMemberNotNullWhenAttribute<T>(TypeSymbol type, ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) where T : WellKnownAttributeData, IMemberNotNullAttributeTarget, new() { var value = arguments.Attribute.CommonConstructorArguments[1]; if (value.IsNull) { return; } var sense = arguments.Attribute.CommonConstructorArguments[0].DecodeValue<bool>(SpecialType.System_Boolean); if (value.Kind != TypedConstantKind.Array) { var memberName = value.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } else { var builder = ArrayBuilder<string>.GetInstance(); foreach (var member in value.Values) { var memberName = member.DecodeValue<string>(SpecialType.System_String); if (memberName is object) { builder.Add(memberName); ReportBadNotNullMemberIfNeeded(type, arguments, memberName); } } arguments.GetOrCreateData<T>().AddNotNullWhenMember(sense, builder); builder.Free(); } } private DeclarativeSecurityAction DecodeSecurityAttributeAction(Symbol targetSymbol, CSharpCompilation compilation, AttributeSyntax? nodeOpt, out bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert((object)targetSymbol != null); Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method); Debug.Assert(this.IsSecurityAttribute(compilation)); var ctorArgs = this.CommonConstructorArguments; if (!ctorArgs.Any()) { // NOTE: Security custom attributes must have a valid SecurityAction as its first argument, we have none here. // NOTE: Ideally, we should always generate 'CS7048: First argument to a security attribute must be a valid SecurityAction' for this case. // NOTE: However, native compiler allows applying System.Security.Permissions.HostProtectionAttribute attribute without any argument and uses // NOTE: SecurityAction.LinkDemand as the default SecurityAction in this case. We maintain compatibility with the native compiler for this case. // BREAKING CHANGE: Even though the native compiler intends to allow only HostProtectionAttribute to be applied without any arguments, // it doesn't quite do this correctly // The implementation issue leads to the native compiler allowing any user defined security attribute with a parameterless constructor and a named property argument as the first // attribute argument to have the above mentioned behavior, even though the comment clearly mentions that this behavior was intended only for the HostProtectionAttribute. // We currently allow this case only for the HostProtectionAttribute. In future if need arises, we can exactly match native compiler's behavior. if (this.IsTargetAttribute(targetSymbol, AttributeDescription.HostProtectionAttribute)) { hasErrors = false; return DeclarativeSecurityAction.LinkDemand; } } else { TypedConstant firstArg = ctorArgs.First(); var firstArgType = (TypeSymbol?)firstArg.TypeInternal; if (firstArgType is object && firstArgType.Equals(compilation.GetWellKnownType(WellKnownType.System_Security_Permissions_SecurityAction))) { return DecodeSecurityAction(firstArg, targetSymbol, nodeOpt, diagnostics, out hasErrors); } } // CS7048: First argument to a security attribute must be a valid SecurityAction diagnostics.Add(ErrorCode.ERR_SecurityAttributeMissingAction, nodeOpt != null ? nodeOpt.Name.Location : NoLocation.Singleton); hasErrors = true; return DeclarativeSecurityAction.None; } private DeclarativeSecurityAction DecodeSecurityAction(TypedConstant typedValue, Symbol targetSymbol, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics, out bool hasErrors) { Debug.Assert((object)targetSymbol != null); Debug.Assert(targetSymbol.Kind == SymbolKind.Assembly || targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method); Debug.Assert(typedValue.ValueInternal is object); int securityAction = (int)typedValue.ValueInternal; bool isPermissionRequestAction; switch (securityAction) { case (int)DeclarativeSecurityAction.InheritanceDemand: case (int)DeclarativeSecurityAction.LinkDemand: if (this.IsTargetAttribute(targetSymbol, AttributeDescription.PrincipalPermissionAttribute)) { // CS7052: SecurityAction value '{0}' is invalid for PrincipalPermission attribute object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_PrincipalPermissionInvalidAction, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } isPermissionRequestAction = false; break; case 1: // Native compiler allows security action value 1 for security attributes on types/methods, even though there is no corresponding field in System.Security.Permissions.SecurityAction enum. // We will maintain compatibility. case (int)DeclarativeSecurityAction.Assert: case (int)DeclarativeSecurityAction.Demand: case (int)DeclarativeSecurityAction.PermitOnly: case (int)DeclarativeSecurityAction.Deny: isPermissionRequestAction = false; break; case (int)DeclarativeSecurityAction.RequestMinimum: case (int)DeclarativeSecurityAction.RequestOptional: case (int)DeclarativeSecurityAction.RequestRefuse: isPermissionRequestAction = true; break; default: { // CS7049: Security attribute '{0}' has an invalid SecurityAction value '{1}' object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidAction, syntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : "", displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } // Validate security action for symbol kind if (isPermissionRequestAction) { if (targetSymbol.Kind == SymbolKind.NamedType || targetSymbol.Kind == SymbolKind.Method) { // Types and methods cannot take permission requests. // CS7051: SecurityAction value '{0}' is invalid for security attributes applied to a type or a method object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } else { if (targetSymbol.Kind == SymbolKind.Assembly) { // Assemblies cannot take declarative security. // CS7050: SecurityAction value '{0}' is invalid for security attributes applied to an assembly object displayString; Location syntaxLocation = GetSecurityAttributeActionSyntaxLocation(nodeOpt, typedValue, out displayString); diagnostics.Add(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, syntaxLocation, displayString); hasErrors = true; return DeclarativeSecurityAction.None; } } hasErrors = false; return (DeclarativeSecurityAction)securityAction; } private static Location GetSecurityAttributeActionSyntaxLocation(AttributeSyntax? nodeOpt, TypedConstant typedValue, out object displayString) { if (nodeOpt == null) { displayString = ""; return NoLocation.Singleton; } var argList = nodeOpt.ArgumentList; if (argList == null || argList.Arguments.IsEmpty()) { // Optional SecurityAction parameter with default value. displayString = (FormattableString)$"{typedValue.ValueInternal}"; return nodeOpt.Location; } AttributeArgumentSyntax argSyntax = argList.Arguments[0]; displayString = argSyntax.ToString(); return argSyntax.Location; } /// <summary> /// Decodes PermissionSetAttribute applied in source to determine if it needs any fixup during codegen. /// </summary> /// <remarks> /// PermissionSetAttribute needs fixup when it contains an assignment to the 'File' property as a single named attribute argument. /// Fixup performed is ported from SecurityAttributes::FixUpPermissionSetAttribute. /// It involves following steps: /// 1) Verifying that the specified file name resolves to a valid path. /// 2) Reading the contents of the file into a byte array. /// 3) Convert each byte in the file content into two bytes containing hexadecimal characters. /// 4) Replacing the 'File = fileName' named argument with 'Hex = hexFileContent' argument, where hexFileContent is the converted output from step 3) above. /// /// Step 1) is performed in this method, i.e. during binding. /// Remaining steps are performed during serialization as we want to avoid retaining the entire file contents throughout the binding/codegen pass. /// See <see cref="Microsoft.CodeAnalysis.CodeGen.PermissionSetAttributeWithFileReference"/> for remaining fixup steps. /// </remarks> /// <returns>String containing the resolved file path if PermissionSetAttribute needs fixup during codegen, null otherwise.</returns> private string? DecodePermissionSetAttribute(CSharpCompilation compilation, AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); string? resolvedFilePath = null; var namedArgs = this.CommonNamedArguments; if (namedArgs.Length == 1) { var namedArg = namedArgs[0]; Debug.Assert(AttributeClass is object); NamedTypeSymbol attrType = this.AttributeClass; string filePropName = PermissionSetAttributeWithFileReference.FilePropertyName; string hexPropName = PermissionSetAttributeWithFileReference.HexPropertyName; if (namedArg.Key == filePropName && PermissionSetAttributeTypeHasRequiredProperty(attrType, filePropName)) { // resolve file prop path var fileName = (string?)namedArg.Value.ValueInternal; var resolver = compilation.Options.XmlReferenceResolver; resolvedFilePath = (resolver != null && fileName != null) ? resolver.ResolveReference(fileName, baseFilePath: null) : null; if (resolvedFilePath == null) { // CS7053: Unable to resolve file path '{0}' specified for the named argument '{1}' for PermissionSet attribute Location argSyntaxLocation = nodeOpt?.GetNamedArgumentSyntax(filePropName)?.Location ?? NoLocation.Singleton; diagnostics.Add(ErrorCode.ERR_PermissionSetAttributeInvalidFile, argSyntaxLocation, fileName ?? "<null>", filePropName); } else if (!PermissionSetAttributeTypeHasRequiredProperty(attrType, hexPropName)) { // PermissionSetAttribute was defined in user source, but doesn't have the required Hex property. // Native compiler still emits the file content as named assignment to 'Hex' property, but this leads to a runtime exception. // We instead skip the fixup and emit the file property. // CONSIDER: We may want to consider taking a breaking change and generating an error here. return null; } } } return resolvedFilePath; } // This method checks if the given PermissionSetAttribute type has a property member with the given propName which is writable, non-generic, public and of string type. private static bool PermissionSetAttributeTypeHasRequiredProperty(NamedTypeSymbol permissionSetType, string propName) { var members = permissionSetType.GetMembers(propName); if (members.Length == 1 && members[0].Kind == SymbolKind.Property) { var property = (PropertySymbol)members[0]; if (property.TypeWithAnnotations.HasType && property.Type.SpecialType == SpecialType.System_String && property.DeclaredAccessibility == Accessibility.Public && property.GetMemberArity() == 0 && (object)property.SetMethod != null && property.SetMethod.DeclaredAccessibility == Accessibility.Public) { return true; } } return false; } internal void DecodeClassInterfaceAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); TypedConstant ctorArgument = this.CommonConstructorArguments[0]; Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive); ClassInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ? ctorArgument.DecodeValue<ClassInterfaceType>(SpecialType.System_Enum) : (ClassInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16); switch (interfaceType) { case ClassInterfaceType.None: case Cci.Constants.ClassInterfaceType_AutoDispatch: case Cci.Constants.ClassInterfaceType_AutoDual: break; default: // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); break; } } internal void DecodeInterfaceTypeAttribute(AttributeSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); TypedConstant ctorArgument = this.CommonConstructorArguments[0]; Debug.Assert(ctorArgument.Kind == TypedConstantKind.Enum || ctorArgument.Kind == TypedConstantKind.Primitive); ComInterfaceType interfaceType = ctorArgument.Kind == TypedConstantKind.Enum ? ctorArgument.DecodeValue<ComInterfaceType>(SpecialType.System_Enum) : (ComInterfaceType)ctorArgument.DecodeValue<short>(SpecialType.System_Int16); switch (interfaceType) { case Cci.Constants.ComInterfaceType_InterfaceIsDual: case Cci.Constants.ComInterfaceType_InterfaceIsIDispatch: case ComInterfaceType.InterfaceIsIInspectable: case ComInterfaceType.InterfaceIsIUnknown: break; default: // CS0591: Invalid value for argument to '{0}' attribute CSharpSyntaxNode attributeArgumentSyntax = this.GetAttributeArgumentSyntax(0, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); break; } } internal string DecodeGuidAttribute(AttributeSyntax? nodeOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!this.HasErrors); var guidString = (string?)this.CommonConstructorArguments[0].ValueInternal; // Native compiler allows only a specific GUID format: "D" format (32 digits separated by hyphens) Guid guid; if (!Guid.TryParseExact(guidString, "D", out guid)) { // CS0591: Invalid value for argument to '{0}' attribute Location attributeArgumentSyntaxLocation = this.GetAttributeArgumentSyntaxLocation(0, nodeOpt); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntaxLocation, nodeOpt != null ? nodeOpt.GetErrorDisplayName() : ""); guidString = String.Empty; } return guidString!; } private protected sealed override bool IsStringProperty(string memberName) { if (AttributeClass is object) { foreach (var member in AttributeClass.GetMembers(memberName)) { if (member is PropertySymbol { Type: { SpecialType: SpecialType.System_String } }) { return true; } } } return false; } #endregion /// <summary> /// This method determines if an applied attribute must be emitted. /// Some attributes appear in symbol model to reflect the source code, /// but should not be emitted. /// </summary> internal bool ShouldEmitAttribute(Symbol target, bool isReturnType, bool emittingAssemblyAttributesInNetModule) { Debug.Assert(target is SourceAssemblySymbol || target.ContainingAssembly is SourceAssemblySymbol); if (HasErrors) { throw ExceptionUtilities.Unreachable; } // Attribute type is conditionally omitted if both the following are true: // (a) It has at least one applied/inherited conditional attribute AND // (b) None of conditional symbols are defined in the source file where the given attribute was defined. if (this.IsConditionallyOmitted) { return false; } switch (target.Kind) { case SymbolKind.Assembly: if ((!emittingAssemblyAttributesInNetModule && (IsTargetAttribute(target, AttributeDescription.AssemblyCultureAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyVersionAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyFlagsAttribute) || IsTargetAttribute(target, AttributeDescription.AssemblyAlgorithmIdAttribute))) || IsTargetAttribute(target, AttributeDescription.TypeForwardedToAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } break; case SymbolKind.Event: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute)) { return false; } break; case SymbolKind.Field: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.NonSerializedAttribute) || IsTargetAttribute(target, AttributeDescription.FieldOffsetAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } break; case SymbolKind.Method: if (isReturnType) { if (IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } } else { if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.MethodImplAttribute) || IsTargetAttribute(target, AttributeDescription.DllImportAttribute) || IsTargetAttribute(target, AttributeDescription.PreserveSigAttribute) || IsTargetAttribute(target, AttributeDescription.DynamicSecurityMethodAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } } break; case SymbolKind.NetModule: // Note that DefaultCharSetAttribute is emitted to metadata, although it's also decoded and used when emitting P/Invoke break; case SymbolKind.NamedType: if (IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.ComImportAttribute) || IsTargetAttribute(target, AttributeDescription.SerializableAttribute) || IsTargetAttribute(target, AttributeDescription.StructLayoutAttribute) || IsTargetAttribute(target, AttributeDescription.WindowsRuntimeImportAttribute) || IsSecurityAttribute(target.DeclaringCompilation)) { return false; } break; case SymbolKind.Parameter: if (IsTargetAttribute(target, AttributeDescription.OptionalAttribute) || IsTargetAttribute(target, AttributeDescription.DefaultParameterValueAttribute) || IsTargetAttribute(target, AttributeDescription.InAttribute) || IsTargetAttribute(target, AttributeDescription.OutAttribute) || IsTargetAttribute(target, AttributeDescription.MarshalAsAttribute)) { return false; } break; case SymbolKind.Property: if (IsTargetAttribute(target, AttributeDescription.IndexerNameAttribute) || IsTargetAttribute(target, AttributeDescription.SpecialNameAttribute) || IsTargetAttribute(target, AttributeDescription.DisallowNullAttribute) || IsTargetAttribute(target, AttributeDescription.AllowNullAttribute) || IsTargetAttribute(target, AttributeDescription.MaybeNullAttribute) || IsTargetAttribute(target, AttributeDescription.NotNullAttribute)) { return false; } break; } return true; } } internal static class AttributeDataExtensions { internal static int IndexOfAttribute(this ImmutableArray<CSharpAttributeData> attributes, Symbol targetSymbol, AttributeDescription description) { for (int i = 0; i < attributes.Length; i++) { if (attributes[i].IsTargetAttribute(targetSymbol, description)) { return i; } } return -1; } internal static CSharpSyntaxNode GetAttributeArgumentSyntax(this AttributeData attribute, int parameterIndex, AttributeSyntax attributeSyntax) { Debug.Assert(attribute is SourceAttributeData); return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntax); } internal static string? DecodeNotNullIfNotNullAttribute(this CSharpAttributeData attribute) { var arguments = attribute.CommonConstructorArguments; return arguments.Length == 1 && arguments[0].TryDecodeValue(SpecialType.System_String, out string? value) ? value : null; } internal static Location GetAttributeArgumentSyntaxLocation(this AttributeData attribute, int parameterIndex, AttributeSyntax? attributeSyntaxOpt) { if (attributeSyntaxOpt == null) { return NoLocation.Singleton; } Debug.Assert(attribute is SourceAttributeData); return ((SourceAttributeData)attribute).GetAttributeArgumentSyntax(parameterIndex, attributeSyntaxOpt).Location; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/EndOfFileTokenFormattingRule.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Formatting.Rules; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class EndOfFileTokenFormattingRule : BaseFormattingRule { internal const string Name = "CSharp End Of File Token Formatting Rule"; public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { // * <End Of File> case for C#, make sure we don't insert new line between * and <End of // File> tokens. if (currentToken.Kind() == SyntaxKind.EndOfFileToken) { return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines); } return nextOperation.Invoke(in previousToken, in currentToken); } public override AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { // * <End Of File) case // for C#, make sure we have nothing between these two tokens if (currentToken.Kind() == SyntaxKind.EndOfFileToken) { return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine); } return nextOperation.Invoke(in previousToken, in currentToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Formatting.Rules; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class EndOfFileTokenFormattingRule : BaseFormattingRule { internal const string Name = "CSharp End Of File Token Formatting Rule"; public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { // * <End Of File> case for C#, make sure we don't insert new line between * and <End of // File> tokens. if (currentToken.Kind() == SyntaxKind.EndOfFileToken) { return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines); } return nextOperation.Invoke(in previousToken, in currentToken); } public override AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { // * <End Of File) case // for C#, make sure we have nothing between these two tokens if (currentToken.Kind() == SyntaxKind.EndOfFileToken) { return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine); } return nextOperation.Invoke(in previousToken, in currentToken); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Analyzers/CSharp/CodeFixes/UseConditionalExpression/CSharpUseConditionalExpressionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseConditionalExpression { internal static class CSharpUseConditionalExpressionHelpers { public static ExpressionSyntax ConvertToExpression(IThrowOperation throwOperation) { var throwStatement = (ThrowStatementSyntax)throwOperation.Syntax; RoslynDebug.Assert(throwStatement.Expression != null); return SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseConditionalExpression { internal static class CSharpUseConditionalExpressionHelpers { public static ExpressionSyntax ConvertToExpression(IThrowOperation throwOperation) { var throwStatement = (ThrowStatementSyntax)throwOperation.Syntax; RoslynDebug.Assert(throwStatement.Expression != null); return SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/CSharpTest2/Recommendations/VarKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class VarKeywordRecommenderTests : RecommenderTests { private readonly VarKeywordRecommender _recommender = new VarKeywordRecommender(); public VarKeywordRecommenderTests() { this.keywordText = "var"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFixedStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateReturnType() { await VerifyAbsenceAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { // Could be a deconstruction await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { // Could be a deconstruction await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock() { await VerifyAbsenceAsync(AddInsideMethod( @"lock $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock2() { await VerifyAbsenceAsync(AddInsideMethod( @"lock ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock3() { await VerifyAbsenceAsync(AddInsideMethod( @"lock (l$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFor() { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor2() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor3() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVar() { await VerifyAbsenceAsync(AddInsideMethod( @"var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForEach() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInForEach() { await VerifyAbsenceAsync(AddInsideMethod( @"foreach (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAwaitForEach() { await VerifyKeywordAsync(AddInsideMethod( @"await foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAwaitForEach() { await VerifyAbsenceAsync(AddInsideMethod( @"await foreach (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForEachRefLoop0() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForEachRefLoop1() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (ref $$ x")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForEachRefLoop2() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (ref v$$ x")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForEachRefReadonlyLoop0() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (ref readonly $$ x")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForRefLoop0() { await VerifyKeywordAsync(AddInsideMethod( @"for (ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForRefLoop1() { await VerifyKeywordAsync(AddInsideMethod( @"for (ref v$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForRefReadonlyLoop0() { await VerifyKeywordAsync(AddInsideMethod( @"for (ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForRefReadonlyLoop1() { await VerifyKeywordAsync(AddInsideMethod( @"for (ref readonly v$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsing() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsing() { await VerifyAbsenceAsync(AddInsideMethod( @"using (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAwaitUsing() { await VerifyKeywordAsync(AddInsideMethod( @"await using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAwaitUsing() { await VerifyAbsenceAsync(AddInsideMethod( @"await using (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocal() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstField() { await VerifyAbsenceAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(12121, "https://github.com/dotnet/roslyn/issues/12121")] public async Task TestAfterOutKeywordInArgument() { await VerifyKeywordAsync(AddInsideMethod( @"M(out $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(12121, "https://github.com/dotnet/roslyn/issues/12121")] public async Task TestAfterOutKeywordInParameter() { await VerifyAbsenceAsync( @"class C { void M1(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestVarPatternInSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch(o) { case $$ } ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestVarPatternInIs() => await VerifyKeywordAsync(AddInsideMethod("var b = o is $$ ")); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefInMemberContext() { await VerifyAbsenceAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefReadonlyInMemberContext() { await VerifyAbsenceAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } // For a local function, we can't add any tests - sometimes the keyword is offered and sometimes it's not, // depending on whether the keyword is partially written or not. This is because a partially written keyword // causes this to be parsed as a local declaration instead. We can't add either test because // VerifyKeywordAsync & VerifyAbsenceAsync check for both cases - with the keyword partially written and without. [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); } [WorkItem(10170, "https://github.com/dotnet/roslyn/issues/10170")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyPattern() { await VerifyKeywordAsync( @" using System; class Person { public string Name; } class Program { void Goo(object o) { if (o is Person { Name: $$ }) { Console.WriteLine(n); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDeclarationDeconstruction() { await VerifyAbsenceAsync(AddInsideMethod( @"var (x, $$) = (0, 0);")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyKeywordAsync(AddInsideMethod( @"(x, $$) = (0, 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class VarKeywordRecommenderTests : RecommenderTests { private readonly VarKeywordRecommender _recommender = new VarKeywordRecommender(); public VarKeywordRecommenderTests() { this.keywordText = "var"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFixedStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateReturnType() { await VerifyAbsenceAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { // Could be a deconstruction await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { // Could be a deconstruction await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock() { await VerifyAbsenceAsync(AddInsideMethod( @"lock $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock2() { await VerifyAbsenceAsync(AddInsideMethod( @"lock ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterLock3() { await VerifyAbsenceAsync(AddInsideMethod( @"lock (l$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClass() { await VerifyAbsenceAsync(@"class C { $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFor() { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor2() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFor3() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVar() { await VerifyAbsenceAsync(AddInsideMethod( @"var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForEach() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInForEach() { await VerifyAbsenceAsync(AddInsideMethod( @"foreach (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAwaitForEach() { await VerifyKeywordAsync(AddInsideMethod( @"await foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAwaitForEach() { await VerifyAbsenceAsync(AddInsideMethod( @"await foreach (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForEachRefLoop0() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForEachRefLoop1() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (ref $$ x")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForEachRefLoop2() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (ref v$$ x")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForEachRefReadonlyLoop0() { await VerifyKeywordAsync(AddInsideMethod( @"foreach (ref readonly $$ x")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForRefLoop0() { await VerifyKeywordAsync(AddInsideMethod( @"for (ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForRefLoop1() { await VerifyKeywordAsync(AddInsideMethod( @"for (ref v$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForRefReadonlyLoop0() { await VerifyKeywordAsync(AddInsideMethod( @"for (ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(37223, "https://github.com/dotnet/roslyn/issues/37223")] public async Task TestInForRefReadonlyLoop1() { await VerifyKeywordAsync(AddInsideMethod( @"for (ref readonly v$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsing() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsing() { await VerifyAbsenceAsync(AddInsideMethod( @"using (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAwaitUsing() { await VerifyKeywordAsync(AddInsideMethod( @"await using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAwaitUsing() { await VerifyAbsenceAsync(AddInsideMethod( @"await using (var $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocal() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConstField() { await VerifyAbsenceAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(12121, "https://github.com/dotnet/roslyn/issues/12121")] public async Task TestAfterOutKeywordInArgument() { await VerifyKeywordAsync(AddInsideMethod( @"M(out $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(12121, "https://github.com/dotnet/roslyn/issues/12121")] public async Task TestAfterOutKeywordInParameter() { await VerifyAbsenceAsync( @"class C { void M1(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestVarPatternInSwitch() { await VerifyKeywordAsync(AddInsideMethod( @"switch(o) { case $$ } ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestVarPatternInIs() => await VerifyKeywordAsync(AddInsideMethod("var b = o is $$ ")); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefInMemberContext() { await VerifyAbsenceAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefReadonlyInMemberContext() { await VerifyAbsenceAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } // For a local function, we can't add any tests - sometimes the keyword is offered and sometimes it's not, // depending on whether the keyword is partially written or not. This is because a partially written keyword // causes this to be parsed as a local declaration instead. We can't add either test because // VerifyKeywordAsync & VerifyAbsenceAsync check for both cases - with the keyword partially written and without. [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); } [WorkItem(10170, "https://github.com/dotnet/roslyn/issues/10170")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPropertyPattern() { await VerifyKeywordAsync( @" using System; class Person { public string Name; } class Program { void Goo(object o) { if (o is Person { Name: $$ }) { Console.WriteLine(n); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDeclarationDeconstruction() { await VerifyAbsenceAsync(AddInsideMethod( @"var (x, $$) = (0, 0);")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyKeywordAsync(AddInsideMethod( @"(x, $$) = (0, 0);")); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/CSharp/Portable/ConvertNumericLiteral/CSharpConvertNumericLiteralCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertNumericLiteral; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertNumericLiteral { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral), Shared] internal sealed class CSharpConvertNumericLiteralCodeRefactoringProvider : AbstractConvertNumericLiteralCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertNumericLiteralCodeRefactoringProvider() { } protected override (string hexPrefix, string binaryPrefix) GetNumericLiteralPrefixes() => (hexPrefix: "0x", binaryPrefix: "0b"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertNumericLiteral; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertNumericLiteral { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertNumericLiteral), Shared] internal sealed class CSharpConvertNumericLiteralCodeRefactoringProvider : AbstractConvertNumericLiteralCodeRefactoringProvider<LiteralExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertNumericLiteralCodeRefactoringProvider() { } protected override (string hexPrefix, string binaryPrefix) GetNumericLiteralPrefixes() => (hexPrefix: "0x", binaryPrefix: "0b"); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Test/PdbUtilities/Shared/DummyMetadataImport.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.DiaSymReader.PortablePdb; using System.Reflection; namespace Roslyn.Test.PdbUtilities { internal sealed class DummyMetadataImport : IMetadataImport, IDisposable { private readonly MetadataReader _metadataReaderOpt; private readonly IDisposable _metadataOwnerOpt; private readonly List<GCHandle> _pinnedBuffers; public DummyMetadataImport(MetadataReader metadataReaderOpt, IDisposable metadataOwnerOpt) { _metadataReaderOpt = metadataReaderOpt; _pinnedBuffers = new List<GCHandle>(); _metadataOwnerOpt = metadataOwnerOpt; } public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } private void Dispose(bool disposing) { _metadataOwnerOpt?.Dispose(); foreach (var pinnedBuffer in _pinnedBuffers) { pinnedBuffer.Free(); } } ~DummyMetadataImport() { Dispose(false); } [PreserveSig] public unsafe int GetSigFromToken( int tkSignature, // Signature token. out byte* ppvSig, // return pointer to signature blob out int pcbSig) // return size of signature { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var sig = _metadataReaderOpt.GetStandaloneSignature((StandaloneSignatureHandle)MetadataTokens.Handle(tkSignature)); var signature = _metadataReaderOpt.GetBlobBytes(sig.Signature); GCHandle pinnedBuffer = GCHandle.Alloc(signature, GCHandleType.Pinned); ppvSig = (byte*)pinnedBuffer.AddrOfPinnedObject(); pcbSig = signature.Length; #pragma warning disable RS0042 // Do not copy value _pinnedBuffers.Add(pinnedBuffer); #pragma warning restore RS0042 // Do not copy value return 0; } public void GetTypeDefProps( int typeDefinition, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder qualifiedName, int qualifiedNameBufferLength, out int qualifiedNameLength, [MarshalAs(UnmanagedType.U4)] out TypeAttributes attributes, out int baseType) { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var handle = (TypeDefinitionHandle)MetadataTokens.Handle(typeDefinition); var typeDef = _metadataReaderOpt.GetTypeDefinition(handle); if (qualifiedName != null) { qualifiedName.Clear(); if (!typeDef.Namespace.IsNil) { qualifiedName.Append(_metadataReaderOpt.GetString(typeDef.Namespace)); qualifiedName.Append('.'); } qualifiedName.Append(_metadataReaderOpt.GetString(typeDef.Name)); qualifiedNameLength = qualifiedName.Length; } else { qualifiedNameLength = (typeDef.Namespace.IsNil ? 0 : _metadataReaderOpt.GetString(typeDef.Namespace).Length + 1) + _metadataReaderOpt.GetString(typeDef.Name).Length; } baseType = MetadataTokens.GetToken(typeDef.BaseType); attributes = typeDef.Attributes; } public void GetTypeRefProps( int typeReference, out int resolutionScope, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder qualifiedName, int qualifiedNameBufferLength, out int qualifiedNameLength) { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var handle = (TypeReferenceHandle)MetadataTokens.Handle(typeReference); var typeRef = _metadataReaderOpt.GetTypeReference(handle); if (qualifiedName != null) { qualifiedName.Clear(); if (!typeRef.Namespace.IsNil) { qualifiedName.Append(_metadataReaderOpt.GetString(typeRef.Namespace)); qualifiedName.Append('.'); } qualifiedName.Append(_metadataReaderOpt.GetString(typeRef.Name)); qualifiedNameLength = qualifiedName.Length; } else { qualifiedNameLength = (typeRef.Namespace.IsNil ? 0 : _metadataReaderOpt.GetString(typeRef.Namespace).Length + 1) + _metadataReaderOpt.GetString(typeRef.Name).Length; } resolutionScope = MetadataTokens.GetToken(typeRef.ResolutionScope); } #region Not Implemented public void CloseEnum(uint handleEnum) { throw new NotImplementedException(); } public uint CountEnum(uint handleEnum) { throw new NotImplementedException(); } public uint EnumCustomAttributes(ref uint handlePointerEnum, uint tk, uint tokenType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayCustomAttributes, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumEvents(ref uint handlePointerEnum, uint td, uint* arrayEvents, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumFields(ref uint handlePointerEnum, uint cl, uint* arrayFields, uint countMax) { throw new NotImplementedException(); } public uint EnumFieldsWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayFields, uint countMax) { throw new NotImplementedException(); } public uint EnumInterfaceImpls(ref uint handlePointerEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayImpls, uint countMax) { throw new NotImplementedException(); } public uint EnumMemberRefs(ref uint handlePointerEnum, uint tokenParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayMemberRefs, uint countMax) { throw new NotImplementedException(); } public uint EnumMembers(ref uint handlePointerEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayMembers, uint countMax) { throw new NotImplementedException(); } public uint EnumMembersWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMembers, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodImpls(ref uint handlePointerEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethodDecl, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumMethods(ref uint handlePointerEnum, uint cl, uint* arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodSemantics(ref uint handlePointerEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayEventProp, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodsWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumModuleRefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayModuleRefs, uint cmax) { throw new NotImplementedException(); } public uint EnumParams(ref uint handlePointerEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayParams, uint countMax) { throw new NotImplementedException(); } public uint EnumPermissionSets(ref uint handlePointerEnum, uint tk, uint dwordActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayPermission, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumProperties(ref uint handlePointerEnum, uint td, uint* arrayProperties, uint countMax) { throw new NotImplementedException(); } public uint EnumSignatures(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arraySignatures, uint cmax) { throw new NotImplementedException(); } public uint EnumTypeDefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeDefs, uint countMax) { throw new NotImplementedException(); } public uint EnumTypeRefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeRefs, uint countMax) { throw new NotImplementedException(); } public uint EnumTypeSpecs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeSpecs, uint cmax) { throw new NotImplementedException(); } public uint EnumUnresolvedMethods(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumUserStrings(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayStrings, uint cmax) { throw new NotImplementedException(); } public uint FindField(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMember(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMemberRef(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMethod(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindTypeDefByName(string stringTypeDef, uint tokenEnclosingClass) { throw new NotImplementedException(); } public uint FindTypeRef(uint tokenResolutionScope, string stringName) { throw new NotImplementedException(); } public uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] ulong[] arrayFieldOffset, uint countMax, out uint countPointerFieldOffset) { throw new NotImplementedException(); } public unsafe uint GetCustomAttributeByName(uint tokenObj, string stringName, out void* ppData) { throw new NotImplementedException(); } public unsafe uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out void* ppBlob) { throw new NotImplementedException(); } public uint GetEventProps(uint ev, out uint pointerClass, StringBuilder stringEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint countMax) { throw new NotImplementedException(); } public unsafe uint GetFieldMarshal(uint tk, out byte* ppvNativeType) { throw new NotImplementedException(); } public unsafe uint GetFieldProps(uint mb, out uint pointerClass, StringBuilder stringField, uint cchField, out uint pchField, out uint pdwAttr, out byte* ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public uint GetInterfaceImplProps(uint impl, out uint pointerClass) { throw new NotImplementedException(); } public unsafe uint GetMemberProps(uint mb, out uint pointerClass, StringBuilder stringMember, uint cchMember, out uint pchMember, out uint pdwAttr, out byte* ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public unsafe uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder stringMember, uint cchMember, out uint pchMember, out byte* ppvSigBlob) { throw new NotImplementedException(); } public uint GetMethodProps(uint mb, out uint pointerClass, IntPtr stringMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA) { throw new NotImplementedException(); } public uint GetMethodSemantics(uint mb, uint tokenEventProp) { throw new NotImplementedException(); } public uint GetModuleFromScope() { throw new NotImplementedException(); } public uint GetModuleRefProps(uint mur, StringBuilder stringName, uint cchName) { throw new NotImplementedException(); } public uint GetNameFromToken(uint tk) { throw new NotImplementedException(); } public unsafe uint GetNativeCallConvFromSig(void* voidPointerSig, uint byteCountSig) { throw new NotImplementedException(); } public uint GetNestedClassProps(uint typeDefNestedClass) { throw new NotImplementedException(); } public int GetParamForMethodIndex(uint md, uint ulongParamSeq, out uint pointerParam) { throw new NotImplementedException(); } public unsafe uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder stringName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public unsafe uint GetPermissionSetProps(uint pm, out uint pdwAction, out void* ppvPermission) { throw new NotImplementedException(); } public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder stringImportName, uint cchImportName, out uint pchImportName) { throw new NotImplementedException(); } public unsafe uint GetPropertyProps(uint prop, out uint pointerClass, StringBuilder stringProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out byte* ppvSig, out uint bytePointerSig, out uint pdwCPlusTypeFlag, out void* ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint countMax) { throw new NotImplementedException(); } public uint GetRVA(uint tk, out uint pulCodeRVA) { throw new NotImplementedException(); } public Guid GetScopeProps(StringBuilder stringName, uint cchName, out uint pchName) { throw new NotImplementedException(); } public unsafe uint GetTypeSpecFromToken(uint typespec, out byte* ppvSig) { throw new NotImplementedException(); } public uint GetUserString(uint stk, StringBuilder stringString, uint cchString) { throw new NotImplementedException(); } public int IsGlobal(uint pd) { throw new NotImplementedException(); } [return: MarshalAs(UnmanagedType.Bool)] public bool IsValidToken(uint tk) { throw new NotImplementedException(); } public void ResetEnum(uint handleEnum, uint ulongPos) { throw new NotImplementedException(); } public uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope) { throw new NotImplementedException(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.DiaSymReader.PortablePdb; using System.Reflection; namespace Roslyn.Test.PdbUtilities { internal sealed class DummyMetadataImport : IMetadataImport, IDisposable { private readonly MetadataReader _metadataReaderOpt; private readonly IDisposable _metadataOwnerOpt; private readonly List<GCHandle> _pinnedBuffers; public DummyMetadataImport(MetadataReader metadataReaderOpt, IDisposable metadataOwnerOpt) { _metadataReaderOpt = metadataReaderOpt; _pinnedBuffers = new List<GCHandle>(); _metadataOwnerOpt = metadataOwnerOpt; } public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } private void Dispose(bool disposing) { _metadataOwnerOpt?.Dispose(); foreach (var pinnedBuffer in _pinnedBuffers) { pinnedBuffer.Free(); } } ~DummyMetadataImport() { Dispose(false); } [PreserveSig] public unsafe int GetSigFromToken( int tkSignature, // Signature token. out byte* ppvSig, // return pointer to signature blob out int pcbSig) // return size of signature { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var sig = _metadataReaderOpt.GetStandaloneSignature((StandaloneSignatureHandle)MetadataTokens.Handle(tkSignature)); var signature = _metadataReaderOpt.GetBlobBytes(sig.Signature); GCHandle pinnedBuffer = GCHandle.Alloc(signature, GCHandleType.Pinned); ppvSig = (byte*)pinnedBuffer.AddrOfPinnedObject(); pcbSig = signature.Length; #pragma warning disable RS0042 // Do not copy value _pinnedBuffers.Add(pinnedBuffer); #pragma warning restore RS0042 // Do not copy value return 0; } public void GetTypeDefProps( int typeDefinition, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder qualifiedName, int qualifiedNameBufferLength, out int qualifiedNameLength, [MarshalAs(UnmanagedType.U4)] out TypeAttributes attributes, out int baseType) { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var handle = (TypeDefinitionHandle)MetadataTokens.Handle(typeDefinition); var typeDef = _metadataReaderOpt.GetTypeDefinition(handle); if (qualifiedName != null) { qualifiedName.Clear(); if (!typeDef.Namespace.IsNil) { qualifiedName.Append(_metadataReaderOpt.GetString(typeDef.Namespace)); qualifiedName.Append('.'); } qualifiedName.Append(_metadataReaderOpt.GetString(typeDef.Name)); qualifiedNameLength = qualifiedName.Length; } else { qualifiedNameLength = (typeDef.Namespace.IsNil ? 0 : _metadataReaderOpt.GetString(typeDef.Namespace).Length + 1) + _metadataReaderOpt.GetString(typeDef.Name).Length; } baseType = MetadataTokens.GetToken(typeDef.BaseType); attributes = typeDef.Attributes; } public void GetTypeRefProps( int typeReference, out int resolutionScope, [MarshalAs(UnmanagedType.LPWStr), Out] StringBuilder qualifiedName, int qualifiedNameBufferLength, out int qualifiedNameLength) { if (_metadataReaderOpt == null) { throw new NotSupportedException("Metadata not available"); } var handle = (TypeReferenceHandle)MetadataTokens.Handle(typeReference); var typeRef = _metadataReaderOpt.GetTypeReference(handle); if (qualifiedName != null) { qualifiedName.Clear(); if (!typeRef.Namespace.IsNil) { qualifiedName.Append(_metadataReaderOpt.GetString(typeRef.Namespace)); qualifiedName.Append('.'); } qualifiedName.Append(_metadataReaderOpt.GetString(typeRef.Name)); qualifiedNameLength = qualifiedName.Length; } else { qualifiedNameLength = (typeRef.Namespace.IsNil ? 0 : _metadataReaderOpt.GetString(typeRef.Namespace).Length + 1) + _metadataReaderOpt.GetString(typeRef.Name).Length; } resolutionScope = MetadataTokens.GetToken(typeRef.ResolutionScope); } #region Not Implemented public void CloseEnum(uint handleEnum) { throw new NotImplementedException(); } public uint CountEnum(uint handleEnum) { throw new NotImplementedException(); } public uint EnumCustomAttributes(ref uint handlePointerEnum, uint tk, uint tokenType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayCustomAttributes, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumEvents(ref uint handlePointerEnum, uint td, uint* arrayEvents, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumFields(ref uint handlePointerEnum, uint cl, uint* arrayFields, uint countMax) { throw new NotImplementedException(); } public uint EnumFieldsWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayFields, uint countMax) { throw new NotImplementedException(); } public uint EnumInterfaceImpls(ref uint handlePointerEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayImpls, uint countMax) { throw new NotImplementedException(); } public uint EnumMemberRefs(ref uint handlePointerEnum, uint tokenParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayMemberRefs, uint countMax) { throw new NotImplementedException(); } public uint EnumMembers(ref uint handlePointerEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayMembers, uint countMax) { throw new NotImplementedException(); } public uint EnumMembersWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMembers, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodImpls(ref uint handlePointerEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethodDecl, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumMethods(ref uint handlePointerEnum, uint cl, uint* arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodSemantics(ref uint handlePointerEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayEventProp, uint countMax) { throw new NotImplementedException(); } public uint EnumMethodsWithName(ref uint handlePointerEnum, uint cl, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumModuleRefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayModuleRefs, uint cmax) { throw new NotImplementedException(); } public uint EnumParams(ref uint handlePointerEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] arrayParams, uint countMax) { throw new NotImplementedException(); } public uint EnumPermissionSets(ref uint handlePointerEnum, uint tk, uint dwordActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] arrayPermission, uint countMax) { throw new NotImplementedException(); } public unsafe uint EnumProperties(ref uint handlePointerEnum, uint td, uint* arrayProperties, uint countMax) { throw new NotImplementedException(); } public uint EnumSignatures(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arraySignatures, uint cmax) { throw new NotImplementedException(); } public uint EnumTypeDefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeDefs, uint countMax) { throw new NotImplementedException(); } public uint EnumTypeRefs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeRefs, uint countMax) { throw new NotImplementedException(); } public uint EnumTypeSpecs(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayTypeSpecs, uint cmax) { throw new NotImplementedException(); } public uint EnumUnresolvedMethods(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayMethods, uint countMax) { throw new NotImplementedException(); } public uint EnumUserStrings(ref uint handlePointerEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] arrayStrings, uint cmax) { throw new NotImplementedException(); } public uint FindField(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMember(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMemberRef(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindMethod(uint td, string stringName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] voidPointerSigBlob, uint byteCountSigBlob) { throw new NotImplementedException(); } public uint FindTypeDefByName(string stringTypeDef, uint tokenEnclosingClass) { throw new NotImplementedException(); } public uint FindTypeRef(uint tokenResolutionScope, string stringName) { throw new NotImplementedException(); } public uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] ulong[] arrayFieldOffset, uint countMax, out uint countPointerFieldOffset) { throw new NotImplementedException(); } public unsafe uint GetCustomAttributeByName(uint tokenObj, string stringName, out void* ppData) { throw new NotImplementedException(); } public unsafe uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out void* ppBlob) { throw new NotImplementedException(); } public uint GetEventProps(uint ev, out uint pointerClass, StringBuilder stringEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint countMax) { throw new NotImplementedException(); } public unsafe uint GetFieldMarshal(uint tk, out byte* ppvNativeType) { throw new NotImplementedException(); } public unsafe uint GetFieldProps(uint mb, out uint pointerClass, StringBuilder stringField, uint cchField, out uint pchField, out uint pdwAttr, out byte* ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public uint GetInterfaceImplProps(uint impl, out uint pointerClass) { throw new NotImplementedException(); } public unsafe uint GetMemberProps(uint mb, out uint pointerClass, StringBuilder stringMember, uint cchMember, out uint pchMember, out uint pdwAttr, out byte* ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public unsafe uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder stringMember, uint cchMember, out uint pchMember, out byte* ppvSigBlob) { throw new NotImplementedException(); } public uint GetMethodProps(uint mb, out uint pointerClass, IntPtr stringMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA) { throw new NotImplementedException(); } public uint GetMethodSemantics(uint mb, uint tokenEventProp) { throw new NotImplementedException(); } public uint GetModuleFromScope() { throw new NotImplementedException(); } public uint GetModuleRefProps(uint mur, StringBuilder stringName, uint cchName) { throw new NotImplementedException(); } public uint GetNameFromToken(uint tk) { throw new NotImplementedException(); } public unsafe uint GetNativeCallConvFromSig(void* voidPointerSig, uint byteCountSig) { throw new NotImplementedException(); } public uint GetNestedClassProps(uint typeDefNestedClass) { throw new NotImplementedException(); } public int GetParamForMethodIndex(uint md, uint ulongParamSeq, out uint pointerParam) { throw new NotImplementedException(); } public unsafe uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder stringName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out void* ppValue) { throw new NotImplementedException(); } public unsafe uint GetPermissionSetProps(uint pm, out uint pdwAction, out void* ppvPermission) { throw new NotImplementedException(); } public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder stringImportName, uint cchImportName, out uint pchImportName) { throw new NotImplementedException(); } public unsafe uint GetPropertyProps(uint prop, out uint pointerClass, StringBuilder stringProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out byte* ppvSig, out uint bytePointerSig, out uint pdwCPlusTypeFlag, out void* ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint countMax) { throw new NotImplementedException(); } public uint GetRVA(uint tk, out uint pulCodeRVA) { throw new NotImplementedException(); } public Guid GetScopeProps(StringBuilder stringName, uint cchName, out uint pchName) { throw new NotImplementedException(); } public unsafe uint GetTypeSpecFromToken(uint typespec, out byte* ppvSig) { throw new NotImplementedException(); } public uint GetUserString(uint stk, StringBuilder stringString, uint cchString) { throw new NotImplementedException(); } public int IsGlobal(uint pd) { throw new NotImplementedException(); } [return: MarshalAs(UnmanagedType.Bool)] public bool IsValidToken(uint tk) { throw new NotImplementedException(); } public void ResetEnum(uint handleEnum, uint ulongPos) { throw new NotImplementedException(); } public uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope) { throw new NotImplementedException(); } #endregion } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/AbstractUseTypeCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseType { internal abstract class AbstractUseTypeCodeRefactoringProvider : CodeRefactoringProvider { protected abstract string Title { get; } protected abstract Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken); protected abstract TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken); protected abstract TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var declaration = await GetDeclarationAsync(context).ConfigureAwait(false); if (declaration == null) { return; } Debug.Assert(declaration.IsKind(SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.DeclarationExpression)); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredType = FindAnalyzableType(declaration, semanticModel, cancellationToken); if (declaredType == null) { return; } var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var typeStyle = AnalyzeTypeName(declaredType, semanticModel, optionSet, cancellationToken); if (typeStyle.IsStylePreferred && typeStyle.Severity != ReportDiagnostic.Suppress) { // the analyzer would handle this. So we do not. return; } if (!typeStyle.CanConvert()) { return; } context.RegisterRefactoring( new MyCodeAction( Title, c => UpdateDocumentAsync(document, declaredType, c)), declaredType.Span); } private static async Task<SyntaxNode> GetDeclarationAsync(CodeRefactoringContext context) { // We want to provide refactoring for changing the Type of newly introduced variables in following cases: // - DeclarationExpressionSyntax: `"42".TryParseInt32(out var number)` // - VariableDeclarationSyntax: General field / variable declaration statement `var number = 42` // - ForEachStatementSyntax: The variable that gets introduced by foreach `foreach(var number in numbers)` // // In addition to providing the refactoring when the whole node (i.e. the node that introduces the new variable) in question is selected // we also want to enable it when only the type node is selected because this refactoring changes the type. We still have to make sure // we're only working on TypeNodes for in above-mentioned situations. // // For foreach we need to guard against selecting just the expression because it is also of type `TypeSyntax`. var declNode = await context.TryGetRelevantNodeAsync<DeclarationExpressionSyntax>().ConfigureAwait(false); if (declNode != null) return declNode; var variableNode = await context.TryGetRelevantNodeAsync<VariableDeclarationSyntax>().ConfigureAwait(false); if (variableNode != null) return variableNode; // `ref var` is a bit of an interesting construct. 'ref' looks like a modifier, but is actually a // type-syntax. Ensure the user can get the feature anywhere on this construct var type = await context.TryGetRelevantNodeAsync<TypeSyntax>().ConfigureAwait(false); if (type?.Parent is RefTypeSyntax) type = (TypeSyntax)type.Parent; if (type?.Parent is VariableDeclarationSyntax) return type.Parent; var foreachStatement = await context.TryGetRelevantNodeAsync<ForEachStatementSyntax>().ConfigureAwait(false); if (foreachStatement != null) return foreachStatement; var syntaxFacts = context.Document.GetLanguageService<ISyntaxFactsService>(); var typeNode = await context.TryGetRelevantNodeAsync<TypeSyntax>().ConfigureAwait(false); var typeNodeParent = typeNode?.Parent; if (typeNodeParent != null && (typeNodeParent.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.VariableDeclaration) || (typeNodeParent.IsKind(SyntaxKind.ForEachStatement) && !syntaxFacts.IsExpressionOfForeach(typeNode)))) { return typeNodeParent; } return null; } private async Task<Document> UpdateDocumentAsync(Document document, TypeSyntax type, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); await HandleDeclarationAsync(document, editor, type, cancellationToken).ConfigureAwait(false); var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseType { internal abstract class AbstractUseTypeCodeRefactoringProvider : CodeRefactoringProvider { protected abstract string Title { get; } protected abstract Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken); protected abstract TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken); protected abstract TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, textSpan, cancellationToken) = context; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var declaration = await GetDeclarationAsync(context).ConfigureAwait(false); if (declaration == null) { return; } Debug.Assert(declaration.IsKind(SyntaxKind.VariableDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.DeclarationExpression)); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declaredType = FindAnalyzableType(declaration, semanticModel, cancellationToken); if (declaredType == null) { return; } var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var typeStyle = AnalyzeTypeName(declaredType, semanticModel, optionSet, cancellationToken); if (typeStyle.IsStylePreferred && typeStyle.Severity != ReportDiagnostic.Suppress) { // the analyzer would handle this. So we do not. return; } if (!typeStyle.CanConvert()) { return; } context.RegisterRefactoring( new MyCodeAction( Title, c => UpdateDocumentAsync(document, declaredType, c)), declaredType.Span); } private static async Task<SyntaxNode> GetDeclarationAsync(CodeRefactoringContext context) { // We want to provide refactoring for changing the Type of newly introduced variables in following cases: // - DeclarationExpressionSyntax: `"42".TryParseInt32(out var number)` // - VariableDeclarationSyntax: General field / variable declaration statement `var number = 42` // - ForEachStatementSyntax: The variable that gets introduced by foreach `foreach(var number in numbers)` // // In addition to providing the refactoring when the whole node (i.e. the node that introduces the new variable) in question is selected // we also want to enable it when only the type node is selected because this refactoring changes the type. We still have to make sure // we're only working on TypeNodes for in above-mentioned situations. // // For foreach we need to guard against selecting just the expression because it is also of type `TypeSyntax`. var declNode = await context.TryGetRelevantNodeAsync<DeclarationExpressionSyntax>().ConfigureAwait(false); if (declNode != null) return declNode; var variableNode = await context.TryGetRelevantNodeAsync<VariableDeclarationSyntax>().ConfigureAwait(false); if (variableNode != null) return variableNode; // `ref var` is a bit of an interesting construct. 'ref' looks like a modifier, but is actually a // type-syntax. Ensure the user can get the feature anywhere on this construct var type = await context.TryGetRelevantNodeAsync<TypeSyntax>().ConfigureAwait(false); if (type?.Parent is RefTypeSyntax) type = (TypeSyntax)type.Parent; if (type?.Parent is VariableDeclarationSyntax) return type.Parent; var foreachStatement = await context.TryGetRelevantNodeAsync<ForEachStatementSyntax>().ConfigureAwait(false); if (foreachStatement != null) return foreachStatement; var syntaxFacts = context.Document.GetLanguageService<ISyntaxFactsService>(); var typeNode = await context.TryGetRelevantNodeAsync<TypeSyntax>().ConfigureAwait(false); var typeNodeParent = typeNode?.Parent; if (typeNodeParent != null && (typeNodeParent.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.VariableDeclaration) || (typeNodeParent.IsKind(SyntaxKind.ForEachStatement) && !syntaxFacts.IsExpressionOfForeach(typeNode)))) { return typeNodeParent; } return null; } private async Task<Document> UpdateDocumentAsync(Document document, TypeSyntax type, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); await HandleDeclarationAsync(document, editor, type, cancellationToken).ConfigureAwait(false); var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/Test/CodeRefactorings/ErrorCases/CodeRefactoringExceptionInComputeRefactorings.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeRefactoringService.ErrorCases { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Test")] [Shared] [PartNotDiscoverable] internal class ExceptionInCodeActions : CodeRefactoringProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExceptionInCodeActions() { } public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) => throw new Exception($"Exception thrown from ComputeRefactoringsAsync in {nameof(ExceptionInCodeActions)}"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeRefactoringService.ErrorCases { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Test")] [Shared] [PartNotDiscoverable] internal class ExceptionInCodeActions : CodeRefactoringProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExceptionInCodeActions() { } public override Task ComputeRefactoringsAsync(CodeRefactoringContext context) => throw new Exception($"Exception thrown from ComputeRefactoringsAsync in {nameof(ExceptionInCodeActions)}"); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Scripting/Core/ScriptState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// The result of running a script. /// </summary> public abstract class ScriptState { /// <summary> /// The script that ran to produce this result. /// </summary> public Script Script { get; } /// <summary> /// Caught exception originating from the script top-level code. /// </summary> /// <remarks> /// Exceptions are only caught and stored here if the API returning the <see cref="ScriptState"/> is instructed to do so. /// By default they are propagated to the caller of the API. /// </remarks> public Exception Exception { get; } internal ScriptExecutionState ExecutionState { get; } private ImmutableArray<ScriptVariable> _lazyVariables; private IReadOnlyDictionary<string, int> _lazyVariableMap; internal ScriptState(ScriptExecutionState executionState, Script script, Exception exceptionOpt) { Debug.Assert(executionState != null); Debug.Assert(script != null); ExecutionState = executionState; Script = script; Exception = exceptionOpt; } /// <summary> /// The final value produced by running the script. /// </summary> public object ReturnValue => GetReturnValue(); internal abstract object GetReturnValue(); /// <summary> /// Returns variables defined by the scripts in the declaration order. /// </summary> public ImmutableArray<ScriptVariable> Variables { get { if (_lazyVariables == null) { ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables()); } return _lazyVariables; } } /// <summary> /// Returns a script variable of the specified name. /// </summary> /// <remarks> /// If multiple script variables are defined in the script (in distinct submissions) returns the last one. /// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts. /// </remarks> /// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> public ScriptVariable GetVariable(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } int index; return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null; } private ImmutableArray<ScriptVariable> CreateVariables() { var result = ArrayBuilder<ScriptVariable>.GetInstance(); var executionState = ExecutionState; // Don't include the globals object (slot #0) for (int i = 1; i < executionState.SubmissionStateCount; i++) { var state = executionState.GetSubmissionState(i); Debug.Assert(state != null); foreach (var field in state.GetType().GetTypeInfo().DeclaredFields) { // TODO: synthesized fields of submissions shouldn't be public if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_')) { result.Add(new ScriptVariable(state, field)); } } } return result.ToImmutableAndFree(); } private IReadOnlyDictionary<string, int> GetVariableMap() { if (_lazyVariableMap == null) { var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer); for (int i = 0; i < Variables.Length; i++) { map[Variables[i].Name] = i; } _lazyVariableMap = map; } return _lazyVariableMap; } /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<object>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<object>(code, options).RunFromAsync(this, catchException, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<TResult>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<TResult>(code, options).RunFromAsync(this, catchException, cancellationToken); // How do we resolve overloads? We should use the language semantics. // https://github.com/dotnet/roslyn/issues/3720 #if TODO /// <summary> /// Invoke a method declared by the script. /// </summary> public object Invoke(string name, params object[] args) { var func = this.FindMethod(name, args != null ? args.Length : 0); if (func != null) { return func(args); } return null; } private Func<object[], object> FindMethod(string name, int argCount) { for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMethod(type, name, argCount); if (method != null) { return (args) => method.Invoke(sub, args); } } } return null; } private MethodInfo FindMethod(Type type, string name, int argCount) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } /// <summary> /// Create a delegate to a method declared by the script. /// </summary> public TDelegate CreateDelegate<TDelegate>(string name) { var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMatchingMethod(type, name, delegateInvokeMethod); if (method != null) { return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub); } } } return default(TDelegate); } private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod) { var dprms = delegateInvokeMethod.GetParameters(); foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (mi.Name == name) { var prms = mi.GetParameters(); if (prms.Length == dprms.Length) { // TODO: better matching.. return mi; } } } return null; } #endif } public sealed class ScriptState<T> : ScriptState { public new T ReturnValue { get; } internal override object GetReturnValue() => ReturnValue; internal ScriptState(ScriptExecutionState executionState, Script script, T value, Exception exceptionOpt) : base(executionState, script, exceptionOpt) { ReturnValue = 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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Reflection; using System.Collections.Generic; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Scripting { /// <summary> /// The result of running a script. /// </summary> public abstract class ScriptState { /// <summary> /// The script that ran to produce this result. /// </summary> public Script Script { get; } /// <summary> /// Caught exception originating from the script top-level code. /// </summary> /// <remarks> /// Exceptions are only caught and stored here if the API returning the <see cref="ScriptState"/> is instructed to do so. /// By default they are propagated to the caller of the API. /// </remarks> public Exception Exception { get; } internal ScriptExecutionState ExecutionState { get; } private ImmutableArray<ScriptVariable> _lazyVariables; private IReadOnlyDictionary<string, int> _lazyVariableMap; internal ScriptState(ScriptExecutionState executionState, Script script, Exception exceptionOpt) { Debug.Assert(executionState != null); Debug.Assert(script != null); ExecutionState = executionState; Script = script; Exception = exceptionOpt; } /// <summary> /// The final value produced by running the script. /// </summary> public object ReturnValue => GetReturnValue(); internal abstract object GetReturnValue(); /// <summary> /// Returns variables defined by the scripts in the declaration order. /// </summary> public ImmutableArray<ScriptVariable> Variables { get { if (_lazyVariables == null) { ImmutableInterlocked.InterlockedInitialize(ref _lazyVariables, CreateVariables()); } return _lazyVariables; } } /// <summary> /// Returns a script variable of the specified name. /// </summary> /// <remarks> /// If multiple script variables are defined in the script (in distinct submissions) returns the last one. /// Name lookup is case sensitive in C# scripts and case insensitive in VB scripts. /// </remarks> /// <returns><see cref="ScriptVariable"/> or null, if no variable of the specified <paramref name="name"/> is defined in the script.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> public ScriptVariable GetVariable(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } int index; return GetVariableMap().TryGetValue(name, out index) ? Variables[index] : null; } private ImmutableArray<ScriptVariable> CreateVariables() { var result = ArrayBuilder<ScriptVariable>.GetInstance(); var executionState = ExecutionState; // Don't include the globals object (slot #0) for (int i = 1; i < executionState.SubmissionStateCount; i++) { var state = executionState.GetSubmissionState(i); Debug.Assert(state != null); foreach (var field in state.GetType().GetTypeInfo().DeclaredFields) { // TODO: synthesized fields of submissions shouldn't be public if (field.IsPublic && field.Name.Length > 0 && (char.IsLetterOrDigit(field.Name[0]) || field.Name[0] == '_')) { result.Add(new ScriptVariable(state, field)); } } } return result.ToImmutableAndFree(); } private IReadOnlyDictionary<string, int> GetVariableMap() { if (_lazyVariableMap == null) { var map = new Dictionary<string, int>(Script.Compiler.IdentifierComparer); for (int i = 0; i < Variables.Length; i++) { map[Variables[i].Name] = i; } _lazyVariableMap = map; } return _lazyVariableMap; } /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<object>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<object>> ContinueWithAsync(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<object>(code, options).RunFromAsync(this, catchException, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync<TResult>(code, options, null, cancellationToken); /// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task<ScriptState<TResult>> ContinueWithAsync<TResult>(string code, ScriptOptions options = null, Func<Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith<TResult>(code, options).RunFromAsync(this, catchException, cancellationToken); // How do we resolve overloads? We should use the language semantics. // https://github.com/dotnet/roslyn/issues/3720 #if TODO /// <summary> /// Invoke a method declared by the script. /// </summary> public object Invoke(string name, params object[] args) { var func = this.FindMethod(name, args != null ? args.Length : 0); if (func != null) { return func(args); } return null; } private Func<object[], object> FindMethod(string name, int argCount) { for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMethod(type, name, argCount); if (method != null) { return (args) => method.Invoke(sub, args); } } } return null; } private MethodInfo FindMethod(Type type, string name, int argCount) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } /// <summary> /// Create a delegate to a method declared by the script. /// </summary> public TDelegate CreateDelegate<TDelegate>(string name) { var delegateInvokeMethod = typeof(TDelegate).GetMethod("Invoke", BindingFlags.Instance | BindingFlags.Public); for (int i = _executionState.Count - 1; i >= 0; i--) { var sub = _executionState[i]; if (sub != null) { var type = sub.GetType(); var method = FindMatchingMethod(type, name, delegateInvokeMethod); if (method != null) { return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), sub); } } } return default(TDelegate); } private MethodInfo FindMatchingMethod(Type instanceType, string name, MethodInfo delegateInvokeMethod) { var dprms = delegateInvokeMethod.GetParameters(); foreach (var mi in instanceType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (mi.Name == name) { var prms = mi.GetParameters(); if (prms.Length == dprms.Length) { // TODO: better matching.. return mi; } } } return null; } #endif } public sealed class ScriptState<T> : ScriptState { public new T ReturnValue { get; } internal override object GetReturnValue() => ReturnValue; internal ScriptState(ScriptExecutionState executionState, Script script, T value, Exception exceptionOpt) : base(executionState, script, exceptionOpt) { ReturnValue = value; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; private const string CreateNewOnMetadataUpdateAttributeName = "CreateNewOnMetadataUpdateAttribute"; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); protected abstract TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node); /// <summary> /// Returns all symbols associated with an edit and an actual edit kind, which may be different then the specified one. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); protected abstract bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); internal string GetDisplayName(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => FeaturesResources.event_, SymbolKind.Field => GetDisplayName((IFieldSymbol)symbol), SymbolKind.Method => GetDisplayName((IMethodSymbol)symbol), SymbolKind.NamedType => GetDisplayName((INamedTypeSymbol)symbol), SymbolKind.Parameter => FeaturesResources.parameter, SymbolKind.Property => GetDisplayName((IPropertySymbol)symbol), SymbolKind.TypeParameter => FeaturesResources.type_parameter, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind) }; internal virtual string GetDisplayName(IPropertySymbol symbol) => FeaturesResources.property_; internal virtual string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Class => FeaturesResources.class_, TypeKind.Interface => FeaturesResources.interface_, TypeKind.Delegate => FeaturesResources.delegate_, TypeKind.Enum => FeaturesResources.enum_, TypeKind.TypeParameter => FeaturesResources.type_parameter, _ => FeaturesResources.type, }; internal virtual string GetDisplayName(IFieldSymbol symbol) => symbol.IsConst ? ((symbol.ContainingType.TypeKind == TypeKind.Enum) ? FeaturesResources.enum_value : FeaturesResources.const_field) : FeaturesResources.field; internal virtual string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => FeaturesResources.constructor, MethodKind.PropertyGet or MethodKind.PropertySet => FeaturesResources.property_accessor, MethodKind.EventAdd or MethodKind.EventRaise or MethodKind.EventRemove => FeaturesResources.event_accessor, MethodKind.BuiltinOperator or MethodKind.UserDefinedOperator or MethodKind.Conversion => FeaturesResources.operator_, _ => FeaturesResources.method, }; /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns the declaration of /// - a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// - a method, an indexer or a type (delegate) if the <paramref name="node"/> is a parameter, /// - a method or an type if the <paramref name="node"/> is a type parameter. /// </summary> internal abstract bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, AsyncLazy<ActiveStatementsMap> lazyOldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, AsyncLazy<EditAndContinueCapabilities> lazyCapabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } var capabilities = await lazyCapabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); var oldActiveStatementMap = await lazyOldActiveStatementMap.GetValueAsync(cancellationToken).ConfigureAwait(false); // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // We are in break state when there are no active statements. var inBreakState = !oldActiveStatementMap.IsEmpty; // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, inBreakState, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // When a method is moved to a different declaration and its parameters are changed at the same time // the new method symbol key will not resolve to the old one since the parameters are different. // As a result we will report separate delete and insert rude edits. // // For delegates, however, the symbol key will resolve to the old type so we need to report // rude edits here. if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldDelegateInvoke } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvoke }) { if (!ParameterTypesEquivalent(oldDelegateInvoke.Parameters, newDelegateInvoke.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingParameterTypes, newSymbol, newNode, cancellationToken); } } } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, GetDiagnosticSpan(newDeclaration, EditKind.Update)); _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, CancellationToken cancellationToken) { var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } triviaEdits.Add((oldNode, newNode, rudeEditSpan)); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode, segment.newNode.Span)); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } // Ignore tuple element changes, nullability and dynamic. These type changes do not affect runtime type. // They only affect custom attributes emitted on the members - all runtimes are expected to accept // custom attribute updates in metadata deltas, even if they do not have any observable effect. private static readonly SymbolEquivalenceComparer s_runtimeSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false, ignoreNullableAnnotations: true); private static readonly SymbolEquivalenceComparer s_exactSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: true, ignoreNullableAnnotations: false); protected static bool SymbolsEquivalent(ISymbol oldSymbol, ISymbol newSymbol) => s_exactSymbolEqualityComparer.Equals(oldSymbol, newSymbol); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) => ParameterTypesEquivalent(oldParameters, newParameters, exact: false) && s_runtimeSymbolEqualityComparer.Equals(oldReturnType, newReturnType); // TODO: should check ref, ref readonly, custom mods protected static bool ParameterTypesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ImmutableArray<IParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => ParameterTypesEquivalent(oldParameter, newParameter, exact)); protected static bool CustomModifiersEquivalent(CustomModifier oldModifier, CustomModifier newModifier, bool exact) => oldModifier.IsOptional == newModifier.IsOptional && TypesEquivalent(oldModifier.Modifier, newModifier.Modifier, exact); protected static bool CustomModifiersEquivalent(ImmutableArray<CustomModifier> oldModifiers, ImmutableArray<CustomModifier> newModifiers, bool exact) => oldModifiers.SequenceEqual(newModifiers, exact, (x, y, exact) => CustomModifiersEquivalent(x, y, exact)); protected static bool ReturnTypesEquivalent(IMethodSymbol oldMethod, IMethodSymbol newMethod, bool exact) => oldMethod.ReturnsByRef == newMethod.ReturnsByRef && oldMethod.ReturnsByRefReadonly == newMethod.ReturnsByRefReadonly && CustomModifiersEquivalent(oldMethod.ReturnTypeCustomModifiers, newMethod.ReturnTypeCustomModifiers, exact) && CustomModifiersEquivalent(oldMethod.RefCustomModifiers, newMethod.RefCustomModifiers, exact) && TypesEquivalent(oldMethod.ReturnType, newMethod.ReturnType, exact); protected static bool ReturnTypesEquivalent(IPropertySymbol oldProperty, IPropertySymbol newProperty, bool exact) => oldProperty.ReturnsByRef == newProperty.ReturnsByRef && oldProperty.ReturnsByRefReadonly == newProperty.ReturnsByRefReadonly && CustomModifiersEquivalent(oldProperty.TypeCustomModifiers, newProperty.TypeCustomModifiers, exact) && CustomModifiersEquivalent(oldProperty.RefCustomModifiers, newProperty.RefCustomModifiers, exact) && TypesEquivalent(oldProperty.Type, newProperty.Type, exact); protected static bool ReturnTypesEquivalent(IEventSymbol oldEvent, IEventSymbol newEvent, bool exact) => TypesEquivalent(oldEvent.Type, newEvent.Type, exact); // Note: SignatureTypeEquivalenceComparer compares dynamic and object the same. protected static bool TypesEquivalent(ITypeSymbol? oldType, ITypeSymbol? newType, bool exact) => (exact ? s_exactSymbolEqualityComparer : (IEqualityComparer<ITypeSymbol?>)s_runtimeSymbolEqualityComparer.SignatureTypeEquivalenceComparer).Equals(oldType, newType); protected static bool TypesEquivalent<T>(ImmutableArray<T> oldTypes, ImmutableArray<T> newTypes, bool exact) where T : ITypeSymbol => oldTypes.SequenceEqual(newTypes, exact, (x, y, exact) => TypesEquivalent(x, y, exact)); protected static bool ParameterTypesEquivalent(IParameterSymbol oldParameter, IParameterSymbol newParameter, bool exact) => (exact ? s_exactSymbolEqualityComparer : s_runtimeSymbolEqualityComparer).ParameterEquivalenceComparer.Equals(oldParameter, newParameter); protected static bool TypeParameterConstraintsEquivalent(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, bool exact) => TypesEquivalent(oldParameter.ConstraintTypes, newParameter.ConstraintTypes, exact) && oldParameter.HasReferenceTypeConstraint == newParameter.HasReferenceTypeConstraint && oldParameter.HasValueTypeConstraint == newParameter.HasValueTypeConstraint && oldParameter.HasConstructorConstraint == newParameter.HasConstructorConstraint && oldParameter.HasNotNullConstraint == newParameter.HasNotNullConstraint && oldParameter.HasUnmanagedTypeConstraint == newParameter.HasUnmanagedTypeConstraint && oldParameter.Variance == newParameter.Variance; protected static bool TypeParametersEquivalent(ImmutableArray<ITypeParameterSymbol> oldParameters, ImmutableArray<ITypeParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => oldParameter.Name == newParameter.Name && TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact)); protected static bool BaseTypesEquivalent(INamedTypeSymbol oldType, INamedTypeSymbol newType, bool exact) => TypesEquivalent(oldType.BaseType, newType.BaseType, exact) && TypesEquivalent(oldType.AllInterfaces, newType.AllInterfaces, exact); protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, bool inBreakState, CancellationToken cancellationToken) { Debug.Assert(inBreakState || newActiveStatementSpans.IsEmpty); if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbolEdits in GetSymbolEdits(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol, syntacticEditKind) = symbolEdits; var symbol = newSymbol ?? oldSymbol; Contract.ThrowIfNull(symbol); if (!processedSymbols.Add(symbol)) { continue; } var symbolKey = SymbolKey.Create(symbol, cancellationToken); // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol ??= symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newSymbol ??= symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); // The syntax change implies an update of the associated symbol but the old/new symbol does not actually exist. // Treat the edit as Insert/Delete. This may happen e.g. when all C# global statements are removed, the first one is added or they are moved to another file. if (syntacticEditKind == EditKind.Update) { if (oldSymbol == null || oldDeclaration != null && oldDeclaration.SyntaxTree != oldModel?.SyntaxTree) { syntacticEditKind = EditKind.Insert; } else if (newSymbol == null || newDeclaration != null && newDeclaration.SyntaxTree != newModel.SyntaxTree) { syntacticEditKind = EditKind.Delete; } } if (!inBreakState) { // Delete/insert/update edit of a member of a reloadable type (including nested types) results in Replace edit of the containing type. // If a Delete edit is part of delete-insert operation (member moved to a different partial type declaration or to a different file) // skip producing Replace semantic edit for this Delete edit as one will be reported by the corresponding Insert edit. var oldContainingType = oldSymbol?.ContainingType; var newContainingType = newSymbol?.ContainingType; var containingType = newContainingType ?? oldContainingType; if (containingType != null && (syntacticEditKind != EditKind.Delete || newSymbol == null)) { var containingTypeSymbolKey = SymbolKey.Create(containingType, cancellationToken); oldContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldContainingType != null && newContainingType != null && IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } } var oldType = oldSymbol as INamedTypeSymbol; var newType = newSymbol as INamedTypeSymbol; // Deleting a reloadable type is a rude edit, reported the same as for non-reloadable. // Adding a reloadable type is a standard type addition (TODO: unless added to a reloadable type?). // Making reloadable attribute non-reloadable results in a new version of the type that is // not reloadable but does not update the old version in-place. if (syntacticEditKind != EditKind.Delete && oldType != null && newType != null && IsReloadable(oldType)) { if (symbol == newType || processedSymbols.Add(newType)) { if (oldType.Name != newType.Name) { // https://github.com/dotnet/roslyn/issues/54886 ReportUpdateRudeEdit(diagnostics, RudeEditKind.Renamed, newType, newDeclaration, cancellationToken); } else if (oldType.Arity != newType.Arity) { // https://github.com/dotnet/roslyn/issues/54881 ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newType, newDeclaration, cancellationToken); } else if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newType, newDeclaration, cancellationToken); } else { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, symbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldType, newType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } continue; } } switch (syntacticEditKind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, RudeEditKind.DeleteActiveStatement, cancellationToken); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits, cancellationToken); } } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); // If we got here for a global statement then the actual edit is a delete of the synthesized Main method if (IsGlobalMain(oldSymbol)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.Delete, diagnosticSpan, edit.OldNode, new[] { GetDisplayName(edit.OldNode, EditKind.Delete) })); continue; } // If the associated member declaration (accessor -> property/indexer/event, parameter -> method) has also been deleted skip // the delete of the symbol as it will be deleted by the delete of the associated member. // // Associated member declarations must be in the same document as the symbol, so we don't need to resolve their symbol. // In some cases the symbol even can't be resolved unambiguously. Consider e.g. resolving a method with its parameter deleted - // we wouldn't know which overload to resolve to. if (TryGetAssociatedMemberDeclaration(oldDeclaration, out var oldAssociatedMemberDeclaration)) { if (HasEdit(editMap, oldAssociatedMemberDeclaration, EditKind.Delete)) { continue; } } else if (oldSymbol.ContainingType != null) { // Check if the symbol being deleted is a member of a type that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var containingSymbolKey = SymbolKey.Create(oldSymbol.ContainingType, cancellationToken); var newContainingSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainingSymbol == null) { continue; } } // deleting symbol is not allowed diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } editKind = SemanticEditKind.Update; } } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newBody = TryGetDeclarationBody(newDeclaration); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); if (isNewConstructorWithMemberInitializers || isDeclarationWithInitializer || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } else { editKind = SemanticEditKind.Update; } } else if (TryGetAssociatedMemberDeclaration(newDeclaration, out var newAssociatedMemberDeclaration) && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. continue; } else if (newSymbol is IParameterSymbol || newSymbol is ITypeParameterSymbol) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); continue; } else if (newContainingType != null && !IsGlobalMain(newSymbol)) { // The edit actually adds a new symbol into an existing or a new type. var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } else { // adds a new top-level type, or a global statement where none existed before, which is // therefore inserting the <Program>$ type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol || IsGlobalMain(newSymbol)); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); editKind = SemanticEditKind.Update; syntaxMap = null; // Partial type declarations and their type parameters. if (oldSymbol.DeclaringSyntaxReferences.Length != 1 && newSymbol.DeclaringSyntaxReferences.Length != 1) { break; } Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { Contract.ThrowIfNull(oldSymbol); AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol or IEventSymbol or IParameterSymbol or ITypeParameterSymbol) { continue; } } semanticEdits.Add(new SemanticEditInfo(editKind, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } foreach (var (oldEditNode, newEditNode, diagnosticSpan) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol, editKind) in GetSymbolEdits(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; Contract.ThrowIfNull(oldContainingType); Contract.ThrowIfNull(newContainingType); if (IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { var containingTypeSymbolKey = SymbolKey.Create(oldContainingType, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, diagnosticSpan); // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericTypeTriviaUpdate; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, diagnosticSpan, newEditNode, new[] { GetDisplayName(newEditNode) })); continue; } var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.Distinct(SemanticEditInfoComparer.Instance).ToImmutableArray(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private static bool IsReloadable(INamedTypeSymbol type) { var current = type; while (current != null) { foreach (var attributeData in current.GetAttributes()) { // We assume that the attribute System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute, if it exists, is well formed. // If not an error will be reported during EnC delta emit. if (attributeData.AttributeClass is { Name: CreateNewOnMetadataUpdateAttributeName, ContainingNamespace: { Name: "CompilerServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System" } } } }) { return true; } } current = current.BaseType; } return false; } private sealed class SemanticEditInfoComparer : IEqualityComparer<SemanticEditInfo> { public static SemanticEditInfoComparer Instance = new(); private static readonly IEqualityComparer<SymbolKey> s_symbolKeyComparer = SymbolKey.GetComparer(); public bool Equals([AllowNull] SemanticEditInfo x, [AllowNull] SemanticEditInfo y) => s_symbolKeyComparer.Equals(x.Symbol, y.Symbol); public int GetHashCode([DisallowNull] SemanticEditInfo obj) => obj.Symbol.GetHashCode(); } private void ReportUpdatedSymbolDeclarationRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasGeneratedAttributeChange, out bool hasGeneratedReturnTypeAttributeChange, out bool hasParameterRename, CancellationToken cancellationToken) { var rudeEdit = RudeEditKind.None; hasGeneratedAttributeChange = false; hasGeneratedReturnTypeAttributeChange = false; hasParameterRename = false; if (oldSymbol.Kind != newSymbol.Kind) { rudeEdit = (oldSymbol.Kind == SymbolKind.Field || newSymbol.Kind == SymbolKind.Field) ? RudeEditKind.FieldKindUpdate : RudeEditKind.Update; } else if (oldSymbol.Name != newSymbol.Name) { if (oldSymbol is IParameterSymbol && newSymbol is IParameterSymbol) { if (capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters)) { hasParameterRename = true; } else { rudeEdit = RudeEditKind.RenamingNotSupportedByRuntime; } } else { rudeEdit = RudeEditKind.Renamed; } // specialize rude edit for accessors and conversion operators: if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.AssociatedSymbol != null && newMethod.AssociatedSymbol != null) { if (oldMethod.MethodKind != newMethod.MethodKind) { rudeEdit = RudeEditKind.AccessorKindUpdate; } else { // rude edit will be reported by the associated symbol rudeEdit = RudeEditKind.None; } } else if (oldMethod.MethodKind == MethodKind.Conversion) { rudeEdit = RudeEditKind.ModifiersUpdate; } } } if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { rudeEdit = RudeEditKind.ChangingAccessibility; } if (oldSymbol.IsStatic != newSymbol.IsStatic || oldSymbol.IsVirtual != newSymbol.IsVirtual || oldSymbol.IsAbstract != newSymbol.IsAbstract || oldSymbol.IsOverride != newSymbol.IsOverride || oldSymbol.IsExtern != newSymbol.IsExtern) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (oldSymbol is IFieldSymbol oldField && newSymbol is IFieldSymbol newField) { if (oldField.IsConst != newField.IsConst || oldField.IsReadOnly != newField.IsReadOnly || oldField.IsVolatile != newField.IsVolatile) { rudeEdit = RudeEditKind.ModifiersUpdate; } // Report rude edit for updating const fields and values of enums. // The latter is only reported whne the enum underlying type does not change to avoid cascading rude edits. if (oldField.IsConst && newField.IsConst && !Equals(oldField.ConstantValue, newField.ConstantValue) && TypesEquivalent(oldField.ContainingType.EnumUnderlyingType, newField.ContainingType.EnumUnderlyingType, exact: false)) { rudeEdit = RudeEditKind.InitializerUpdate; } if (oldField.FixedSize != newField.FixedSize) { rudeEdit = RudeEditKind.FixedSizeFieldUpdate; } AnalyzeType(oldField.Type, newField.Type, ref rudeEdit, ref hasGeneratedAttributeChange); } else if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.IsReadOnly != newMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (oldMethod.IsInitOnly != newMethod.IsInitOnly) { rudeEdit = RudeEditKind.AccessorKindUpdate; } // Consider: Generalize to compare P/Invokes regardless of how they are defined (using attribute or Declare) if (oldMethod.MethodKind == MethodKind.DeclareMethod || newMethod.MethodKind == MethodKind.DeclareMethod) { var oldImportData = oldMethod.GetDllImportData(); var newImportData = newMethod.GetDllImportData(); if (oldImportData != null && newImportData != null) { // Declare method syntax can't change these. Debug.Assert(oldImportData.BestFitMapping == newImportData.BestFitMapping || oldImportData.CallingConvention == newImportData.CallingConvention || oldImportData.ExactSpelling == newImportData.ExactSpelling || oldImportData.SetLastError == newImportData.SetLastError || oldImportData.ThrowOnUnmappableCharacter == newImportData.ThrowOnUnmappableCharacter); if (oldImportData.ModuleName != newImportData.ModuleName) { rudeEdit = RudeEditKind.DeclareLibraryUpdate; } else if (oldImportData.EntryPointName != newImportData.EntryPointName) { rudeEdit = RudeEditKind.DeclareAliasUpdate; } else if (oldImportData.CharacterSet != newImportData.CharacterSet) { rudeEdit = RudeEditKind.ModifiersUpdate; } } else if (oldImportData is null != newImportData is null) { rudeEdit = RudeEditKind.ModifiersUpdate; } } // VB implements clause if (!oldMethod.ExplicitInterfaceImplementations.SequenceEqual(newMethod.ExplicitInterfaceImplementations, (x, y) => SymbolsEquivalent(x, y))) { rudeEdit = RudeEditKind.ImplementsClauseUpdate; } // VB handles clause if (!AreHandledEventsEqual(oldMethod, newMethod)) { rudeEdit = RudeEditKind.HandlesClauseUpdate; } // Check return type - do not report for accessors, their containing symbol will report the rude edits and attribute updates. if (rudeEdit == RudeEditKind.None && oldMethod.AssociatedSymbol == null && newMethod.AssociatedSymbol == null) { AnalyzeReturnType(oldMethod, newMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is INamedTypeSymbol oldType && newSymbol is INamedTypeSymbol newType) { if (oldType.TypeKind != newType.TypeKind || oldType.IsRecord != newType.IsRecord) // TODO: https://github.com/dotnet/roslyn/issues/51874 { rudeEdit = RudeEditKind.TypeKindUpdate; } else if (oldType.IsRefLikeType != newType.IsRefLikeType || oldType.IsReadOnly != newType.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (rudeEdit == RudeEditKind.None) { AnalyzeBaseTypes(oldType, newType, ref rudeEdit, ref hasGeneratedAttributeChange); if (oldType.DelegateInvokeMethod != null) { Contract.ThrowIfNull(newType.DelegateInvokeMethod); AnalyzeReturnType(oldType.DelegateInvokeMethod, newType.DelegateInvokeMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } } else if (oldSymbol is IPropertySymbol oldProperty && newSymbol is IPropertySymbol newProperty) { AnalyzeReturnType(oldProperty, newProperty, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } else if (oldSymbol is IEventSymbol oldEvent && newSymbol is IEventSymbol newEvent) { // "readonly" modifier can only be applied on the event itself, not on its accessors. if (oldEvent.AddMethod != null && newEvent.AddMethod != null && oldEvent.AddMethod.IsReadOnly != newEvent.AddMethod.IsReadOnly || oldEvent.RemoveMethod != null && newEvent.RemoveMethod != null && oldEvent.RemoveMethod.IsReadOnly != newEvent.RemoveMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } else { AnalyzeReturnType(oldEvent, newEvent, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is IParameterSymbol oldParameter && newSymbol is IParameterSymbol newParameter) { if (oldParameter.RefKind != newParameter.RefKind || oldParameter.IsParams != newParameter.IsParams || IsExtensionMethodThisParameter(oldParameter) != IsExtensionMethodThisParameter(newParameter)) { rudeEdit = RudeEditKind.ModifiersUpdate; } else if (oldParameter.HasExplicitDefaultValue != newParameter.HasExplicitDefaultValue || oldParameter.HasExplicitDefaultValue && !Equals(oldParameter.ExplicitDefaultValue, newParameter.ExplicitDefaultValue)) { rudeEdit = RudeEditKind.InitializerUpdate; } else { AnalyzeParameterType(oldParameter, newParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } } else if (oldSymbol is ITypeParameterSymbol oldTypeParameter && newSymbol is ITypeParameterSymbol newTypeParameter) { AnalyzeTypeParameter(oldTypeParameter, newTypeParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } // Do not report modifier update if type kind changed. if (rudeEdit == RudeEditKind.None && oldSymbol.IsSealed != newSymbol.IsSealed) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (rudeEdit != RudeEditKind.None) { // so we'll just use the last global statement in the file ReportUpdateRudeEdit(diagnostics, rudeEdit, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); } } private static void AnalyzeType(ITypeSymbol oldType, ITypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange, RudeEditKind rudeEditKind = RudeEditKind.TypeUpdate) { if (!TypesEquivalent(oldType, newType, exact: true)) { if (TypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = rudeEditKind; } } } private static void AnalyzeBaseTypes(INamedTypeSymbol oldType, INamedTypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (oldType.EnumUnderlyingType != null && newType.EnumUnderlyingType != null) { if (!TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: true)) { if (TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.EnumUnderlyingTypeUpdate; } } } else if (!BaseTypesEquivalent(oldType, newType, exact: true)) { if (BaseTypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.BaseTypeOrInterfaceUpdate; } } } private static void AnalyzeParameterType(IParameterSymbol oldParameter, IParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!ParameterTypesEquivalent(oldParameter, newParameter, exact: true)) { if (ParameterTypesEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeTypeParameter(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: true)) { if (TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = (oldParameter.Variance != newParameter.Variance) ? RudeEditKind.VarianceUpdate : RudeEditKind.ChangingConstraints; } } } private static void AnalyzeReturnType(IMethodSymbol oldMethod, IMethodSymbol newMethod, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldMethod, newMethod, exact: true)) { if (ReturnTypesEquivalent(oldMethod, newMethod, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else if (IsGlobalMain(oldMethod) || IsGlobalMain(newMethod)) { rudeEdit = RudeEditKind.ChangeImplicitMainReturnType; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IEventSymbol oldEvent, IEventSymbol newEvent, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldEvent, newEvent, exact: true)) { if (ReturnTypesEquivalent(oldEvent, newEvent, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IPropertySymbol oldProperty, IPropertySymbol newProperty, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldProperty, newProperty, exact: true)) { if (ReturnTypesEquivalent(oldProperty, newProperty, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static bool IsExtensionMethodThisParameter(IParameterSymbol parameter) => parameter is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } }; private void AnalyzeSymbolUpdate( ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, Match<SyntaxNode> topMatch, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo> semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { // TODO: fails in VB on delegate parameter https://github.com/dotnet/roslyn/issues/53337 // Contract.ThrowIfFalse(newSymbol.IsImplicitlyDeclared == newDeclaration is null); ReportCustomAttributeRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasAttributeChange, out var hasReturnTypeAttributeChange, cancellationToken); ReportUpdatedSymbolDeclarationRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasGeneratedAttributeChange, out var hasGeneratedReturnTypeAttributeChange, out var hasParameterRename, cancellationToken); hasAttributeChange |= hasGeneratedAttributeChange; hasReturnTypeAttributeChange |= hasGeneratedReturnTypeAttributeChange; if (hasParameterRename) { Debug.Assert(newSymbol is IParameterSymbol); AddParameterUpdateSemanticEdit(semanticEdits, (IParameterSymbol)newSymbol, syntaxMap, cancellationToken); } else if (hasAttributeChange || hasReturnTypeAttributeChange) { AddCustomAttributeSemanticEdits(semanticEdits, oldSymbol, newSymbol, topMatch, syntaxMap, hasAttributeChange, hasReturnTypeAttributeChange, cancellationToken); } // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod) || InGenericContext(newSymbol, out _)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodUpdate : RudeEditKind.GenericTypeUpdate; ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static void AddCustomAttributeSemanticEdits( ArrayBuilder<SemanticEditInfo> semanticEdits, ISymbol oldSymbol, ISymbol newSymbol, Match<SyntaxNode> topMatch, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool hasAttributeChange, bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvokeMethod } newDelegateType) { if (hasAttributeChange) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateType, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } if (hasReturnTypeAttributeChange) { // attributes applied on return type of a delegate are applied to both Invoke and BeginInvoke methods semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); AddDelegateBeginInvokeEdit(semanticEdits, newDelegateType, syntaxMap, cancellationToken); } } else if (newSymbol is INamedTypeSymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? symbolKey : null)); } else if (newSymbol is ITypeParameterSymbol) { var containingTypeSymbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, containingTypeSymbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol.ContainingSymbol, newSymbol.ContainingSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else if (newSymbol is IFieldSymbol or IPropertySymbol or IEventSymbol) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is IParameterSymbol newParameterSymbol) { AddParameterUpdateSemanticEdit(semanticEdits, newParameterSymbol, syntaxMap, cancellationToken); } } private static void AddParameterUpdateSemanticEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, IParameterSymbol newParameterSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { var newContainingSymbol = newParameterSymbol.ContainingSymbol; semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newContainingSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); // attributes applied on parameters of a delegate are applied to both Invoke and BeginInvoke methods if (newContainingSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: TypeKind.Delegate } newContainingDelegateType) { AddDelegateBeginInvokeEdit(semanticEdits, newContainingDelegateType, syntaxMap, cancellationToken); } } private static void AddDelegateBeginInvokeEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, INamedTypeSymbol delegateType, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(semanticEdits != null); var beginInvokeMethod = delegateType.GetMembers("BeginInvoke").FirstOrDefault(); if (beginInvokeMethod != null) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(beginInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } } private void ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasAttributeChange, out bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. hasAttributeChange = ReportCustomAttributeRudeEdits(diagnostics, oldSymbol.GetAttributes(), newSymbol.GetAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); hasReturnTypeAttributeChange = false; if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } else if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldInvokeMethod } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newInvokeMethod }) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldInvokeMethod.GetReturnTypeAttributes(), newInvokeMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } } private bool ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingAttributesNotSupportedByRuntime, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits, CancellationToken cancellationToken) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, Compilation newCompilation, RudeEditKind rudeEditKind, CancellationToken cancellationToken) { var newNode = GetDeleteRudeEditDiagnosticNode(oldSymbol, newCompilation, cancellationToken); diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Delete), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldSymbol), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol newSymbol, SyntaxNode? newNode, CancellationToken cancellationToken) { var node = newNode ?? GetRudeEditDiagnosticNode(newSymbol, cancellationToken); var span = (rudeEdit == RudeEditKind.ChangeImplicitMainReturnType) ? GetGlobalStatementDiagnosticSpan(node) : GetDiagnosticSpan(node, EditKind.Update); var arguments = rudeEdit switch { RudeEditKind.TypeKindUpdate or RudeEditKind.ChangeImplicitMainReturnType or RudeEditKind.GenericMethodUpdate or RudeEditKind.GenericTypeUpdate => Array.Empty<string>(), RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime => new[] { CreateNewOnMetadataUpdateAttributeName }, _ => new[] { GetDisplayName(newSymbol) } }; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, span, node, arguments)); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, CancellationToken cancellationToken) { if (newSymbol.IsImplicitlyDeclared) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, rudeEdit, cancellationToken); } else { ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static SyntaxNode GetRudeEditDiagnosticNode(ISymbol symbol, CancellationToken cancellationToken) { var container = symbol; while (container != null) { if (container.DeclaringSyntaxReferences.Length > 0) { return container.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); } container = container.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } private static SyntaxNode GetDeleteRudeEditDiagnosticNode(ISymbol oldSymbol, Compilation newCompilation, CancellationToken cancellationToken) { var oldContainer = oldSymbol.ContainingSymbol; while (oldContainer != null) { var containerKey = SymbolKey.Create(oldContainer, cancellationToken); var newContainer = containerKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainer != null) { return GetRudeEditDiagnosticNode(newContainer, cancellationToken); } oldContainer = oldContainer.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, Compilation newCompilation, IReadOnlySet<ISymbol> processedSymbols, EditAndContinueCapabilities capabilities, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); var isPartialEdit = IsPartialEdit(oldType, newType, oldSyntaxTree, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; SyntaxNode? newDeclaration = null; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Implicit record constructors are represented by the record declaration itself. // https://github.com/dotnet/roslyn/issues/54403 var isPrimaryRecordConstructor = IsRecordDeclaration(newDeclaration); // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!isPrimaryRecordConstructor && !IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!isPrimaryRecordConstructor && !anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, take the slow path. if (!isPrimaryRecordConstructor && topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfFalse(oldCtor is IMethodSymbol { MethodKind: MethodKind.Constructor or MethodKind.StaticConstructor }); } else if (!isPrimaryRecordConstructor && newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name must match for symbol matching to work // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 if (oldCtor != null && !isPrimaryRecordConstructor && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { AnalyzeSymbolUpdate(oldCtor, newCtor, newDeclaration, newCompilation, topMatch, capabilities, diagnostics, semanticEdits, syntaxMapToUse, cancellationToken); semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } private static bool IsPartialEdit(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree) { // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; return oldSymbol?.Kind == SymbolKind.NamedType && oldSymbol.DeclaringSyntaxReferences.Length > 1 && oldSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newSymbol?.Kind == SymbolKind.NamedType && newSymbol.DeclaringSyntaxReferences.Length > 1 && newSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(diagnostics, oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } using var oldLambdaBodyEnumerator = GetLambdaBodies(oldMemberBody).GetEnumerator(); using var newLambdaBodyEnumerator = GetLambdaBodies(newMemberBody).GetEnumerator(); var oldHasLambdas = oldLambdaBodyEnumerator.MoveNext(); var newHasLambdas = newLambdaBodyEnumerator.MoveNext(); // Exit early if there are no lambdas in the method to avoid expensive data flow analysis: if (!oldHasLambdas && !newHasLambdas) { return; } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } using var _1 = ArrayBuilder<int>.GetInstance(newCaptures.Length, fillWithValue: 0, out var reverseCapturesMap); // { new capture index -> new closure scope or null for "this" } using var _2 = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, fillWithValue: null, out var newCapturesToClosureScopes); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } using var _3 = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, fillWithValue: null, out var oldCapturesToClosureScopes); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _11 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _12 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); var newHasLambdaBodies = newHasLambdas; while (newHasLambdaBodies) { var (newLambda, newLambdaBody1, newLambdaBody2) = newLambdaBodyEnumerator.Current; if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } newHasLambdaBodies = newLambdaBodyEnumerator.MoveNext(); } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. var oldHasMoreLambdas = oldHasLambdas; while (oldHasMoreLambdas) { var (oldLambda, oldLambdaBody1, oldLambdaBody2) = oldLambdaBodyEnumerator.Current; if (!map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } oldHasMoreLambdas = oldLambdaBodyEnumerator.MoveNext(); } syntaxMapRequired = newHasLambdas; } private IEnumerable<(SyntaxNode lambda, SyntaxNode lambdaBody1, SyntaxNode? lambdaBody2)> GetLambdaBodies(SyntaxNode body) { foreach (var node in body.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(node, out var body1, out var body2)) { yield return (node, body1, body2); } } } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!TypesEquivalent(oldTypeOpt, newTypeOpt, exact: false)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } private void ReportLambdaSignatureRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, out bool hasSignatureErrors, CancellationToken cancellationToken) { hasSignatureErrors = false; var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { return; } if (IsLocalFunction(oldLambda) != IsLocalFunction(newLambda)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.SwitchBetweenLambdaAndLocalFunction, newLambda); hasSignatureErrors = true; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); // signature validation: if (!ParameterTypesEquivalent(oldLambdaSymbol.Parameters, newLambdaSymbol.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaParameters, newLambda); hasSignatureErrors = true; } else if (!ReturnTypesEquivalent(oldLambdaSymbol, newLambdaSymbol, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaReturnType, newLambda); hasSignatureErrors = true; } else if (!TypeParametersEquivalent(oldLambdaSymbol.TypeParameters, newLambdaSymbol.TypeParameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newLambda); hasSignatureErrors = true; } if (hasSignatureErrors) { return; } // custom attributes ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol, newLambdaSymbol, newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); for (var i = 0; i < oldLambdaSymbol.Parameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.Parameters[i], newLambdaSymbol.Parameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } for (var i = 0; i < oldLambdaSymbol.TypeParameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.TypeParameters[i], newLambdaSymbol.TypeParameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #pragma warning disable format private static bool IsGlobalMain(ISymbol symbol) => symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType.Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; #pragma warning restore format private static bool InGenericContext(ISymbol symbol, out bool isGenericMethod) { var current = symbol; while (true) { if (current is IMethodSymbol { Arity: > 0 }) { isGenericMethod = true; return true; } if (current is INamedTypeSymbol { Arity: > 0 }) { isGenericMethod = false; return true; } current = current.ContainingSymbol; if (current == null) { isGenericMethod = false; return false; } } } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; private const string CreateNewOnMetadataUpdateAttributeName = "CreateNewOnMetadataUpdateAttribute"; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); protected abstract TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node); /// <summary> /// Returns all symbols associated with an edit and an actual edit kind, which may be different then the specified one. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); protected abstract bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); internal string GetDisplayName(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => FeaturesResources.event_, SymbolKind.Field => GetDisplayName((IFieldSymbol)symbol), SymbolKind.Method => GetDisplayName((IMethodSymbol)symbol), SymbolKind.NamedType => GetDisplayName((INamedTypeSymbol)symbol), SymbolKind.Parameter => FeaturesResources.parameter, SymbolKind.Property => GetDisplayName((IPropertySymbol)symbol), SymbolKind.TypeParameter => FeaturesResources.type_parameter, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind) }; internal virtual string GetDisplayName(IPropertySymbol symbol) => FeaturesResources.property_; internal virtual string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Class => FeaturesResources.class_, TypeKind.Interface => FeaturesResources.interface_, TypeKind.Delegate => FeaturesResources.delegate_, TypeKind.Enum => FeaturesResources.enum_, TypeKind.TypeParameter => FeaturesResources.type_parameter, _ => FeaturesResources.type, }; internal virtual string GetDisplayName(IFieldSymbol symbol) => symbol.IsConst ? ((symbol.ContainingType.TypeKind == TypeKind.Enum) ? FeaturesResources.enum_value : FeaturesResources.const_field) : FeaturesResources.field; internal virtual string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => FeaturesResources.constructor, MethodKind.PropertyGet or MethodKind.PropertySet => FeaturesResources.property_accessor, MethodKind.EventAdd or MethodKind.EventRaise or MethodKind.EventRemove => FeaturesResources.event_accessor, MethodKind.BuiltinOperator or MethodKind.UserDefinedOperator or MethodKind.Conversion => FeaturesResources.operator_, _ => FeaturesResources.method, }; /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns the declaration of /// - a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// - a method, an indexer or a type (delegate) if the <paramref name="node"/> is a parameter, /// - a method or an type if the <paramref name="node"/> is a type parameter. /// </summary> internal abstract bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, AsyncLazy<ActiveStatementsMap> lazyOldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, AsyncLazy<EditAndContinueCapabilities> lazyCapabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } var capabilities = await lazyCapabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); var oldActiveStatementMap = await lazyOldActiveStatementMap.GetValueAsync(cancellationToken).ConfigureAwait(false); // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // We are in break state when there are no active statements. var inBreakState = !oldActiveStatementMap.IsEmpty; // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, inBreakState, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // When a method is moved to a different declaration and its parameters are changed at the same time // the new method symbol key will not resolve to the old one since the parameters are different. // As a result we will report separate delete and insert rude edits. // // For delegates, however, the symbol key will resolve to the old type so we need to report // rude edits here. if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldDelegateInvoke } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvoke }) { if (!ParameterTypesEquivalent(oldDelegateInvoke.Parameters, newDelegateInvoke.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingParameterTypes, newSymbol, newNode, cancellationToken); } } } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, GetDiagnosticSpan(newDeclaration, EditKind.Update)); _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, CancellationToken cancellationToken) { var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } triviaEdits.Add((oldNode, newNode, rudeEditSpan)); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode, segment.newNode.Span)); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } // Ignore tuple element changes, nullability and dynamic. These type changes do not affect runtime type. // They only affect custom attributes emitted on the members - all runtimes are expected to accept // custom attribute updates in metadata deltas, even if they do not have any observable effect. private static readonly SymbolEquivalenceComparer s_runtimeSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false, ignoreNullableAnnotations: true); private static readonly SymbolEquivalenceComparer s_exactSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: true, ignoreNullableAnnotations: false); protected static bool SymbolsEquivalent(ISymbol oldSymbol, ISymbol newSymbol) => s_exactSymbolEqualityComparer.Equals(oldSymbol, newSymbol); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) => ParameterTypesEquivalent(oldParameters, newParameters, exact: false) && s_runtimeSymbolEqualityComparer.Equals(oldReturnType, newReturnType); // TODO: should check ref, ref readonly, custom mods protected static bool ParameterTypesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ImmutableArray<IParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => ParameterTypesEquivalent(oldParameter, newParameter, exact)); protected static bool CustomModifiersEquivalent(CustomModifier oldModifier, CustomModifier newModifier, bool exact) => oldModifier.IsOptional == newModifier.IsOptional && TypesEquivalent(oldModifier.Modifier, newModifier.Modifier, exact); protected static bool CustomModifiersEquivalent(ImmutableArray<CustomModifier> oldModifiers, ImmutableArray<CustomModifier> newModifiers, bool exact) => oldModifiers.SequenceEqual(newModifiers, exact, (x, y, exact) => CustomModifiersEquivalent(x, y, exact)); protected static bool ReturnTypesEquivalent(IMethodSymbol oldMethod, IMethodSymbol newMethod, bool exact) => oldMethod.ReturnsByRef == newMethod.ReturnsByRef && oldMethod.ReturnsByRefReadonly == newMethod.ReturnsByRefReadonly && CustomModifiersEquivalent(oldMethod.ReturnTypeCustomModifiers, newMethod.ReturnTypeCustomModifiers, exact) && CustomModifiersEquivalent(oldMethod.RefCustomModifiers, newMethod.RefCustomModifiers, exact) && TypesEquivalent(oldMethod.ReturnType, newMethod.ReturnType, exact); protected static bool ReturnTypesEquivalent(IPropertySymbol oldProperty, IPropertySymbol newProperty, bool exact) => oldProperty.ReturnsByRef == newProperty.ReturnsByRef && oldProperty.ReturnsByRefReadonly == newProperty.ReturnsByRefReadonly && CustomModifiersEquivalent(oldProperty.TypeCustomModifiers, newProperty.TypeCustomModifiers, exact) && CustomModifiersEquivalent(oldProperty.RefCustomModifiers, newProperty.RefCustomModifiers, exact) && TypesEquivalent(oldProperty.Type, newProperty.Type, exact); protected static bool ReturnTypesEquivalent(IEventSymbol oldEvent, IEventSymbol newEvent, bool exact) => TypesEquivalent(oldEvent.Type, newEvent.Type, exact); // Note: SignatureTypeEquivalenceComparer compares dynamic and object the same. protected static bool TypesEquivalent(ITypeSymbol? oldType, ITypeSymbol? newType, bool exact) => (exact ? s_exactSymbolEqualityComparer : (IEqualityComparer<ITypeSymbol?>)s_runtimeSymbolEqualityComparer.SignatureTypeEquivalenceComparer).Equals(oldType, newType); protected static bool TypesEquivalent<T>(ImmutableArray<T> oldTypes, ImmutableArray<T> newTypes, bool exact) where T : ITypeSymbol => oldTypes.SequenceEqual(newTypes, exact, (x, y, exact) => TypesEquivalent(x, y, exact)); protected static bool ParameterTypesEquivalent(IParameterSymbol oldParameter, IParameterSymbol newParameter, bool exact) => (exact ? s_exactSymbolEqualityComparer : s_runtimeSymbolEqualityComparer).ParameterEquivalenceComparer.Equals(oldParameter, newParameter); protected static bool TypeParameterConstraintsEquivalent(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, bool exact) => TypesEquivalent(oldParameter.ConstraintTypes, newParameter.ConstraintTypes, exact) && oldParameter.HasReferenceTypeConstraint == newParameter.HasReferenceTypeConstraint && oldParameter.HasValueTypeConstraint == newParameter.HasValueTypeConstraint && oldParameter.HasConstructorConstraint == newParameter.HasConstructorConstraint && oldParameter.HasNotNullConstraint == newParameter.HasNotNullConstraint && oldParameter.HasUnmanagedTypeConstraint == newParameter.HasUnmanagedTypeConstraint && oldParameter.Variance == newParameter.Variance; protected static bool TypeParametersEquivalent(ImmutableArray<ITypeParameterSymbol> oldParameters, ImmutableArray<ITypeParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => oldParameter.Name == newParameter.Name && TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact)); protected static bool BaseTypesEquivalent(INamedTypeSymbol oldType, INamedTypeSymbol newType, bool exact) => TypesEquivalent(oldType.BaseType, newType.BaseType, exact) && TypesEquivalent(oldType.AllInterfaces, newType.AllInterfaces, exact); protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, bool inBreakState, CancellationToken cancellationToken) { Debug.Assert(inBreakState || newActiveStatementSpans.IsEmpty); if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbolEdits in GetSymbolEdits(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol, syntacticEditKind) = symbolEdits; var symbol = newSymbol ?? oldSymbol; Contract.ThrowIfNull(symbol); if (!processedSymbols.Add(symbol)) { continue; } var symbolKey = SymbolKey.Create(symbol, cancellationToken); // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol ??= symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newSymbol ??= symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); // The syntax change implies an update of the associated symbol but the old/new symbol does not actually exist. // Treat the edit as Insert/Delete. This may happen e.g. when all C# global statements are removed, the first one is added or they are moved to another file. if (syntacticEditKind == EditKind.Update) { if (oldSymbol == null || oldDeclaration != null && oldDeclaration.SyntaxTree != oldModel?.SyntaxTree) { syntacticEditKind = EditKind.Insert; } else if (newSymbol == null || newDeclaration != null && newDeclaration.SyntaxTree != newModel.SyntaxTree) { syntacticEditKind = EditKind.Delete; } } if (!inBreakState) { // Delete/insert/update edit of a member of a reloadable type (including nested types) results in Replace edit of the containing type. // If a Delete edit is part of delete-insert operation (member moved to a different partial type declaration or to a different file) // skip producing Replace semantic edit for this Delete edit as one will be reported by the corresponding Insert edit. var oldContainingType = oldSymbol?.ContainingType; var newContainingType = newSymbol?.ContainingType; var containingType = newContainingType ?? oldContainingType; if (containingType != null && (syntacticEditKind != EditKind.Delete || newSymbol == null)) { var containingTypeSymbolKey = SymbolKey.Create(containingType, cancellationToken); oldContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldContainingType != null && newContainingType != null && IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } } var oldType = oldSymbol as INamedTypeSymbol; var newType = newSymbol as INamedTypeSymbol; // Deleting a reloadable type is a rude edit, reported the same as for non-reloadable. // Adding a reloadable type is a standard type addition (TODO: unless added to a reloadable type?). // Making reloadable attribute non-reloadable results in a new version of the type that is // not reloadable but does not update the old version in-place. if (syntacticEditKind != EditKind.Delete && oldType != null && newType != null && IsReloadable(oldType)) { if (symbol == newType || processedSymbols.Add(newType)) { if (oldType.Name != newType.Name) { // https://github.com/dotnet/roslyn/issues/54886 ReportUpdateRudeEdit(diagnostics, RudeEditKind.Renamed, newType, newDeclaration, cancellationToken); } else if (oldType.Arity != newType.Arity) { // https://github.com/dotnet/roslyn/issues/54881 ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newType, newDeclaration, cancellationToken); } else if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newType, newDeclaration, cancellationToken); } else { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, symbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldType, newType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } continue; } } switch (syntacticEditKind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, RudeEditKind.DeleteActiveStatement, cancellationToken); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits, cancellationToken); } } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); // If we got here for a global statement then the actual edit is a delete of the synthesized Main method if (IsGlobalMain(oldSymbol)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.Delete, diagnosticSpan, edit.OldNode, new[] { GetDisplayName(edit.OldNode, EditKind.Delete) })); continue; } // If the associated member declaration (accessor -> property/indexer/event, parameter -> method) has also been deleted skip // the delete of the symbol as it will be deleted by the delete of the associated member. // // Associated member declarations must be in the same document as the symbol, so we don't need to resolve their symbol. // In some cases the symbol even can't be resolved unambiguously. Consider e.g. resolving a method with its parameter deleted - // we wouldn't know which overload to resolve to. if (TryGetAssociatedMemberDeclaration(oldDeclaration, out var oldAssociatedMemberDeclaration)) { if (HasEdit(editMap, oldAssociatedMemberDeclaration, EditKind.Delete)) { continue; } } else if (oldSymbol.ContainingType != null) { // Check if the symbol being deleted is a member of a type that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var containingSymbolKey = SymbolKey.Create(oldSymbol.ContainingType, cancellationToken); var newContainingSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainingSymbol == null) { continue; } } // deleting symbol is not allowed diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } editKind = SemanticEditKind.Update; } } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newBody = TryGetDeclarationBody(newDeclaration); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); if (isNewConstructorWithMemberInitializers || isDeclarationWithInitializer || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } else { editKind = SemanticEditKind.Update; } } else if (TryGetAssociatedMemberDeclaration(newDeclaration, out var newAssociatedMemberDeclaration) && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. continue; } else if (newSymbol is IParameterSymbol || newSymbol is ITypeParameterSymbol) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); continue; } else if (newContainingType != null && !IsGlobalMain(newSymbol)) { // The edit actually adds a new symbol into an existing or a new type. var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } else { // adds a new top-level type, or a global statement where none existed before, which is // therefore inserting the <Program>$ type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol || IsGlobalMain(newSymbol)); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); editKind = SemanticEditKind.Update; syntaxMap = null; // Partial type declarations and their type parameters. if (oldSymbol.DeclaringSyntaxReferences.Length != 1 && newSymbol.DeclaringSyntaxReferences.Length != 1) { break; } Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { Contract.ThrowIfNull(oldSymbol); AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol or IEventSymbol or IParameterSymbol or ITypeParameterSymbol) { continue; } } semanticEdits.Add(new SemanticEditInfo(editKind, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } foreach (var (oldEditNode, newEditNode, diagnosticSpan) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol, editKind) in GetSymbolEdits(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; Contract.ThrowIfNull(oldContainingType); Contract.ThrowIfNull(newContainingType); if (IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { var containingTypeSymbolKey = SymbolKey.Create(oldContainingType, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, diagnosticSpan); // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericTypeTriviaUpdate; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, diagnosticSpan, newEditNode, new[] { GetDisplayName(newEditNode) })); continue; } var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.Distinct(SemanticEditInfoComparer.Instance).ToImmutableArray(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private static bool IsReloadable(INamedTypeSymbol type) { var current = type; while (current != null) { foreach (var attributeData in current.GetAttributes()) { // We assume that the attribute System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute, if it exists, is well formed. // If not an error will be reported during EnC delta emit. if (attributeData.AttributeClass is { Name: CreateNewOnMetadataUpdateAttributeName, ContainingNamespace: { Name: "CompilerServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System" } } } }) { return true; } } current = current.BaseType; } return false; } private sealed class SemanticEditInfoComparer : IEqualityComparer<SemanticEditInfo> { public static SemanticEditInfoComparer Instance = new(); private static readonly IEqualityComparer<SymbolKey> s_symbolKeyComparer = SymbolKey.GetComparer(); public bool Equals([AllowNull] SemanticEditInfo x, [AllowNull] SemanticEditInfo y) => s_symbolKeyComparer.Equals(x.Symbol, y.Symbol); public int GetHashCode([DisallowNull] SemanticEditInfo obj) => obj.Symbol.GetHashCode(); } private void ReportUpdatedSymbolDeclarationRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasGeneratedAttributeChange, out bool hasGeneratedReturnTypeAttributeChange, out bool hasParameterRename, CancellationToken cancellationToken) { var rudeEdit = RudeEditKind.None; hasGeneratedAttributeChange = false; hasGeneratedReturnTypeAttributeChange = false; hasParameterRename = false; if (oldSymbol.Kind != newSymbol.Kind) { rudeEdit = (oldSymbol.Kind == SymbolKind.Field || newSymbol.Kind == SymbolKind.Field) ? RudeEditKind.FieldKindUpdate : RudeEditKind.Update; } else if (oldSymbol.Name != newSymbol.Name) { if (oldSymbol is IParameterSymbol && newSymbol is IParameterSymbol) { if (capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters)) { hasParameterRename = true; } else { rudeEdit = RudeEditKind.RenamingNotSupportedByRuntime; } } else { rudeEdit = RudeEditKind.Renamed; } // specialize rude edit for accessors and conversion operators: if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.AssociatedSymbol != null && newMethod.AssociatedSymbol != null) { if (oldMethod.MethodKind != newMethod.MethodKind) { rudeEdit = RudeEditKind.AccessorKindUpdate; } else { // rude edit will be reported by the associated symbol rudeEdit = RudeEditKind.None; } } else if (oldMethod.MethodKind == MethodKind.Conversion) { rudeEdit = RudeEditKind.ModifiersUpdate; } } } if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { rudeEdit = RudeEditKind.ChangingAccessibility; } if (oldSymbol.IsStatic != newSymbol.IsStatic || oldSymbol.IsVirtual != newSymbol.IsVirtual || oldSymbol.IsAbstract != newSymbol.IsAbstract || oldSymbol.IsOverride != newSymbol.IsOverride || oldSymbol.IsExtern != newSymbol.IsExtern) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (oldSymbol is IFieldSymbol oldField && newSymbol is IFieldSymbol newField) { if (oldField.IsConst != newField.IsConst || oldField.IsReadOnly != newField.IsReadOnly || oldField.IsVolatile != newField.IsVolatile) { rudeEdit = RudeEditKind.ModifiersUpdate; } // Report rude edit for updating const fields and values of enums. // The latter is only reported whne the enum underlying type does not change to avoid cascading rude edits. if (oldField.IsConst && newField.IsConst && !Equals(oldField.ConstantValue, newField.ConstantValue) && TypesEquivalent(oldField.ContainingType.EnumUnderlyingType, newField.ContainingType.EnumUnderlyingType, exact: false)) { rudeEdit = RudeEditKind.InitializerUpdate; } if (oldField.FixedSize != newField.FixedSize) { rudeEdit = RudeEditKind.FixedSizeFieldUpdate; } AnalyzeType(oldField.Type, newField.Type, ref rudeEdit, ref hasGeneratedAttributeChange); } else if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.IsReadOnly != newMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (oldMethod.IsInitOnly != newMethod.IsInitOnly) { rudeEdit = RudeEditKind.AccessorKindUpdate; } // Consider: Generalize to compare P/Invokes regardless of how they are defined (using attribute or Declare) if (oldMethod.MethodKind == MethodKind.DeclareMethod || newMethod.MethodKind == MethodKind.DeclareMethod) { var oldImportData = oldMethod.GetDllImportData(); var newImportData = newMethod.GetDllImportData(); if (oldImportData != null && newImportData != null) { // Declare method syntax can't change these. Debug.Assert(oldImportData.BestFitMapping == newImportData.BestFitMapping || oldImportData.CallingConvention == newImportData.CallingConvention || oldImportData.ExactSpelling == newImportData.ExactSpelling || oldImportData.SetLastError == newImportData.SetLastError || oldImportData.ThrowOnUnmappableCharacter == newImportData.ThrowOnUnmappableCharacter); if (oldImportData.ModuleName != newImportData.ModuleName) { rudeEdit = RudeEditKind.DeclareLibraryUpdate; } else if (oldImportData.EntryPointName != newImportData.EntryPointName) { rudeEdit = RudeEditKind.DeclareAliasUpdate; } else if (oldImportData.CharacterSet != newImportData.CharacterSet) { rudeEdit = RudeEditKind.ModifiersUpdate; } } else if (oldImportData is null != newImportData is null) { rudeEdit = RudeEditKind.ModifiersUpdate; } } // VB implements clause if (!oldMethod.ExplicitInterfaceImplementations.SequenceEqual(newMethod.ExplicitInterfaceImplementations, (x, y) => SymbolsEquivalent(x, y))) { rudeEdit = RudeEditKind.ImplementsClauseUpdate; } // VB handles clause if (!AreHandledEventsEqual(oldMethod, newMethod)) { rudeEdit = RudeEditKind.HandlesClauseUpdate; } // Check return type - do not report for accessors, their containing symbol will report the rude edits and attribute updates. if (rudeEdit == RudeEditKind.None && oldMethod.AssociatedSymbol == null && newMethod.AssociatedSymbol == null) { AnalyzeReturnType(oldMethod, newMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is INamedTypeSymbol oldType && newSymbol is INamedTypeSymbol newType) { if (oldType.TypeKind != newType.TypeKind || oldType.IsRecord != newType.IsRecord) // TODO: https://github.com/dotnet/roslyn/issues/51874 { rudeEdit = RudeEditKind.TypeKindUpdate; } else if (oldType.IsRefLikeType != newType.IsRefLikeType || oldType.IsReadOnly != newType.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (rudeEdit == RudeEditKind.None) { AnalyzeBaseTypes(oldType, newType, ref rudeEdit, ref hasGeneratedAttributeChange); if (oldType.DelegateInvokeMethod != null) { Contract.ThrowIfNull(newType.DelegateInvokeMethod); AnalyzeReturnType(oldType.DelegateInvokeMethod, newType.DelegateInvokeMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } } else if (oldSymbol is IPropertySymbol oldProperty && newSymbol is IPropertySymbol newProperty) { AnalyzeReturnType(oldProperty, newProperty, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } else if (oldSymbol is IEventSymbol oldEvent && newSymbol is IEventSymbol newEvent) { // "readonly" modifier can only be applied on the event itself, not on its accessors. if (oldEvent.AddMethod != null && newEvent.AddMethod != null && oldEvent.AddMethod.IsReadOnly != newEvent.AddMethod.IsReadOnly || oldEvent.RemoveMethod != null && newEvent.RemoveMethod != null && oldEvent.RemoveMethod.IsReadOnly != newEvent.RemoveMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } else { AnalyzeReturnType(oldEvent, newEvent, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is IParameterSymbol oldParameter && newSymbol is IParameterSymbol newParameter) { if (oldParameter.RefKind != newParameter.RefKind || oldParameter.IsParams != newParameter.IsParams || IsExtensionMethodThisParameter(oldParameter) != IsExtensionMethodThisParameter(newParameter)) { rudeEdit = RudeEditKind.ModifiersUpdate; } else if (oldParameter.HasExplicitDefaultValue != newParameter.HasExplicitDefaultValue || oldParameter.HasExplicitDefaultValue && !Equals(oldParameter.ExplicitDefaultValue, newParameter.ExplicitDefaultValue)) { rudeEdit = RudeEditKind.InitializerUpdate; } else { AnalyzeParameterType(oldParameter, newParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } } else if (oldSymbol is ITypeParameterSymbol oldTypeParameter && newSymbol is ITypeParameterSymbol newTypeParameter) { AnalyzeTypeParameter(oldTypeParameter, newTypeParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } // Do not report modifier update if type kind changed. if (rudeEdit == RudeEditKind.None && oldSymbol.IsSealed != newSymbol.IsSealed) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (rudeEdit != RudeEditKind.None) { // so we'll just use the last global statement in the file ReportUpdateRudeEdit(diagnostics, rudeEdit, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); } } private static void AnalyzeType(ITypeSymbol oldType, ITypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange, RudeEditKind rudeEditKind = RudeEditKind.TypeUpdate) { if (!TypesEquivalent(oldType, newType, exact: true)) { if (TypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = rudeEditKind; } } } private static void AnalyzeBaseTypes(INamedTypeSymbol oldType, INamedTypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (oldType.EnumUnderlyingType != null && newType.EnumUnderlyingType != null) { if (!TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: true)) { if (TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.EnumUnderlyingTypeUpdate; } } } else if (!BaseTypesEquivalent(oldType, newType, exact: true)) { if (BaseTypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.BaseTypeOrInterfaceUpdate; } } } private static void AnalyzeParameterType(IParameterSymbol oldParameter, IParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!ParameterTypesEquivalent(oldParameter, newParameter, exact: true)) { if (ParameterTypesEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeTypeParameter(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: true)) { if (TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = (oldParameter.Variance != newParameter.Variance) ? RudeEditKind.VarianceUpdate : RudeEditKind.ChangingConstraints; } } } private static void AnalyzeReturnType(IMethodSymbol oldMethod, IMethodSymbol newMethod, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldMethod, newMethod, exact: true)) { if (ReturnTypesEquivalent(oldMethod, newMethod, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else if (IsGlobalMain(oldMethod) || IsGlobalMain(newMethod)) { rudeEdit = RudeEditKind.ChangeImplicitMainReturnType; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IEventSymbol oldEvent, IEventSymbol newEvent, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldEvent, newEvent, exact: true)) { if (ReturnTypesEquivalent(oldEvent, newEvent, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IPropertySymbol oldProperty, IPropertySymbol newProperty, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldProperty, newProperty, exact: true)) { if (ReturnTypesEquivalent(oldProperty, newProperty, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static bool IsExtensionMethodThisParameter(IParameterSymbol parameter) => parameter is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } }; private void AnalyzeSymbolUpdate( ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, Match<SyntaxNode> topMatch, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo> semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { // TODO: fails in VB on delegate parameter https://github.com/dotnet/roslyn/issues/53337 // Contract.ThrowIfFalse(newSymbol.IsImplicitlyDeclared == newDeclaration is null); ReportCustomAttributeRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasAttributeChange, out var hasReturnTypeAttributeChange, cancellationToken); ReportUpdatedSymbolDeclarationRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasGeneratedAttributeChange, out var hasGeneratedReturnTypeAttributeChange, out var hasParameterRename, cancellationToken); hasAttributeChange |= hasGeneratedAttributeChange; hasReturnTypeAttributeChange |= hasGeneratedReturnTypeAttributeChange; if (hasParameterRename) { Debug.Assert(newSymbol is IParameterSymbol); AddParameterUpdateSemanticEdit(semanticEdits, (IParameterSymbol)newSymbol, syntaxMap, cancellationToken); } else if (hasAttributeChange || hasReturnTypeAttributeChange) { AddCustomAttributeSemanticEdits(semanticEdits, oldSymbol, newSymbol, topMatch, syntaxMap, hasAttributeChange, hasReturnTypeAttributeChange, cancellationToken); } // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod) || InGenericContext(newSymbol, out _)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodUpdate : RudeEditKind.GenericTypeUpdate; ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static void AddCustomAttributeSemanticEdits( ArrayBuilder<SemanticEditInfo> semanticEdits, ISymbol oldSymbol, ISymbol newSymbol, Match<SyntaxNode> topMatch, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool hasAttributeChange, bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvokeMethod } newDelegateType) { if (hasAttributeChange) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateType, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } if (hasReturnTypeAttributeChange) { // attributes applied on return type of a delegate are applied to both Invoke and BeginInvoke methods semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); AddDelegateBeginInvokeEdit(semanticEdits, newDelegateType, syntaxMap, cancellationToken); } } else if (newSymbol is INamedTypeSymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? symbolKey : null)); } else if (newSymbol is ITypeParameterSymbol) { var containingTypeSymbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, containingTypeSymbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol.ContainingSymbol, newSymbol.ContainingSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else if (newSymbol is IFieldSymbol or IPropertySymbol or IEventSymbol) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is IParameterSymbol newParameterSymbol) { AddParameterUpdateSemanticEdit(semanticEdits, newParameterSymbol, syntaxMap, cancellationToken); } } private static void AddParameterUpdateSemanticEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, IParameterSymbol newParameterSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { var newContainingSymbol = newParameterSymbol.ContainingSymbol; semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newContainingSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); // attributes applied on parameters of a delegate are applied to both Invoke and BeginInvoke methods if (newContainingSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: TypeKind.Delegate } newContainingDelegateType) { AddDelegateBeginInvokeEdit(semanticEdits, newContainingDelegateType, syntaxMap, cancellationToken); } } private static void AddDelegateBeginInvokeEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, INamedTypeSymbol delegateType, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(semanticEdits != null); var beginInvokeMethod = delegateType.GetMembers("BeginInvoke").FirstOrDefault(); if (beginInvokeMethod != null) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(beginInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } } private void ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasAttributeChange, out bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. hasAttributeChange = ReportCustomAttributeRudeEdits(diagnostics, oldSymbol.GetAttributes(), newSymbol.GetAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); hasReturnTypeAttributeChange = false; if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } else if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldInvokeMethod } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newInvokeMethod }) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldInvokeMethod.GetReturnTypeAttributes(), newInvokeMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } } private bool ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingAttributesNotSupportedByRuntime, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits, CancellationToken cancellationToken) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, Compilation newCompilation, RudeEditKind rudeEditKind, CancellationToken cancellationToken) { var newNode = GetDeleteRudeEditDiagnosticNode(oldSymbol, newCompilation, cancellationToken); diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Delete), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldSymbol), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol newSymbol, SyntaxNode? newNode, CancellationToken cancellationToken) { var node = newNode ?? GetRudeEditDiagnosticNode(newSymbol, cancellationToken); var span = (rudeEdit == RudeEditKind.ChangeImplicitMainReturnType) ? GetGlobalStatementDiagnosticSpan(node) : GetDiagnosticSpan(node, EditKind.Update); var arguments = rudeEdit switch { RudeEditKind.TypeKindUpdate or RudeEditKind.ChangeImplicitMainReturnType or RudeEditKind.GenericMethodUpdate or RudeEditKind.GenericTypeUpdate => Array.Empty<string>(), RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime => new[] { CreateNewOnMetadataUpdateAttributeName }, _ => new[] { GetDisplayName(newSymbol) } }; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, span, node, arguments)); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, CancellationToken cancellationToken) { if (newSymbol.IsImplicitlyDeclared) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, rudeEdit, cancellationToken); } else { ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static SyntaxNode GetRudeEditDiagnosticNode(ISymbol symbol, CancellationToken cancellationToken) { var container = symbol; while (container != null) { if (container.DeclaringSyntaxReferences.Length > 0) { return container.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); } container = container.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } private static SyntaxNode GetDeleteRudeEditDiagnosticNode(ISymbol oldSymbol, Compilation newCompilation, CancellationToken cancellationToken) { var oldContainer = oldSymbol.ContainingSymbol; while (oldContainer != null) { var containerKey = SymbolKey.Create(oldContainer, cancellationToken); var newContainer = containerKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainer != null) { return GetRudeEditDiagnosticNode(newContainer, cancellationToken); } oldContainer = oldContainer.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, Compilation newCompilation, IReadOnlySet<ISymbol> processedSymbols, EditAndContinueCapabilities capabilities, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); var isPartialEdit = IsPartialEdit(oldType, newType, oldSyntaxTree, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; SyntaxNode? newDeclaration = null; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Implicit record constructors are represented by the record declaration itself. // https://github.com/dotnet/roslyn/issues/54403 var isPrimaryRecordConstructor = IsRecordDeclaration(newDeclaration); // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!isPrimaryRecordConstructor && !IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!isPrimaryRecordConstructor && !anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, take the slow path. if (!isPrimaryRecordConstructor && topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfFalse(oldCtor is IMethodSymbol { MethodKind: MethodKind.Constructor or MethodKind.StaticConstructor }); } else if (!isPrimaryRecordConstructor && newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name must match for symbol matching to work // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 if (oldCtor != null && !isPrimaryRecordConstructor && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { AnalyzeSymbolUpdate(oldCtor, newCtor, newDeclaration, newCompilation, topMatch, capabilities, diagnostics, semanticEdits, syntaxMapToUse, cancellationToken); semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } private static bool IsPartialEdit(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree) { // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; return oldSymbol?.Kind == SymbolKind.NamedType && oldSymbol.DeclaringSyntaxReferences.Length > 1 && oldSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newSymbol?.Kind == SymbolKind.NamedType && newSymbol.DeclaringSyntaxReferences.Length > 1 && newSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(diagnostics, oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } using var oldLambdaBodyEnumerator = GetLambdaBodies(oldMemberBody).GetEnumerator(); using var newLambdaBodyEnumerator = GetLambdaBodies(newMemberBody).GetEnumerator(); var oldHasLambdas = oldLambdaBodyEnumerator.MoveNext(); var newHasLambdas = newLambdaBodyEnumerator.MoveNext(); // Exit early if there are no lambdas in the method to avoid expensive data flow analysis: if (!oldHasLambdas && !newHasLambdas) { return; } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } using var _1 = ArrayBuilder<int>.GetInstance(newCaptures.Length, fillWithValue: 0, out var reverseCapturesMap); // { new capture index -> new closure scope or null for "this" } using var _2 = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, fillWithValue: null, out var newCapturesToClosureScopes); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } using var _3 = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, fillWithValue: null, out var oldCapturesToClosureScopes); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _11 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _12 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); var newHasLambdaBodies = newHasLambdas; while (newHasLambdaBodies) { var (newLambda, newLambdaBody1, newLambdaBody2) = newLambdaBodyEnumerator.Current; if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } newHasLambdaBodies = newLambdaBodyEnumerator.MoveNext(); } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. var oldHasMoreLambdas = oldHasLambdas; while (oldHasMoreLambdas) { var (oldLambda, oldLambdaBody1, oldLambdaBody2) = oldLambdaBodyEnumerator.Current; if (!map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } oldHasMoreLambdas = oldLambdaBodyEnumerator.MoveNext(); } syntaxMapRequired = newHasLambdas; } private IEnumerable<(SyntaxNode lambda, SyntaxNode lambdaBody1, SyntaxNode? lambdaBody2)> GetLambdaBodies(SyntaxNode body) { foreach (var node in body.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(node, out var body1, out var body2)) { yield return (node, body1, body2); } } } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!TypesEquivalent(oldTypeOpt, newTypeOpt, exact: false)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } private void ReportLambdaSignatureRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, out bool hasSignatureErrors, CancellationToken cancellationToken) { hasSignatureErrors = false; var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { return; } if (IsLocalFunction(oldLambda) != IsLocalFunction(newLambda)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.SwitchBetweenLambdaAndLocalFunction, newLambda); hasSignatureErrors = true; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); // signature validation: if (!ParameterTypesEquivalent(oldLambdaSymbol.Parameters, newLambdaSymbol.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaParameters, newLambda); hasSignatureErrors = true; } else if (!ReturnTypesEquivalent(oldLambdaSymbol, newLambdaSymbol, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaReturnType, newLambda); hasSignatureErrors = true; } else if (!TypeParametersEquivalent(oldLambdaSymbol.TypeParameters, newLambdaSymbol.TypeParameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newLambda); hasSignatureErrors = true; } if (hasSignatureErrors) { return; } // custom attributes ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol, newLambdaSymbol, newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); for (var i = 0; i < oldLambdaSymbol.Parameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.Parameters[i], newLambdaSymbol.Parameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } for (var i = 0; i < oldLambdaSymbol.TypeParameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.TypeParameters[i], newLambdaSymbol.TypeParameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #pragma warning disable format private static bool IsGlobalMain(ISymbol symbol) => symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType.Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; #pragma warning restore format private static bool InGenericContext(ISymbol symbol, out bool isGenericMethod) { var current = symbol; while (true) { if (current is IMethodSymbol { Arity: > 0 }) { isGenericMethod = true; return true; } if (current is INamedTypeSymbol { Arity: > 0 }) { isGenericMethod = false; return true; } current = current.ContainingSymbol; if (current == null) { isGenericMethod = false; return false; } } } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } } #endregion } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Scripting/CoreTestUtilities/ObjectFormatterTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Text.RegularExpressions; using Xunit; namespace Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests { public abstract class ObjectFormatterTestBase { protected static PrintOptions SingleLineOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.SingleLine }; protected static PrintOptions SeparateLinesOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.SeparateLines, MaximumOutputLength = int.MaxValue }; protected static PrintOptions HiddenOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.Hidden }; public void AssertMembers(string str, params string[] expected) { int i = 0; foreach (var line in str.Split(new[] { Environment.NewLine + " " }, StringSplitOptions.None)) { if (i == 0) { Assert.Equal(expected[i] + " {", line); } else if (i == expected.Length - 1) { Assert.Equal(expected[i] + Environment.NewLine + "}" + Environment.NewLine, line); } else { Assert.Equal(expected[i] + ",", line); } i++; } Assert.Equal(expected.Length, 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.Text.RegularExpressions; using Xunit; namespace Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests { public abstract class ObjectFormatterTestBase { protected static PrintOptions SingleLineOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.SingleLine }; protected static PrintOptions SeparateLinesOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.SeparateLines, MaximumOutputLength = int.MaxValue }; protected static PrintOptions HiddenOptions => new PrintOptions { MemberDisplayFormat = MemberDisplayFormat.Hidden }; public void AssertMembers(string str, params string[] expected) { int i = 0; foreach (var line in str.Split(new[] { Environment.NewLine + " " }, StringSplitOptions.None)) { if (i == 0) { Assert.Equal(expected[i] + " {", line); } else if (i == expected.Length - 1) { Assert.Equal(expected[i] + Environment.NewLine + "}" + Environment.NewLine, line); } else { Assert.Equal(expected[i] + ",", line); } i++; } Assert.Equal(expected.Length, i); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/CSharp/Portable/SemanticModelReuse/CSharpSemanticModelReuseLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SemanticModelReuse; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SemanticModelReuse { [ExportLanguageService(typeof(ISemanticModelReuseLanguageService), LanguageNames.CSharp), Shared] internal class CSharpSemanticModelReuseLanguageService : AbstractSemanticModelReuseLanguageService< MemberDeclarationSyntax, BaseMethodDeclarationSyntax, BasePropertyDeclarationSyntax, AccessorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSemanticModelReuseLanguageService() { } protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override BasePropertyDeclarationSyntax GetBasePropertyDeclaration(AccessorDeclarationSyntax accessor) { Contract.ThrowIfFalse(accessor.Parent is AccessorListSyntax); Contract.ThrowIfFalse(accessor.Parent.Parent is BasePropertyDeclarationSyntax); return (BasePropertyDeclarationSyntax)accessor.Parent.Parent; } protected override SyntaxList<AccessorDeclarationSyntax> GetAccessors(BasePropertyDeclarationSyntax baseProperty) => baseProperty.AccessorList!.Accessors; public override SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node) { for (SyntaxNode? previous = null, current = node; current != null; previous = current, current = current.Parent) { // These are the exact types that SemanticModel.TryGetSpeculativeSemanticModelForMethodBody accepts. if (current is BaseMethodDeclarationSyntax baseMethod) return previous != null && baseMethod.Body == previous ? baseMethod : null; if (current is AccessorDeclarationSyntax accessor) return previous != null && accessor.Body == previous ? accessor : null; } return null; } protected override async Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync( SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousRoot = await previousSemanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await currentBodyNode.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var previousBodyNode = GetPreviousBodyNode(previousRoot, currentRoot, currentBodyNode); if (previousBodyNode is BaseMethodDeclarationSyntax previousBaseMethod && currentBodyNode is BaseMethodDeclarationSyntax currentBaseMethod && previousBaseMethod.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousBaseMethod.Body.SpanStart, currentBaseMethod, out var speculativeModel)) { return speculativeModel; } if (previousBodyNode is AccessorDeclarationSyntax previousAccessorDeclaration && currentBodyNode is AccessorDeclarationSyntax currentAccessorDeclaration && previousAccessorDeclaration.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousAccessorDeclaration.Body.SpanStart, currentAccessorDeclaration, out speculativeModel)) { return speculativeModel; } 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. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SemanticModelReuse; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SemanticModelReuse { [ExportLanguageService(typeof(ISemanticModelReuseLanguageService), LanguageNames.CSharp), Shared] internal class CSharpSemanticModelReuseLanguageService : AbstractSemanticModelReuseLanguageService< MemberDeclarationSyntax, BaseMethodDeclarationSyntax, BasePropertyDeclarationSyntax, AccessorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSemanticModelReuseLanguageService() { } protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override BasePropertyDeclarationSyntax GetBasePropertyDeclaration(AccessorDeclarationSyntax accessor) { Contract.ThrowIfFalse(accessor.Parent is AccessorListSyntax); Contract.ThrowIfFalse(accessor.Parent.Parent is BasePropertyDeclarationSyntax); return (BasePropertyDeclarationSyntax)accessor.Parent.Parent; } protected override SyntaxList<AccessorDeclarationSyntax> GetAccessors(BasePropertyDeclarationSyntax baseProperty) => baseProperty.AccessorList!.Accessors; public override SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node) { for (SyntaxNode? previous = null, current = node; current != null; previous = current, current = current.Parent) { // These are the exact types that SemanticModel.TryGetSpeculativeSemanticModelForMethodBody accepts. if (current is BaseMethodDeclarationSyntax baseMethod) return previous != null && baseMethod.Body == previous ? baseMethod : null; if (current is AccessorDeclarationSyntax accessor) return previous != null && accessor.Body == previous ? accessor : null; } return null; } protected override async Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync( SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousRoot = await previousSemanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await currentBodyNode.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var previousBodyNode = GetPreviousBodyNode(previousRoot, currentRoot, currentBodyNode); if (previousBodyNode is BaseMethodDeclarationSyntax previousBaseMethod && currentBodyNode is BaseMethodDeclarationSyntax currentBaseMethod && previousBaseMethod.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousBaseMethod.Body.SpanStart, currentBaseMethod, out var speculativeModel)) { return speculativeModel; } if (previousBodyNode is AccessorDeclarationSyntax previousAccessorDeclaration && currentBodyNode is AccessorDeclarationSyntax currentAccessorDeclaration && previousAccessorDeclaration.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousAccessorDeclaration.Body.SpanStart, currentAccessorDeclaration, out speculativeModel)) { return speculativeModel; } return null; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.RenameFileEditor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { private class RenameFileEditor : Editor { public RenameFileEditor(TService service, State state, string fileName, CancellationToken cancellationToken) : base(service, state, fileName, cancellationToken) { } public override Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() => Task.FromResult(RenameFileToMatchTypeName()); public override Task<Solution> GetModifiedSolutionAsync() { var modifiedSolution = SemanticDocument.Project.Solution .WithDocumentName(SemanticDocument.Document.Id, FileName); return Task.FromResult(modifiedSolution); } /// <summary> /// Renames the file to match the type contained in it. /// </summary> private ImmutableArray<CodeActionOperation> RenameFileToMatchTypeName() { var documentId = SemanticDocument.Document.Id; var oldSolution = SemanticDocument.Document.Project.Solution; var newSolution = oldSolution.WithDocumentName(documentId, FileName); return ImmutableArray.Create<CodeActionOperation>( new ApplyChangesOperation(newSolution)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { private class RenameFileEditor : Editor { public RenameFileEditor(TService service, State state, string fileName, CancellationToken cancellationToken) : base(service, state, fileName, cancellationToken) { } public override Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() => Task.FromResult(RenameFileToMatchTypeName()); public override Task<Solution> GetModifiedSolutionAsync() { var modifiedSolution = SemanticDocument.Project.Solution .WithDocumentName(SemanticDocument.Document.Id, FileName); return Task.FromResult(modifiedSolution); } /// <summary> /// Renames the file to match the type contained in it. /// </summary> private ImmutableArray<CodeActionOperation> RenameFileToMatchTypeName() { var documentId = SemanticDocument.Document.Id; var oldSolution = SemanticDocument.Document.Project.Solution; var newSolution = oldSolution.WithDocumentName(documentId, FileName); return ImmutableArray.Create<CodeActionOperation>( new ApplyChangesOperation(newSolution)); } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectState_Checksum.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class ProjectState { public bool TryGetStateChecksums(out ProjectStateChecksums stateChecksums) => _lazyChecksums.TryGetValue(out stateChecksums); public Task<ProjectStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken) => _lazyChecksums.GetValueAsync(cancellationToken); public Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken) { return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync( static (lazyChecksums, cancellationToken) => new ValueTask<ProjectStateChecksums>(lazyChecksums.GetValueAsync(cancellationToken)), static (projectStateChecksums, _) => projectStateChecksums.Checksum, _lazyChecksums, cancellationToken).AsTask(); } public Checksum GetParseOptionsChecksum() => GetParseOptionsChecksum(_solutionServices.Workspace.Services.GetService<ISerializerService>()); private Checksum GetParseOptionsChecksum(ISerializerService serializer) => this.SupportsCompilation ? ChecksumCache.GetOrCreate(this.ParseOptions, _ => serializer.CreateParseOptionsChecksum(this.ParseOptions)) : Checksum.Null; private async Task<ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken)) { var documentChecksumsTasks = DocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var additionalDocumentChecksumTasks = AdditionalDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var analyzerConfigDocumentChecksumTasks = AnalyzerConfigDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var serializer = _solutionServices.Workspace.Services.GetService<ISerializerService>(); var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken); // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed. var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null; cancellationToken.ThrowIfCancellationRequested(); var parseOptionsChecksum = GetParseOptionsChecksum(serializer); var projectReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(ProjectReferences, _ => new ChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var metadataReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(MetadataReferences, _ => new ChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false); var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false); var analyzerConfigDocumentChecksums = await Task.WhenAll(analyzerConfigDocumentChecksumTasks).ConfigureAwait(false); return new ProjectStateChecksums( infoChecksum, compilationOptionsChecksum, parseOptionsChecksum, documentChecksums: new ChecksumCollection(documentChecksums), projectReferenceChecksums, metadataReferenceChecksums, analyzerReferenceChecksums, additionalDocumentChecksums: new ChecksumCollection(additionalChecksums), analyzerConfigDocumentChecksumCollection: new ChecksumCollection(analyzerConfigDocumentChecksums)); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class ProjectState { public bool TryGetStateChecksums(out ProjectStateChecksums stateChecksums) => _lazyChecksums.TryGetValue(out stateChecksums); public Task<ProjectStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken) => _lazyChecksums.GetValueAsync(cancellationToken); public Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken) { return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync( static (lazyChecksums, cancellationToken) => new ValueTask<ProjectStateChecksums>(lazyChecksums.GetValueAsync(cancellationToken)), static (projectStateChecksums, _) => projectStateChecksums.Checksum, _lazyChecksums, cancellationToken).AsTask(); } public Checksum GetParseOptionsChecksum() => GetParseOptionsChecksum(_solutionServices.Workspace.Services.GetService<ISerializerService>()); private Checksum GetParseOptionsChecksum(ISerializerService serializer) => this.SupportsCompilation ? ChecksumCache.GetOrCreate(this.ParseOptions, _ => serializer.CreateParseOptionsChecksum(this.ParseOptions)) : Checksum.Null; private async Task<ProjectStateChecksums> ComputeChecksumsAsync(CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.ProjectState_ComputeChecksumsAsync, FilePath, cancellationToken)) { var documentChecksumsTasks = DocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var additionalDocumentChecksumTasks = AdditionalDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var analyzerConfigDocumentChecksumTasks = AnalyzerConfigDocumentStates.SelectAsArray(static (state, token) => state.GetChecksumAsync(token), cancellationToken); var serializer = _solutionServices.Workspace.Services.GetService<ISerializerService>(); var infoChecksum = serializer.CreateChecksum(ProjectInfo.Attributes, cancellationToken); // these compiler objects doesn't have good place to cache checksum. but rarely ever get changed. var compilationOptionsChecksum = SupportsCompilation ? ChecksumCache.GetOrCreate(CompilationOptions, _ => serializer.CreateChecksum(CompilationOptions, cancellationToken)) : Checksum.Null; cancellationToken.ThrowIfCancellationRequested(); var parseOptionsChecksum = GetParseOptionsChecksum(serializer); var projectReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(ProjectReferences, _ => new ChecksumCollection(ProjectReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var metadataReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(MetadataReferences, _ => new ChecksumCollection(MetadataReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var documentChecksums = await Task.WhenAll(documentChecksumsTasks).ConfigureAwait(false); var additionalChecksums = await Task.WhenAll(additionalDocumentChecksumTasks).ConfigureAwait(false); var analyzerConfigDocumentChecksums = await Task.WhenAll(analyzerConfigDocumentChecksumTasks).ConfigureAwait(false); return new ProjectStateChecksums( infoChecksum, compilationOptionsChecksum, parseOptionsChecksum, documentChecksums: new ChecksumCollection(documentChecksums), projectReferenceChecksums, metadataReferenceChecksums, analyzerReferenceChecksums, additionalDocumentChecksums: new ChecksumCollection(additionalChecksums), analyzerConfigDocumentChecksumCollection: new ChecksumCollection(analyzerConfigDocumentChecksums)); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/UnifiedSuggestions/UnifiedSuggestedActions/IUnifiedSuggestedAction.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeActions; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Similar to ISuggestedAction, but in a location that can be used by both local Roslyn and LSP. /// </summary> internal interface IUnifiedSuggestedAction { Workspace Workspace { get; } CodeAction OriginalCodeAction { get; } CodeActionPriority CodeActionPriority { 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. using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Similar to ISuggestedAction, but in a location that can be used by both local Roslyn and LSP. /// </summary> internal interface IUnifiedSuggestedAction { Workspace Workspace { get; } CodeAction OriginalCodeAction { get; } CodeActionPriority CodeActionPriority { get; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/Diagnostics/DefaultDiagnosticModeServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { [ExportWorkspaceServiceFactory(typeof(IDiagnosticModeService), ServiceLayer.Default), Shared] internal class DefaultDiagnosticModeServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDiagnosticModeServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new DefaultDiagnosticModeService(workspaceServices.Workspace); private class DefaultDiagnosticModeService : IDiagnosticModeService { private readonly Workspace _workspace; private readonly Dictionary<Option2<DiagnosticMode>, Lazy<DiagnosticMode>> _optionToMode = new(); public DefaultDiagnosticModeService(Workspace workspace) { _workspace = workspace; } public DiagnosticMode GetDiagnosticMode(Option2<DiagnosticMode> option) { var lazy = GetLazy(option); return lazy.Value; } private Lazy<DiagnosticMode> GetLazy(Option2<DiagnosticMode> option) { lock (_optionToMode) { if (!_optionToMode.TryGetValue(option, out var lazy)) { lazy = new Lazy<DiagnosticMode>(() => ComputeDiagnosticMode(option), isThreadSafe: true); _optionToMode.Add(option, lazy); } return lazy; } } private DiagnosticMode ComputeDiagnosticMode(Option2<DiagnosticMode> option) { var inCodeSpacesServer = IsInCodeSpacesServer(); // If we're in the code-spaces server, we only support pull diagnostics. This is because the only way // for diagnostics to make it through from the server to the client is through the codespaces LSP // channel, which is only pull based. if (inCodeSpacesServer) return DiagnosticMode.Pull; var diagnosticModeOption = _workspace.Options.GetOption(option); // If the workspace diagnostic mode is set to Default, defer to the feature flag service. if (diagnosticModeOption == DiagnosticMode.Default) { return GetDiagnosticModeFromFeatureFlag(); } // Otherwise, defer to the workspace+option to determine what mode we're in. return diagnosticModeOption; } private DiagnosticMode GetDiagnosticModeFromFeatureFlag() { var featureFlagService = _workspace.Services.GetRequiredService<IExperimentationService>(); var isPullDiagnosticExperimentEnabled = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag); return isPullDiagnosticExperimentEnabled ? DiagnosticMode.Pull : DiagnosticMode.Push; } private static bool IsInCodeSpacesServer() { // hack until there is an officially supported free-threaded synchronous platform API to ask this question. return Environment.GetEnvironmentVariable("VisualStudioServerMode") == "1"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Diagnostics { [ExportWorkspaceServiceFactory(typeof(IDiagnosticModeService), ServiceLayer.Default), Shared] internal class DefaultDiagnosticModeServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDiagnosticModeServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new DefaultDiagnosticModeService(workspaceServices.Workspace); private class DefaultDiagnosticModeService : IDiagnosticModeService { private readonly Workspace _workspace; private readonly Dictionary<Option2<DiagnosticMode>, Lazy<DiagnosticMode>> _optionToMode = new(); public DefaultDiagnosticModeService(Workspace workspace) { _workspace = workspace; } public DiagnosticMode GetDiagnosticMode(Option2<DiagnosticMode> option) { var lazy = GetLazy(option); return lazy.Value; } private Lazy<DiagnosticMode> GetLazy(Option2<DiagnosticMode> option) { lock (_optionToMode) { if (!_optionToMode.TryGetValue(option, out var lazy)) { lazy = new Lazy<DiagnosticMode>(() => ComputeDiagnosticMode(option), isThreadSafe: true); _optionToMode.Add(option, lazy); } return lazy; } } private DiagnosticMode ComputeDiagnosticMode(Option2<DiagnosticMode> option) { var inCodeSpacesServer = IsInCodeSpacesServer(); // If we're in the code-spaces server, we only support pull diagnostics. This is because the only way // for diagnostics to make it through from the server to the client is through the codespaces LSP // channel, which is only pull based. if (inCodeSpacesServer) return DiagnosticMode.Pull; var diagnosticModeOption = _workspace.Options.GetOption(option); // If the workspace diagnostic mode is set to Default, defer to the feature flag service. if (diagnosticModeOption == DiagnosticMode.Default) { return GetDiagnosticModeFromFeatureFlag(); } // Otherwise, defer to the workspace+option to determine what mode we're in. return diagnosticModeOption; } private DiagnosticMode GetDiagnosticModeFromFeatureFlag() { var featureFlagService = _workspace.Services.GetRequiredService<IExperimentationService>(); var isPullDiagnosticExperimentEnabled = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LspPullDiagnosticsFeatureFlag); return isPullDiagnosticExperimentEnabled ? DiagnosticMode.Pull : DiagnosticMode.Push; } private static bool IsInCodeSpacesServer() { // hack until there is an officially supported free-threaded synchronous platform API to ask this question. return Environment.GetEnvironmentVariable("VisualStudioServerMode") == "1"; } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/Log/IErrorLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ErrorLogger { internal interface IErrorLoggerService : IWorkspaceService { void LogException(object source, Exception exception); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.ErrorLogger { internal interface IErrorLoggerService : IWorkspaceService { void LogException(object source, Exception exception); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/CSharp/Portable/Debugging/CSharpProximityExpressionsService.Worker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Debugging { internal partial class CSharpProximityExpressionsService { internal class Worker { private readonly SyntaxTree _syntaxTree; private readonly int _position; private StatementSyntax _parentStatement; private SyntaxToken _token; private readonly List<string> _expressions = new List<string>(); public Worker(SyntaxTree syntaxTree, int position) { _syntaxTree = syntaxTree; _position = position; } internal IList<string> Do(CancellationToken cancellationToken) { // First, find the containing statement. We'll want to add the expressions in this // statement to the result. _token = _syntaxTree.GetRoot(cancellationToken).FindToken(_position); _parentStatement = _token.GetAncestor<StatementSyntax>(); if (_parentStatement == null) { return null; } AddRelevantExpressions(_parentStatement, _expressions, includeDeclarations: false); AddPrecedingRelevantExpressions(); AddFollowingRelevantExpressions(cancellationToken); AddCurrentDeclaration(); AddMethodParameters(); AddIndexerParameters(); AddCatchParameters(); AddThisExpression(); AddValueExpression(); var result = _expressions.Distinct().Where(e => e.Length > 0).ToList(); return result.Count == 0 ? null : result; } private void AddValueExpression() { // If we're in a setter/adder/remover then add "value". if (_parentStatement.GetAncestorOrThis<AccessorDeclarationSyntax>().IsKind( SyntaxKind.SetAccessorDeclaration, SyntaxKind.InitAccessorDeclaration, SyntaxKind.AddAccessorDeclaration, SyntaxKind.RemoveAccessorDeclaration)) { _expressions.Add("value"); } } private void AddThisExpression() { // If it's an instance member, then also add "this". var memberDeclaration = _parentStatement.GetAncestorOrThis<MemberDeclarationSyntax>(); if (!memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword)) { _expressions.Add("this"); } } private void AddCatchParameters() { var block = GetImmediatelyContainingBlock(); // if we're the start of a "catch(Goo e)" clause, then add "e". if (block != null && block.IsParentKind(SyntaxKind.CatchClause, out CatchClauseSyntax catchClause) && catchClause.Declaration != null && catchClause.Declaration.Identifier.Kind() != SyntaxKind.None) { _expressions.Add(catchClause.Declaration.Identifier.ValueText); } } private BlockSyntax GetImmediatelyContainingBlock() { return IsFirstBlockStatement() ? (BlockSyntax)_parentStatement.Parent : _parentStatement is BlockSyntax && ((BlockSyntax)_parentStatement).OpenBraceToken == _token ? (BlockSyntax)_parentStatement : null; } private bool IsFirstBlockStatement() => _parentStatement.Parent is BlockSyntax parentBlockOpt && parentBlockOpt.Statements.FirstOrDefault() == _parentStatement; private void AddCurrentDeclaration() { if (_parentStatement is LocalDeclarationStatementSyntax) { AddRelevantExpressions(_parentStatement, _expressions, includeDeclarations: true); } } private void AddMethodParameters() { // and we're the start of a method, then also add the parameters of that method to // the proximity expressions. var block = GetImmediatelyContainingBlock(); if (block != null && block.Parent is MemberDeclarationSyntax) { var parameterList = ((MemberDeclarationSyntax)block.Parent).GetParameterList(); AddParameters(parameterList); } } private void AddIndexerParameters() { var block = GetImmediatelyContainingBlock(); // and we're the start of a method, then also add the parameters of that method to // the proximity expressions. if (block != null && block.Parent is AccessorDeclarationSyntax && block.Parent.Parent is AccessorListSyntax && block.Parent.Parent.Parent is IndexerDeclarationSyntax) { var parameterList = ((IndexerDeclarationSyntax)block.Parent.Parent.Parent).ParameterList; AddParameters(parameterList); } } private void AddParameters(BaseParameterListSyntax parameterList) { if (parameterList != null) { _expressions.AddRange( from p in parameterList.Parameters select p.Identifier.ValueText); } } private void AddFollowingRelevantExpressions(CancellationToken cancellationToken) { var line = _syntaxTree.GetText(cancellationToken).Lines.IndexOf(_position); // If there's are more statements following us on the same line, then add them as // well. for (var nextStatement = _parentStatement.GetNextStatement(); nextStatement != null && _syntaxTree.GetText(cancellationToken).Lines.IndexOf(nextStatement.SpanStart) == line; nextStatement = nextStatement.GetNextStatement()) { AddRelevantExpressions(nextStatement, _expressions, includeDeclarations: false); } } private void AddPrecedingRelevantExpressions() { // If we're not the first statement in this block, // and there's an expression or declaration statement directly above us, // then add the expressions from that as well. StatementSyntax previousStatement; if (_parentStatement is BlockSyntax block && block.CloseBraceToken == _token) { // If we're at the last brace of a block, use the last // statement in the block. previousStatement = block.Statements.LastOrDefault(); } else { previousStatement = _parentStatement.GetPreviousStatement(); } if (previousStatement != null) { switch (previousStatement.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.LocalDeclarationStatement: AddRelevantExpressions(previousStatement, _expressions, includeDeclarations: true); break; case SyntaxKind.DoStatement: AddExpressionTerms((previousStatement as DoStatementSyntax).Condition, _expressions); AddLastStatementOfConstruct(previousStatement); break; case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.IfStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.WhileStatement: case SyntaxKind.LockStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.TryStatement: case SyntaxKind.UsingStatement: AddRelevantExpressions(previousStatement, _expressions, includeDeclarations: false); AddLastStatementOfConstruct(previousStatement); break; default: break; } } else { // This is the first statement of the block. Go to the nearest enclosing statement and add its expressions var statementAncestor = _parentStatement.Ancestors().OfType<StatementSyntax>().FirstOrDefault(node => !node.IsKind(SyntaxKind.Block)); if (statementAncestor != null) { AddRelevantExpressions(statementAncestor, _expressions, includeDeclarations: true); } } } private void AddLastStatementOfConstruct(StatementSyntax statement) { if (statement == null) { return; } switch (statement.Kind()) { case SyntaxKind.Block: AddLastStatementOfConstruct((statement as BlockSyntax).Statements.LastOrDefault()); break; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: AddLastStatementOfConstruct(statement.GetPreviousStatement()); break; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: AddLastStatementOfConstruct((statement as CheckedStatementSyntax).Block); break; case SyntaxKind.DoStatement: AddLastStatementOfConstruct((statement as DoStatementSyntax).Statement); break; case SyntaxKind.ForStatement: AddLastStatementOfConstruct((statement as ForStatementSyntax).Statement); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: AddLastStatementOfConstruct((statement as CommonForEachStatementSyntax).Statement); break; case SyntaxKind.IfStatement: var ifStatement = statement as IfStatementSyntax; AddLastStatementOfConstruct(ifStatement.Statement); if (ifStatement.Else != null) { AddLastStatementOfConstruct(ifStatement.Else.Statement); } break; case SyntaxKind.LockStatement: AddLastStatementOfConstruct((statement as LockStatementSyntax).Statement); break; case SyntaxKind.SwitchStatement: var switchStatement = statement as SwitchStatementSyntax; foreach (var section in switchStatement.Sections) { AddLastStatementOfConstruct(section.Statements.LastOrDefault()); } break; case SyntaxKind.TryStatement: var tryStatement = statement as TryStatementSyntax; if (tryStatement.Finally != null) { AddLastStatementOfConstruct(tryStatement.Finally.Block); } else { AddLastStatementOfConstruct(tryStatement.Block); foreach (var catchClause in tryStatement.Catches) { AddLastStatementOfConstruct(catchClause.Block); } } break; case SyntaxKind.UsingStatement: AddLastStatementOfConstruct((statement as UsingStatementSyntax).Statement); break; case SyntaxKind.WhileStatement: AddLastStatementOfConstruct((statement as WhileStatementSyntax).Statement); break; default: AddRelevantExpressions(statement, _expressions, includeDeclarations: false); break; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Debugging { internal partial class CSharpProximityExpressionsService { internal class Worker { private readonly SyntaxTree _syntaxTree; private readonly int _position; private StatementSyntax _parentStatement; private SyntaxToken _token; private readonly List<string> _expressions = new List<string>(); public Worker(SyntaxTree syntaxTree, int position) { _syntaxTree = syntaxTree; _position = position; } internal IList<string> Do(CancellationToken cancellationToken) { // First, find the containing statement. We'll want to add the expressions in this // statement to the result. _token = _syntaxTree.GetRoot(cancellationToken).FindToken(_position); _parentStatement = _token.GetAncestor<StatementSyntax>(); if (_parentStatement == null) { return null; } AddRelevantExpressions(_parentStatement, _expressions, includeDeclarations: false); AddPrecedingRelevantExpressions(); AddFollowingRelevantExpressions(cancellationToken); AddCurrentDeclaration(); AddMethodParameters(); AddIndexerParameters(); AddCatchParameters(); AddThisExpression(); AddValueExpression(); var result = _expressions.Distinct().Where(e => e.Length > 0).ToList(); return result.Count == 0 ? null : result; } private void AddValueExpression() { // If we're in a setter/adder/remover then add "value". if (_parentStatement.GetAncestorOrThis<AccessorDeclarationSyntax>().IsKind( SyntaxKind.SetAccessorDeclaration, SyntaxKind.InitAccessorDeclaration, SyntaxKind.AddAccessorDeclaration, SyntaxKind.RemoveAccessorDeclaration)) { _expressions.Add("value"); } } private void AddThisExpression() { // If it's an instance member, then also add "this". var memberDeclaration = _parentStatement.GetAncestorOrThis<MemberDeclarationSyntax>(); if (!memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword)) { _expressions.Add("this"); } } private void AddCatchParameters() { var block = GetImmediatelyContainingBlock(); // if we're the start of a "catch(Goo e)" clause, then add "e". if (block != null && block.IsParentKind(SyntaxKind.CatchClause, out CatchClauseSyntax catchClause) && catchClause.Declaration != null && catchClause.Declaration.Identifier.Kind() != SyntaxKind.None) { _expressions.Add(catchClause.Declaration.Identifier.ValueText); } } private BlockSyntax GetImmediatelyContainingBlock() { return IsFirstBlockStatement() ? (BlockSyntax)_parentStatement.Parent : _parentStatement is BlockSyntax && ((BlockSyntax)_parentStatement).OpenBraceToken == _token ? (BlockSyntax)_parentStatement : null; } private bool IsFirstBlockStatement() => _parentStatement.Parent is BlockSyntax parentBlockOpt && parentBlockOpt.Statements.FirstOrDefault() == _parentStatement; private void AddCurrentDeclaration() { if (_parentStatement is LocalDeclarationStatementSyntax) { AddRelevantExpressions(_parentStatement, _expressions, includeDeclarations: true); } } private void AddMethodParameters() { // and we're the start of a method, then also add the parameters of that method to // the proximity expressions. var block = GetImmediatelyContainingBlock(); if (block != null && block.Parent is MemberDeclarationSyntax) { var parameterList = ((MemberDeclarationSyntax)block.Parent).GetParameterList(); AddParameters(parameterList); } } private void AddIndexerParameters() { var block = GetImmediatelyContainingBlock(); // and we're the start of a method, then also add the parameters of that method to // the proximity expressions. if (block != null && block.Parent is AccessorDeclarationSyntax && block.Parent.Parent is AccessorListSyntax && block.Parent.Parent.Parent is IndexerDeclarationSyntax) { var parameterList = ((IndexerDeclarationSyntax)block.Parent.Parent.Parent).ParameterList; AddParameters(parameterList); } } private void AddParameters(BaseParameterListSyntax parameterList) { if (parameterList != null) { _expressions.AddRange( from p in parameterList.Parameters select p.Identifier.ValueText); } } private void AddFollowingRelevantExpressions(CancellationToken cancellationToken) { var line = _syntaxTree.GetText(cancellationToken).Lines.IndexOf(_position); // If there's are more statements following us on the same line, then add them as // well. for (var nextStatement = _parentStatement.GetNextStatement(); nextStatement != null && _syntaxTree.GetText(cancellationToken).Lines.IndexOf(nextStatement.SpanStart) == line; nextStatement = nextStatement.GetNextStatement()) { AddRelevantExpressions(nextStatement, _expressions, includeDeclarations: false); } } private void AddPrecedingRelevantExpressions() { // If we're not the first statement in this block, // and there's an expression or declaration statement directly above us, // then add the expressions from that as well. StatementSyntax previousStatement; if (_parentStatement is BlockSyntax block && block.CloseBraceToken == _token) { // If we're at the last brace of a block, use the last // statement in the block. previousStatement = block.Statements.LastOrDefault(); } else { previousStatement = _parentStatement.GetPreviousStatement(); } if (previousStatement != null) { switch (previousStatement.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.LocalDeclarationStatement: AddRelevantExpressions(previousStatement, _expressions, includeDeclarations: true); break; case SyntaxKind.DoStatement: AddExpressionTerms((previousStatement as DoStatementSyntax).Condition, _expressions); AddLastStatementOfConstruct(previousStatement); break; case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.IfStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.WhileStatement: case SyntaxKind.LockStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.TryStatement: case SyntaxKind.UsingStatement: AddRelevantExpressions(previousStatement, _expressions, includeDeclarations: false); AddLastStatementOfConstruct(previousStatement); break; default: break; } } else { // This is the first statement of the block. Go to the nearest enclosing statement and add its expressions var statementAncestor = _parentStatement.Ancestors().OfType<StatementSyntax>().FirstOrDefault(node => !node.IsKind(SyntaxKind.Block)); if (statementAncestor != null) { AddRelevantExpressions(statementAncestor, _expressions, includeDeclarations: true); } } } private void AddLastStatementOfConstruct(StatementSyntax statement) { if (statement == null) { return; } switch (statement.Kind()) { case SyntaxKind.Block: AddLastStatementOfConstruct((statement as BlockSyntax).Statements.LastOrDefault()); break; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: AddLastStatementOfConstruct(statement.GetPreviousStatement()); break; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: AddLastStatementOfConstruct((statement as CheckedStatementSyntax).Block); break; case SyntaxKind.DoStatement: AddLastStatementOfConstruct((statement as DoStatementSyntax).Statement); break; case SyntaxKind.ForStatement: AddLastStatementOfConstruct((statement as ForStatementSyntax).Statement); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: AddLastStatementOfConstruct((statement as CommonForEachStatementSyntax).Statement); break; case SyntaxKind.IfStatement: var ifStatement = statement as IfStatementSyntax; AddLastStatementOfConstruct(ifStatement.Statement); if (ifStatement.Else != null) { AddLastStatementOfConstruct(ifStatement.Else.Statement); } break; case SyntaxKind.LockStatement: AddLastStatementOfConstruct((statement as LockStatementSyntax).Statement); break; case SyntaxKind.SwitchStatement: var switchStatement = statement as SwitchStatementSyntax; foreach (var section in switchStatement.Sections) { AddLastStatementOfConstruct(section.Statements.LastOrDefault()); } break; case SyntaxKind.TryStatement: var tryStatement = statement as TryStatementSyntax; if (tryStatement.Finally != null) { AddLastStatementOfConstruct(tryStatement.Finally.Block); } else { AddLastStatementOfConstruct(tryStatement.Block); foreach (var catchClause in tryStatement.Catches) { AddLastStatementOfConstruct(catchClause.Block); } } break; case SyntaxKind.UsingStatement: AddLastStatementOfConstruct((statement as UsingStatementSyntax).Statement); break; case SyntaxKind.WhileStatement: AddLastStatementOfConstruct((statement as WhileStatementSyntax).Statement); break; default: AddRelevantExpressions(statement, _expressions, includeDeclarations: false); break; } } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Test/Core/Diagnostics/CommonDiagnosticAnalyzers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis { public static class CommonDiagnosticAnalyzers { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AnalyzerForErrorLogTest : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor( "ID1", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "Description1", helpLinkUri: "HelpLink1", customTags: new[] { "1_CustomTag1", "1_CustomTag2" }); public static readonly DiagnosticDescriptor Descriptor2 = new DiagnosticDescriptor( "ID2", "Title2", "Message2", "Category2", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Description2", helpLinkUri: "HelpLink2", customTags: new[] { "2_CustomTag1", "2_CustomTag2" }); private static readonly ImmutableDictionary<string, string> s_properties = new Dictionary<string, string> { { "Key1", "Value1" }, { "Key2", "Value2" } }.ToImmutableDictionary(); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1, Descriptor2); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => { // With location diagnostic. var location = compilationContext.Compilation.SyntaxTrees.First().GetRoot().GetLocation(); compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor1, location, s_properties)); // No location diagnostic. compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor2, Location.None, s_properties)); }); } private static string GetExpectedPropertiesMapText() { var expectedText = @" ""customProperties"": {"; foreach (var kvp in s_properties.OrderBy(kvp => kvp.Key)) { if (!expectedText.EndsWith("{")) { expectedText += ","; } expectedText += string.Format(@" ""{0}"": ""{1}""", kvp.Key, kvp.Value); } expectedText += @" }"; return expectedText; } public static string GetExpectedV1ErrorLogResultsAndRulesText(Compilation compilation) { var tree = compilation.SyntaxTrees.First(); var root = tree.GetRoot(); var expectedLineSpan = root.GetLocation().GetLineSpan(); var filePath = GetUriForPath(tree.FilePath); return @" ""results"": [ { ""ruleId"": """ + Descriptor1.Id + @""", ""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": """ + Descriptor1.MessageFormat + @""", ""locations"": [ { ""resultFile"": { ""uri"": """ + filePath + @""", ""region"": { ""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @", ""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @", ""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @", ""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @" } } } ], ""properties"": { ""warningLevel"": 1," + GetExpectedPropertiesMapText() + @" } }, { ""ruleId"": """ + Descriptor2.Id + @""", ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": """ + Descriptor2.MessageFormat + @""", ""properties"": {" + GetExpectedPropertiesMapText() + @" } } ], ""rules"": { """ + Descriptor1.Id + @""": { ""id"": """ + Descriptor1.Id + @""", ""shortDescription"": """ + Descriptor1.Title + @""", ""fullDescription"": """ + Descriptor1.Description + @""", ""defaultLevel"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""helpUri"": """ + Descriptor1.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor1.Category + @""", ""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @" ] } }, """ + Descriptor2.Id + @""": { ""id"": """ + Descriptor2.Id + @""", ""shortDescription"": """ + Descriptor2.Title + @""", ""fullDescription"": """ + Descriptor2.Description + @""", ""defaultLevel"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""helpUri"": """ + Descriptor2.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor2.Category + @""", ""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @" ] } } } } ] }"; } public static string GetExpectedV1ErrorLogWithSuppressionResultsAndRulesText(Compilation compilation) { var tree = compilation.SyntaxTrees.First(); var root = tree.GetRoot(); var expectedLineSpan = root.GetLocation().GetLineSpan(); var filePath = GetUriForPath(tree.FilePath); return @" ""results"": [ { ""ruleId"": """ + Descriptor1.Id + @""", ""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": """ + Descriptor1.MessageFormat + @""", ""suppressionStates"": [ ""suppressedInSource"" ], ""locations"": [ { ""resultFile"": { ""uri"": """ + filePath + @""", ""region"": { ""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @", ""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @", ""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @", ""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @" } } } ], ""properties"": { ""warningLevel"": 1," + GetExpectedPropertiesMapText() + @" } }, { ""ruleId"": """ + Descriptor2.Id + @""", ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": """ + Descriptor2.MessageFormat + @""", ""properties"": {" + GetExpectedPropertiesMapText() + @" } } ], ""rules"": { """ + Descriptor1.Id + @""": { ""id"": """ + Descriptor1.Id + @""", ""shortDescription"": """ + Descriptor1.Title + @""", ""fullDescription"": """ + Descriptor1.Description + @""", ""defaultLevel"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""helpUri"": """ + Descriptor1.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor1.Category + @""", ""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @" ] } }, """ + Descriptor2.Id + @""": { ""id"": """ + Descriptor2.Id + @""", ""shortDescription"": """ + Descriptor2.Title + @""", ""fullDescription"": """ + Descriptor2.Description + @""", ""defaultLevel"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""helpUri"": """ + Descriptor2.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor2.Category + @""", ""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @" ] } } } } ] }"; } public static string GetExpectedV2ErrorLogResultsText(Compilation compilation) { var tree = compilation.SyntaxTrees.First(); var root = tree.GetRoot(); var expectedLineSpan = root.GetLocation().GetLineSpan(); var filePath = GetUriForPath(tree.FilePath); return @" ""results"": [ { ""ruleId"": """ + Descriptor1.Id + @""", ""ruleIndex"": 0, ""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": { ""text"": """ + Descriptor1.MessageFormat + @""" }, ""locations"": [ { ""physicalLocation"": { ""artifactLocation"": { ""uri"": """ + filePath + @""" }, ""region"": { ""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @", ""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @", ""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @", ""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @" } } } ], ""properties"": { ""warningLevel"": 1," + GetExpectedPropertiesMapText() + @" } }, { ""ruleId"": """ + Descriptor2.Id + @""", ""ruleIndex"": 1, ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": { ""text"": """ + Descriptor2.MessageFormat + @""" }, ""properties"": {" + GetExpectedPropertiesMapText() + @" } } ]"; } public static string GetExpectedV2ErrorLogWithSuppressionResultsText(Compilation compilation, string justification) { var tree = compilation.SyntaxTrees.First(); var root = tree.GetRoot(); var expectedLineSpan = root.GetLocation().GetLineSpan(); var filePath = GetUriForPath(tree.FilePath); return @" ""results"": [ { ""ruleId"": """ + Descriptor1.Id + @""", ""ruleIndex"": 0, ""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": { ""text"": """ + Descriptor1.MessageFormat + @""" }, ""suppressions"": [ { ""kind"": ""inSource""" + (justification == null ? "" : @", ""justification"": """ + (justification) + @"""") + @" } ], ""locations"": [ { ""physicalLocation"": { ""artifactLocation"": { ""uri"": """ + filePath + @""" }, ""region"": { ""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @", ""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @", ""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @", ""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @" } } } ], ""properties"": { ""warningLevel"": 1," + GetExpectedPropertiesMapText() + @" } }, { ""ruleId"": """ + Descriptor2.Id + @""", ""ruleIndex"": 1, ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": { ""text"": """ + Descriptor2.MessageFormat + @""" }, ""properties"": {" + GetExpectedPropertiesMapText() + @" } } ]"; } public static string GetExpectedV2ErrorLogRulesText() { return @" ""rules"": [ { ""id"": """ + Descriptor1.Id + @""", ""shortDescription"": { ""text"": """ + Descriptor1.Title + @""" }, ""fullDescription"": { ""text"": """ + Descriptor1.Description + @""" }, ""helpUri"": """ + Descriptor1.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor1.Category + @""", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @" ] } }, { ""id"": """ + Descriptor2.Id + @""", ""shortDescription"": { ""text"": """ + Descriptor2.Title + @""" }, ""fullDescription"": { ""text"": """ + Descriptor2.Description + @""" }, ""defaultConfiguration"": { ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""" }, ""helpUri"": """ + Descriptor2.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor2.Category + @""", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @" ] } } ]"; } public static string GetUriForPath(string path) { var uri = new Uri(path, UriKind.RelativeOrAbsolute); return uri.IsAbsoluteUri ? uri.AbsoluteUri : WebUtility.UrlEncode(uri.ToString()); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class NotConfigurableDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor EnabledRule = new DiagnosticDescriptor( "ID1", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.NotConfigurable); public static readonly DiagnosticDescriptor DisabledRule = new DiagnosticDescriptor( "ID2", "Title2", "Message2", "Category2", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: false, customTags: WellKnownDiagnosticTags.NotConfigurable); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(EnabledRule, DisabledRule); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => { // Report enabled diagnostic. compilationContext.ReportDiagnostic(Diagnostic.Create(EnabledRule, Location.None)); // Try to report disabled diagnostic. compilationContext.ReportDiagnostic(Diagnostic.Create(DisabledRule, Location.None)); }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CodeBlockActionAnalyzer : DiagnosticAnalyzer { private readonly bool _onlyStatelessAction; public CodeBlockActionAnalyzer(bool onlyStatelessAction = false) { _onlyStatelessAction = onlyStatelessAction; } public static readonly DiagnosticDescriptor CodeBlockTopLevelRule = new DiagnosticDescriptor( "CodeBlockTopLevelRuleId", "CodeBlockTopLevelRuleTitle", "CodeBlock : {0}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor CodeBlockPerCompilationRule = new DiagnosticDescriptor( "CodeBlockPerCompilationRuleId", "CodeBlockPerCompilationRuleTitle", "CodeBlock : {0}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(CodeBlockTopLevelRule, CodeBlockPerCompilationRule); } } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(codeBlockContext => { codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockTopLevelRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name)); }); if (!_onlyStatelessAction) { context.RegisterCompilationStartAction(compilationStartContext => { compilationStartContext.RegisterCodeBlockAction(codeBlockContext => { codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockPerCompilationRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name)); }); }); } } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class CSharpCodeBlockObjectCreationAnalyzer : CodeBlockObjectCreationAnalyzer<SyntaxKind> { protected override SyntaxKind ObjectCreationExpressionKind => SyntaxKind.ObjectCreationExpression; } [DiagnosticAnalyzer(LanguageNames.VisualBasic)] public class VisualBasicCodeBlockObjectCreationAnalyzer : CodeBlockObjectCreationAnalyzer<VisualBasic.SyntaxKind> { protected override VisualBasic.SyntaxKind ObjectCreationExpressionKind => VisualBasic.SyntaxKind.ObjectCreationExpression; } public abstract class CodeBlockObjectCreationAnalyzer<TLanguageKindEnum> : DiagnosticAnalyzer where TLanguageKindEnum : struct { public static readonly DiagnosticDescriptor DiagnosticDescriptor = new DiagnosticDescriptor( "Id", "Title", "Message", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DiagnosticDescriptor); protected abstract TLanguageKindEnum ObjectCreationExpressionKind { get; } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<TLanguageKindEnum>(codeBlockStartContext => { codeBlockStartContext.RegisterSyntaxNodeAction(syntaxNodeContext => { syntaxNodeContext.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptor, syntaxNodeContext.Node.GetLocation())); }, ObjectCreationExpressionKind); }); } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class CSharpGenericNameAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = nameof(DiagnosticId); public const string Title = nameof(Title); public const string Message = nameof(Message); public const string Category = nameof(Category); public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, Severity, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.GenericName); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation())); } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class CSharpNamespaceDeclarationAnalyzer : AbstractNamespaceDeclarationAnalyzer<SyntaxKind> { protected override SyntaxKind NamespaceDeclarationSyntaxKind => SyntaxKind.NamespaceDeclaration; } [DiagnosticAnalyzer(LanguageNames.VisualBasic)] public class VisualBasicNamespaceDeclarationAnalyzer : AbstractNamespaceDeclarationAnalyzer<VisualBasic.SyntaxKind> { protected override VisualBasic.SyntaxKind NamespaceDeclarationSyntaxKind => VisualBasic.SyntaxKind.NamespaceStatement; } public abstract class AbstractNamespaceDeclarationAnalyzer<TLanguageKindEnum> : DiagnosticAnalyzer where TLanguageKindEnum : struct { public const string DiagnosticId = nameof(DiagnosticId); public const string Title = nameof(Title); public const string Message = nameof(Message); public const string Category = nameof(Category); public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, Severity, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); protected abstract TLanguageKindEnum NamespaceDeclarationSyntaxKind { get; } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, NamespaceDeclarationSyntaxKind); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation())); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithNoActions : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor DummyRule = new DiagnosticDescriptor( "ID1", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DummyRule); public override void Initialize(AnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithDisabledRules : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( "ID1", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(_ => { }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class EnsureNoMergedNamespaceSymbolAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = nameof(DiagnosticId); public const string Title = nameof(Title); public const string Message = nameof(Message); public const string Category = nameof(Category); public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, Severity, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Namespace); } private void AnalyzeSymbol(SymbolAnalysisContext context) { // Ensure we are not invoked for merged namespace symbol, but instead for constituent namespace scoped to the source assembly. var ns = (INamespaceSymbol)context.Symbol; if (ns.ContainingAssembly != context.Compilation.Assembly || ns.ConstituentNamespaces.Length > 1) { context.ReportDiagnostic(Diagnostic.Create(Rule, ns.Locations[0])); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithNoSupportedDiagnostics : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public override void Initialize(AnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithInvalidDiagnosticId : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "Invalid ID", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None))); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithNullDescriptor : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create((DiagnosticDescriptor)null); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(_ => { }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithCSharpCompilerDiagnosticId : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( #pragma warning disable RS1029 // Do not use reserved diagnostic IDs. "CS101", #pragma warning restore RS1029 // Do not use reserved diagnostic IDs. "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None))); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithBasicCompilerDiagnosticId : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( #pragma warning disable RS1029 // Do not use reserved diagnostic IDs. "BC101", #pragma warning restore RS1029 // Do not use reserved diagnostic IDs. "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None))); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithInvalidDiagnosticSpan : DiagnosticAnalyzer { private readonly TextSpan _badSpan; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title1", "Message", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public AnalyzerWithInvalidDiagnosticSpan(TextSpan badSpan) => _badSpan = badSpan; public Exception ThrownException { get; set; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxTreeAction(c => { try { ThrownException = null; c.ReportDiagnostic(Diagnostic.Create(Descriptor, SourceLocation.Create(c.Tree, _badSpan))); } catch (Exception e) { ThrownException = e; throw; } }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithInvalidDiagnosticLocation : DiagnosticAnalyzer { private readonly Location _invalidLocation; private readonly ActionKind _actionKind; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title1", "Message {0}", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public enum ActionKind { Symbol, CodeBlock, Operation, OperationBlockEnd, Compilation, CompilationEnd, SyntaxTree } public AnalyzerWithInvalidDiagnosticLocation(SyntaxTree treeInAnotherCompilation, ActionKind actionKind) { _invalidLocation = treeInAnotherCompilation.GetRoot().GetLocation(); _actionKind = actionKind; } private void ReportDiagnostic(Action<Diagnostic> addDiagnostic, ActionKind actionKindBeingRun) { if (_actionKind == actionKindBeingRun) { var diagnostic = Diagnostic.Create(Descriptor, _invalidLocation); addDiagnostic(diagnostic); } } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(cc => { cc.RegisterSymbolAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.Symbol), SymbolKind.NamedType); cc.RegisterCodeBlockAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.CodeBlock)); cc.RegisterCompilationEndAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.CompilationEnd)); cc.RegisterOperationBlockStartAction(oc => { oc.RegisterOperationAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.Operation), OperationKind.VariableDeclarationGroup); oc.RegisterOperationBlockEndAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.OperationBlockEnd)); }); }); context.RegisterSyntaxTreeAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.SyntaxTree)); context.RegisterCompilationAction(cc => ReportDiagnostic(cc.ReportDiagnostic, ActionKind.Compilation)); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerThatThrowsInSupportedDiagnostics : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(); public override void Initialize(AnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerThatThrowsInGetMessage : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( "ID1", "Title1", new MyLocalizableStringThatThrows(), "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(symbolContext => { symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0])); }, SymbolKind.NamedType); } private sealed class MyLocalizableStringThatThrows : LocalizableString { protected override bool AreEqual(object other) { return ReferenceEquals(this, other); } protected override int GetHash() { return 0; } protected override string GetText(IFormatProvider formatProvider) { throw new NotImplementedException(); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerReportingMisformattedDiagnostic : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( "ID1", "Title1", "Symbol Name: {0}, Extra argument: {1}", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(symbolContext => { // Report diagnostic with incorrect number of message format arguments. symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name)); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CompilationAnalyzerWithSeverity : DiagnosticAnalyzer { public const string DiagnosticId = "ID1000"; public CompilationAnalyzerWithSeverity( DiagnosticSeverity severity, bool configurable) { var customTags = !configurable ? new[] { WellKnownDiagnosticTags.NotConfigurable } : Array.Empty<string>(); Descriptor = new DiagnosticDescriptor( DiagnosticId, "Description1", string.Empty, "Analysis", severity, true, customTags: customTags); } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(this.OnCompilation); } private void OnCompilation(CompilationAnalysisContext context) { // Report the diagnostic on all trees in compilation. foreach (var tree in context.Compilation.SyntaxTrees) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, tree.GetRoot().GetLocation())); } } } /// <summary> /// This analyzer is intended to be used only when concurrent execution is enabled for analyzers. /// This analyzer will deadlock if the driver runs analyzers on a single thread OR takes a lock around callbacks into this analyzer to prevent concurrent analyzer execution /// Former indicates a bug in the test using this analyzer and the latter indicates a bug in the analyzer driver. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class ConcurrentAnalyzer : DiagnosticAnalyzer { private readonly ImmutableHashSet<string> _symbolNames; private int _token; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ConcurrentAnalyzerId", "Title", "ConcurrentAnalyzerMessage for symbol '{0}'", "Category", DiagnosticSeverity.Warning, true); public ConcurrentAnalyzer(IEnumerable<string> symbolNames) { Assert.True(Environment.ProcessorCount > 1, "This analyzer is intended to be used only in a concurrent environment."); _symbolNames = symbolNames.ToImmutableHashSet(); _token = 0; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); // Enable concurrent action callbacks on analyzer. context.EnableConcurrentExecution(); } private void OnCompilationStart(CompilationStartAnalysisContext context) { Assert.True(context.Compilation.Options.ConcurrentBuild, "This analyzer is intended to be used only when concurrent build is enabled."); var pendingSymbols = new ConcurrentSet<INamedTypeSymbol>(); foreach (var type in context.Compilation.GlobalNamespace.GetTypeMembers()) { if (_symbolNames.Contains(type.Name)) { pendingSymbols.Add(type); } } context.RegisterSymbolAction(symbolContext => { if (!pendingSymbols.Remove((INamedTypeSymbol)symbolContext.Symbol)) { return; } var myToken = Interlocked.Increment(ref _token); if (myToken == 1) { // Wait for all symbol callbacks to execute. // This analyzer will deadlock if the driver doesn't attempt concurrent callbacks. while (pendingSymbols.Any()) { Thread.Sleep(10); } } // ok, now report diagnostic on the symbol. var diagnostic = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name); symbolContext.ReportDiagnostic(diagnostic); }, SymbolKind.NamedType); } } /// <summary> /// This analyzer will report diagnostics only if it receives any concurrent action callbacks, which would be a /// bug in the analyzer driver as this analyzer doesn't invoke <see cref="AnalysisContext.EnableConcurrentExecution"/>. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class NonConcurrentAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "NonConcurrentAnalyzerId", "Title", "Analyzer driver made concurrent action callbacks, when analyzer didn't register for concurrent execution", "Category", DiagnosticSeverity.Warning, true); private const int registeredActionCounts = 1000; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { SemaphoreSlim gate = new SemaphoreSlim(initialCount: registeredActionCounts); for (var i = 0; i < registeredActionCounts; i++) { context.RegisterSymbolAction(symbolContext => { using (gate.DisposableWait(symbolContext.CancellationToken)) { ReportDiagnosticIfActionInvokedConcurrently(gate, symbolContext); } }, SymbolKind.NamedType); } } private void ReportDiagnosticIfActionInvokedConcurrently(SemaphoreSlim gate, SymbolAnalysisContext symbolContext) { if (gate.CurrentCount != registeredActionCounts - 1) { var diagnostic = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations[0]); symbolContext.ReportDiagnostic(diagnostic); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class OperationAnalyzer : DiagnosticAnalyzer { private readonly ActionKind _actionKind; private readonly bool _verifyGetControlFlowGraph; private readonly ConcurrentDictionary<IOperation, (ControlFlowGraph Graph, ISymbol AssociatedSymbol)> _controlFlowGraphMapOpt; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title1", "{0} diagnostic", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public enum ActionKind { Operation, OperationInOperationBlockStart, OperationBlock, OperationBlockEnd } public OperationAnalyzer(ActionKind actionKind, bool verifyGetControlFlowGraph = false) { _actionKind = actionKind; _verifyGetControlFlowGraph = verifyGetControlFlowGraph; _controlFlowGraphMapOpt = verifyGetControlFlowGraph ? new ConcurrentDictionary<IOperation, (ControlFlowGraph, ISymbol)>() : null; } public ImmutableArray<(ControlFlowGraph Graph, ISymbol AssociatedSymbol)> GetControlFlowGraphs() { Assert.True(_verifyGetControlFlowGraph); return _controlFlowGraphMapOpt.Values.OrderBy(flowGraphAndSymbol => flowGraphAndSymbol.Graph.OriginalOperation.Syntax.SpanStart).ToImmutableArray(); } private void ReportDiagnostic(Action<Diagnostic> addDiagnostic, Location location) { var diagnostic = Diagnostic.Create(Descriptor, location, _actionKind); addDiagnostic(diagnostic); } private void CacheAndVerifyControlFlowGraph(ImmutableArray<IOperation> operationBlocks, Func<IOperation, (ControlFlowGraph Graph, ISymbol AssociatedSymbol)> getControlFlowGraph) { if (_verifyGetControlFlowGraph) { foreach (var operationBlock in operationBlocks) { var controlFlowGraphAndSymbol = getControlFlowGraph(operationBlock); Assert.NotNull(controlFlowGraphAndSymbol); Assert.Same(operationBlock.GetRootOperation(), controlFlowGraphAndSymbol.Graph.OriginalOperation); _controlFlowGraphMapOpt.Add(controlFlowGraphAndSymbol.Graph.OriginalOperation, controlFlowGraphAndSymbol); // Verify analyzer driver caches the flow graph. Assert.Same(controlFlowGraphAndSymbol.Graph, getControlFlowGraph(operationBlock).Graph); // Verify exceptions for invalid inputs. try { _ = getControlFlowGraph(null); } catch (ArgumentNullException ex) { Assert.Equal(new ArgumentNullException("operationBlock").Message, ex.Message); } try { _ = getControlFlowGraph(operationBlock.Descendants().First()); } catch (ArgumentException ex) { Assert.Equal(new ArgumentException(CodeAnalysisResources.InvalidOperationBlockForAnalysisContext, "operationBlock").Message, ex.Message); } } } } private void VerifyControlFlowGraph(OperationAnalysisContext operationContext, bool inBlockAnalysisContext) { if (_verifyGetControlFlowGraph) { var controlFlowGraph = operationContext.GetControlFlowGraph(); Assert.NotNull(controlFlowGraph); // Verify analyzer driver caches the flow graph. Assert.Same(controlFlowGraph, operationContext.GetControlFlowGraph()); var rootOperation = operationContext.Operation.GetRootOperation(); if (inBlockAnalysisContext) { // Verify same flow graph returned from containing block analysis context. Assert.Same(controlFlowGraph, _controlFlowGraphMapOpt[rootOperation].Graph); } else { _controlFlowGraphMapOpt[rootOperation] = (controlFlowGraph, operationContext.ContainingSymbol); } } } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { switch (_actionKind) { case ActionKind.OperationBlockEnd: context.RegisterOperationBlockStartAction(blockStartContext => { blockStartContext.RegisterOperationBlockEndAction(c => ReportDiagnostic(c.ReportDiagnostic, c.OwningSymbol.Locations[0])); CacheAndVerifyControlFlowGraph(blockStartContext.OperationBlocks, op => (blockStartContext.GetControlFlowGraph(op), blockStartContext.OwningSymbol)); }); break; case ActionKind.OperationBlock: context.RegisterOperationBlockAction(blockContext => { ReportDiagnostic(blockContext.ReportDiagnostic, blockContext.OwningSymbol.Locations[0]); CacheAndVerifyControlFlowGraph(blockContext.OperationBlocks, op => (blockContext.GetControlFlowGraph(op), blockContext.OwningSymbol)); }); break; case ActionKind.Operation: context.RegisterOperationAction(operationContext => { ReportDiagnostic(operationContext.ReportDiagnostic, operationContext.Operation.Syntax.GetLocation()); VerifyControlFlowGraph(operationContext, inBlockAnalysisContext: false); }, OperationKind.Literal); break; case ActionKind.OperationInOperationBlockStart: context.RegisterOperationBlockStartAction(blockContext => { CacheAndVerifyControlFlowGraph(blockContext.OperationBlocks, op => (blockContext.GetControlFlowGraph(op), blockContext.OwningSymbol)); blockContext.RegisterOperationAction(operationContext => { ReportDiagnostic(operationContext.ReportDiagnostic, operationContext.Operation.Syntax.GetLocation()); VerifyControlFlowGraph(operationContext, inBlockAnalysisContext: true); }, OperationKind.Literal); }); break; } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class OperationBlockAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title1", "OperationBlock for {0}: {1}", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(c => { foreach (var operationRoot in c.OperationBlocks) { var diagnostic = Diagnostic.Create(Descriptor, c.OwningSymbol.Locations[0], c.OwningSymbol.Name, operationRoot.Kind); c.ReportDiagnostic(diagnostic); } }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class FieldReferenceOperationAnalyzer : DiagnosticAnalyzer { private readonly bool _doOperationBlockAnalysis; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title", "Field {0} = {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public FieldReferenceOperationAnalyzer(bool doOperationBlockAnalysis) { _doOperationBlockAnalysis = doOperationBlockAnalysis; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { if (_doOperationBlockAnalysis) { context.RegisterOperationBlockAction(operationBlockAnalysisContext => { foreach (var operationBlock in operationBlockAnalysisContext.OperationBlocks) { foreach (var operation in operationBlock.DescendantsAndSelf().OfType<IFieldReferenceOperation>()) { AnalyzerFieldReferenceOperation(operation, operationBlockAnalysisContext.ReportDiagnostic); } } }); } else { context.RegisterOperationAction(AnalyzerOperation, OperationKind.FieldReference); } } private static void AnalyzerOperation(OperationAnalysisContext operationAnalysisContext) { AnalyzerFieldReferenceOperation((IFieldReferenceOperation)operationAnalysisContext.Operation, operationAnalysisContext.ReportDiagnostic); } private static void AnalyzerFieldReferenceOperation(IFieldReferenceOperation operation, Action<Diagnostic> reportDiagnostic) { var diagnostic = Diagnostic.Create(Descriptor, operation.Syntax.GetLocation(), operation.Field.Name, operation.Field.ConstantValue); reportDiagnostic(diagnostic); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class MethodOrConstructorBodyOperationAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title", "Method {0}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(operationContext => { var diagnostic = Diagnostic.Create(Descriptor, operationContext.Operation.Syntax.GetLocation(), operationContext.ContainingSymbol.Name); operationContext.ReportDiagnostic(diagnostic); }, OperationKind.MethodBody, OperationKind.ConstructorBody); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class GeneratedCodeAnalyzer : DiagnosticAnalyzer { private readonly GeneratedCodeAnalysisFlags? _generatedCodeAnalysisFlagsOpt; public static readonly DiagnosticDescriptor Warning = new DiagnosticDescriptor( "GeneratedCodeAnalyzerWarning", "Title", "GeneratedCodeAnalyzerMessage for '{0}'", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor Error = new DiagnosticDescriptor( "GeneratedCodeAnalyzerError", "Title", "GeneratedCodeAnalyzerMessage for '{0}'", "Category", DiagnosticSeverity.Error, true); public static readonly DiagnosticDescriptor Summary = new DiagnosticDescriptor( "GeneratedCodeAnalyzerSummary", "Title2", "GeneratedCodeAnalyzer received callbacks for: '{0}' types and '{1}' files", "Category", DiagnosticSeverity.Warning, true); public GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { _generatedCodeAnalysisFlagsOpt = generatedCodeAnalysisFlagsOpt; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Warning, Error, Summary); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); if (_generatedCodeAnalysisFlagsOpt.HasValue) { // Configure analysis on generated code. context.ConfigureGeneratedCodeAnalysis(_generatedCodeAnalysisFlagsOpt.Value); } } private void OnCompilationStart(CompilationStartAnalysisContext context) { var sortedCallbackSymbolNames = new SortedSet<string>(); var sortedCallbackTreePaths = new SortedSet<string>(); context.RegisterSymbolAction(symbolContext => { sortedCallbackSymbolNames.Add(symbolContext.Symbol.Name); ReportSymbolDiagnostics(symbolContext.Symbol, symbolContext.ReportDiagnostic); }, SymbolKind.NamedType); context.RegisterSyntaxTreeAction(treeContext => { sortedCallbackTreePaths.Add(treeContext.Tree.FilePath); ReportTreeDiagnostics(treeContext.Tree, treeContext.ReportDiagnostic); }); context.RegisterCompilationEndAction(endContext => { var arg1 = sortedCallbackSymbolNames.Join(","); var arg2 = sortedCallbackTreePaths.Join(","); // Summary diagnostics about received callbacks. var diagnostic = Diagnostic.Create(Summary, Location.None, arg1, arg2); endContext.ReportDiagnostic(diagnostic); }); } private void ReportSymbolDiagnostics(ISymbol symbol, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, symbol.Locations[0], symbol.Name); } private void ReportTreeDiagnostics(SyntaxTree tree, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, tree.GetRoot().GetLastToken().GetLocation(), tree.FilePath); } private void ReportDiagnosticsCore(Action<Diagnostic> addDiagnostic, Location location, params object[] messageArguments) { // warning diagnostic var diagnostic = Diagnostic.Create(Warning, location, messageArguments); addDiagnostic(diagnostic); // error diagnostic diagnostic = Diagnostic.Create(Error, location, messageArguments); addDiagnostic(diagnostic); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class GeneratedCodeAnalyzer2 : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( "GeneratedCodeAnalyzer2Warning", "Title", "GeneratedCodeAnalyzer2Message for '{0}'; Total types analyzed: '{1}'", "Category", DiagnosticSeverity.Warning, true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { // Analyze but don't report diagnostics on generated code. context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); context.RegisterCompilationStartAction(compilationStartContext => { var namedTypes = new HashSet<ISymbol>(); compilationStartContext.RegisterSymbolAction(symbolContext => namedTypes.Add(symbolContext.Symbol), SymbolKind.NamedType); compilationStartContext.RegisterCompilationEndAction(compilationEndContext => { foreach (var namedType in namedTypes) { var diagnostic = Diagnostic.Create(Rule, namedType.Locations[0], namedType.Name, namedTypes.Count); compilationEndContext.ReportDiagnostic(diagnostic); } }); }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class SharedStateAnalyzer : DiagnosticAnalyzer { private readonly SyntaxTreeValueProvider<bool> _treeValueProvider; private readonly HashSet<SyntaxTree> _treeCallbackSet; private readonly SourceTextValueProvider<int> _textValueProvider; private readonly HashSet<SourceText> _textCallbackSet; public static readonly DiagnosticDescriptor GeneratedCodeDescriptor = new DiagnosticDescriptor( "GeneratedCodeDiagnostic", "Title1", "GeneratedCodeDiagnostic {0}", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor NonGeneratedCodeDescriptor = new DiagnosticDescriptor( "UserCodeDiagnostic", "Title2", "UserCodeDiagnostic {0}", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor UniqueTextFileDescriptor = new DiagnosticDescriptor( "UniqueTextFileDiagnostic", "Title3", "UniqueTextFileDiagnostic {0}", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor NumberOfUniqueTextFileDescriptor = new DiagnosticDescriptor( "NumberOfUniqueTextFileDescriptor", "Title4", "NumberOfUniqueTextFileDescriptor {0}", "Category", DiagnosticSeverity.Warning, true); public SharedStateAnalyzer() { _treeValueProvider = new SyntaxTreeValueProvider<bool>(IsGeneratedCode); _treeCallbackSet = new HashSet<SyntaxTree>(SyntaxTreeComparer.Instance); _textValueProvider = new SourceTextValueProvider<int>(GetCharacterCount); _textCallbackSet = new HashSet<SourceText>(SourceTextComparer.Instance); } private bool IsGeneratedCode(SyntaxTree tree) { lock (_treeCallbackSet) { if (!_treeCallbackSet.Add(tree)) { throw new Exception("Expected driver to make a single callback per tree"); } } var fileNameWithoutExtension = PathUtilities.GetFileName(tree.FilePath, includeExtension: false); return fileNameWithoutExtension.EndsWith(".designer", StringComparison.OrdinalIgnoreCase) || fileNameWithoutExtension.EndsWith(".generated", StringComparison.OrdinalIgnoreCase); } private int GetCharacterCount(SourceText text) { lock (_textCallbackSet) { if (!_textCallbackSet.Add(text)) { throw new Exception("Expected driver to make a single callback per text"); } } return text.Length; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(GeneratedCodeDescriptor, NonGeneratedCodeDescriptor, UniqueTextFileDescriptor, NumberOfUniqueTextFileDescriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); } private void OnCompilationStart(CompilationStartAnalysisContext context) { context.RegisterSymbolAction(symbolContext => { var descriptor = GeneratedCodeDescriptor; foreach (var location in symbolContext.Symbol.Locations) { context.TryGetValue(location.SourceTree, _treeValueProvider, out var isGeneratedCode); if (!isGeneratedCode) { descriptor = NonGeneratedCodeDescriptor; break; } } var diagnostic = Diagnostic.Create(descriptor, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name); symbolContext.ReportDiagnostic(diagnostic); }, SymbolKind.NamedType); context.RegisterSyntaxTreeAction(treeContext => { context.TryGetValue(treeContext.Tree, _treeValueProvider, out var isGeneratedCode); var descriptor = isGeneratedCode ? GeneratedCodeDescriptor : NonGeneratedCodeDescriptor; var diagnostic = Diagnostic.Create(descriptor, Location.None, treeContext.Tree.FilePath); treeContext.ReportDiagnostic(diagnostic); context.TryGetValue(treeContext.Tree.GetText(), _textValueProvider, out var length); diagnostic = Diagnostic.Create(UniqueTextFileDescriptor, Location.None, treeContext.Tree.FilePath); treeContext.ReportDiagnostic(diagnostic); }); context.RegisterCompilationEndAction(endContext => { if (_treeCallbackSet.Count != endContext.Compilation.SyntaxTrees.Count()) { throw new Exception("Expected driver to make a callback for every tree"); } var diagnostic = Diagnostic.Create(NumberOfUniqueTextFileDescriptor, Location.None, _textCallbackSet.Count); endContext.ReportDiagnostic(diagnostic); }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AnalyzerForParameters : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ParameterDescriptor = new DiagnosticDescriptor( "Parameter_ID", "Parameter_Title", "Parameter_Message", "Parameter_Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ParameterDescriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(SymbolAction, SymbolKind.Parameter); } private void SymbolAction(SymbolAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(ParameterDescriptor, context.Symbol.Locations[0])); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class SymbolStartAnalyzer : DiagnosticAnalyzer { private readonly SymbolKind _symbolKind; private readonly bool _topLevelAction; private readonly OperationKind? _operationKind; private readonly string _analyzerId; public SymbolStartAnalyzer(bool topLevelAction, SymbolKind symbolKind, OperationKind? operationKindOpt = null, int? analyzerId = null) { _topLevelAction = topLevelAction; _symbolKind = symbolKind; _operationKind = operationKindOpt; _analyzerId = $"Analyzer{(analyzerId.HasValue ? analyzerId.Value : 1)}"; SymbolsStarted = new ConcurrentSet<ISymbol>(); } internal ConcurrentSet<ISymbol> SymbolsStarted { get; } public static readonly DiagnosticDescriptor SymbolStartTopLevelRule = new DiagnosticDescriptor( "SymbolStartTopLevelRuleId", "SymbolStartTopLevelRuleTitle", "Symbol : {0}, Analyzer: {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor SymbolStartCompilationLevelRule = new DiagnosticDescriptor( "SymbolStartRuleId", "SymbolStartRuleTitle", "Symbol : {0}, Analyzer: {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor SymbolStartedEndedDifferRule = new DiagnosticDescriptor( "SymbolStartedEndedDifferRuleId", "SymbolStartedEndedDifferRuleTitle", "Symbols Started: '{0}', Symbols Ended: '{1}', Analyzer: {2}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor SymbolStartedOrderingRule = new DiagnosticDescriptor( "SymbolStartedOrderingRuleId", "SymbolStartedOrderingRuleTitle", "Member '{0}' started before container '{1}', Analyzer: {2}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor SymbolEndedOrderingRule = new DiagnosticDescriptor( "SymbolEndedOrderingRuleId", "SymbolEndedOrderingRuleTitle", "Container '{0}' ended before member '{1}', Analyzer: {2}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OperationOrderingRule = new DiagnosticDescriptor( "OperationOrderingRuleId", "OperationOrderingRuleTitle", "Container '{0}' started after operation '{1}', Analyzer: {2}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor DuplicateStartActionRule = new DiagnosticDescriptor( "DuplicateStartActionRuleId", "DuplicateStartActionRuleTitle", "Symbol : {0}, Analyzer: {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor DuplicateEndActionRule = new DiagnosticDescriptor( "DuplicateEndActionRuleId", "DuplicateEndActionRuleTitle", "Symbol : {0}, Analyzer: {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OperationRule = new DiagnosticDescriptor( "OperationRuleId", "OperationRuleTitle", "Symbol Started: '{0}', Owning Symbol: '{1}' Operation : {2}, Analyzer: {3}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create( SymbolStartTopLevelRule, SymbolStartCompilationLevelRule, SymbolStartedEndedDifferRule, SymbolStartedOrderingRule, SymbolEndedOrderingRule, DuplicateStartActionRule, DuplicateEndActionRule, OperationRule, OperationOrderingRule); } } public override void Initialize(AnalysisContext context) { var diagnostics = new ConcurrentBag<Diagnostic>(); var symbolsEnded = new ConcurrentSet<ISymbol>(); var seenOperationContainers = new ConcurrentDictionary<OperationAnalysisContext, ISet<ISymbol>>(); if (_topLevelAction) { context.RegisterSymbolStartAction(onSymbolStart, _symbolKind); context.RegisterCompilationStartAction(compilationStartContext => { compilationStartContext.RegisterCompilationEndAction(compilationEndContext => { reportDiagnosticsAtCompilationEnd(compilationEndContext); }); }); } else { context.RegisterCompilationStartAction(compilationStartContext => { compilationStartContext.RegisterSymbolStartAction(onSymbolStart, _symbolKind); compilationStartContext.RegisterCompilationEndAction(compilationEndContext => { reportDiagnosticsAtCompilationEnd(compilationEndContext); }); }); } return; void onSymbolStart(SymbolStartAnalysisContext symbolStartContext) { performSymbolStartActionVerification(symbolStartContext); if (_operationKind.HasValue) { symbolStartContext.RegisterOperationAction(operationContext => { performOperationActionVerification(operationContext, symbolStartContext); }, _operationKind.Value); } symbolStartContext.RegisterSymbolEndAction(symbolEndContext => { performSymbolEndActionVerification(symbolEndContext, symbolStartContext); }); } void reportDiagnosticsAtCompilationEnd(CompilationAnalysisContext compilationEndContext) { if (!SymbolsStarted.SetEquals(symbolsEnded)) { // Symbols Started: '{0}', Symbols Ended: '{1}', Analyzer: {2} var symbolsStartedStr = string.Join(", ", SymbolsStarted.Select(s => s.ToDisplayString()).Order()); var symbolsEndedStr = string.Join(", ", symbolsEnded.Select(s => s.ToDisplayString()).Order()); compilationEndContext.ReportDiagnostic(Diagnostic.Create(SymbolStartedEndedDifferRule, Location.None, symbolsStartedStr, symbolsEndedStr, _analyzerId)); } foreach (var diagnostic in diagnostics) { compilationEndContext.ReportDiagnostic(diagnostic); } } void performSymbolStartActionVerification(SymbolStartAnalysisContext symbolStartContext) { verifySymbolStartOrdering(symbolStartContext); verifySymbolStartAndOperationOrdering(symbolStartContext); if (!SymbolsStarted.Add(symbolStartContext.Symbol)) { diagnostics.Add(Diagnostic.Create(DuplicateStartActionRule, Location.None, symbolStartContext.Symbol.Name, _analyzerId)); } } void performSymbolEndActionVerification(SymbolAnalysisContext symbolEndContext, SymbolStartAnalysisContext symbolStartContext) { Assert.Equal(symbolStartContext.Symbol, symbolEndContext.Symbol); verifySymbolEndOrdering(symbolEndContext); if (!symbolsEnded.Add(symbolEndContext.Symbol)) { diagnostics.Add(Diagnostic.Create(DuplicateEndActionRule, Location.None, symbolEndContext.Symbol.Name, _analyzerId)); } Assert.False(symbolEndContext.Symbol.IsImplicitlyDeclared); var rule = _topLevelAction ? SymbolStartTopLevelRule : SymbolStartCompilationLevelRule; symbolEndContext.ReportDiagnostic(Diagnostic.Create(rule, Location.None, symbolStartContext.Symbol.Name, _analyzerId)); } void performOperationActionVerification(OperationAnalysisContext operationContext, SymbolStartAnalysisContext symbolStartContext) { var containingSymbols = GetContainingSymbolsAndThis(operationContext.ContainingSymbol).ToSet(); seenOperationContainers.Add(operationContext, containingSymbols); Assert.Contains(symbolStartContext.Symbol, containingSymbols); Assert.All(containingSymbols, s => Assert.DoesNotContain(s, symbolsEnded)); // Symbol Started: '{0}', Owning Symbol: '{1}' Operation : {2}, Analyzer: {3} operationContext.ReportDiagnostic(Diagnostic.Create(OperationRule, Location.None, symbolStartContext.Symbol.Name, operationContext.ContainingSymbol.Name, operationContext.Operation.Syntax.ToString(), _analyzerId)); } IEnumerable<ISymbol> GetContainingSymbolsAndThis(ISymbol symbol) { do { yield return symbol; symbol = symbol.ContainingSymbol; } while (symbol != null && !symbol.IsImplicitlyDeclared); } void verifySymbolStartOrdering(SymbolStartAnalysisContext symbolStartContext) { ISymbol symbolStarted = symbolStartContext.Symbol; IEnumerable<ISymbol> members; switch (symbolStarted) { case INamedTypeSymbol namedType: members = namedType.GetMembers(); break; case INamespaceSymbol namespaceSym: members = namespaceSym.GetMembers(); break; default: return; } foreach (var member in members.Where(m => !m.IsImplicitlyDeclared)) { if (SymbolsStarted.Contains(member)) { // Member '{0}' started before container '{1}', Analyzer {2} diagnostics.Add(Diagnostic.Create(SymbolStartedOrderingRule, Location.None, member, symbolStarted, _analyzerId)); } } } void verifySymbolEndOrdering(SymbolAnalysisContext symbolEndContext) { ISymbol symbolEnded = symbolEndContext.Symbol; IList<ISymbol> containersToVerify = new List<ISymbol>(); if (symbolEnded.ContainingType != null) { containersToVerify.Add(symbolEnded.ContainingType); } if (symbolEnded.ContainingNamespace != null) { containersToVerify.Add(symbolEnded.ContainingNamespace); } foreach (var container in containersToVerify) { if (symbolsEnded.Contains(container)) { // Container '{0}' ended before member '{1}', Analyzer {2} diagnostics.Add(Diagnostic.Create(SymbolEndedOrderingRule, Location.None, container, symbolEnded, _analyzerId)); } } } void verifySymbolStartAndOperationOrdering(SymbolStartAnalysisContext symbolStartContext) { foreach (var kvp in seenOperationContainers) { OperationAnalysisContext operationContext = kvp.Key; ISet<ISymbol> containers = kvp.Value; if (containers.Contains(symbolStartContext.Symbol)) { // Container '{0}' started after operation '{1}', Analyzer {2} diagnostics.Add(Diagnostic.Create(OperationOrderingRule, Location.None, symbolStartContext.Symbol, operationContext.Operation.Syntax.ToString(), _analyzerId)); } } } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressorForId : DiagnosticSuppressor { public SuppressionDescriptor SuppressionDescriptor { get; } public DiagnosticSuppressorForId(string suppressedDiagnosticId, string suppressionId = null) { SuppressionDescriptor = new SuppressionDescriptor( id: suppressionId ?? "SPR0001", suppressedDiagnosticId: suppressedDiagnosticId, justification: $"Suppress {suppressedDiagnosticId}"); } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(SuppressionDescriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { foreach (var diagnostic in context.ReportedDiagnostics) { Assert.Equal(SuppressionDescriptor.SuppressedDiagnosticId, diagnostic.Id); context.ReportSuppression(Suppression.Create(SuppressionDescriptor, diagnostic)); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressorForId_ThrowsOperationCancelledException : DiagnosticSuppressor { public CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource(); public SuppressionDescriptor SuppressionDescriptor { get; } public DiagnosticSuppressorForId_ThrowsOperationCancelledException(string suppressedDiagnosticId) { SuppressionDescriptor = new SuppressionDescriptor( id: "SPR0001", suppressedDiagnosticId: suppressedDiagnosticId, justification: $"Suppress {suppressedDiagnosticId}"); } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(SuppressionDescriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { CancellationTokenSource.Cancel(); context.CancellationToken.ThrowIfCancellationRequested(); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressorThrowsExceptionFromSupportedSuppressions : DiagnosticSuppressor { private readonly NotImplementedException _exception; public DiagnosticSuppressorThrowsExceptionFromSupportedSuppressions(NotImplementedException exception) { _exception = exception; } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => throw _exception; public override void ReportSuppressions(SuppressionAnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressorThrowsExceptionFromReportedSuppressions : DiagnosticSuppressor { private readonly SuppressionDescriptor _descriptor; private readonly NotImplementedException _exception; public DiagnosticSuppressorThrowsExceptionFromReportedSuppressions(string suppressedDiagnosticId, NotImplementedException exception) { _descriptor = new SuppressionDescriptor( "SPR0001", suppressedDiagnosticId, $"Suppress {suppressedDiagnosticId}"); _exception = exception; } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(_descriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { throw _exception; } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressor_UnsupportedSuppressionReported : DiagnosticSuppressor { private readonly SuppressionDescriptor _supportedDescriptor; private readonly SuppressionDescriptor _unsupportedDescriptor; public DiagnosticSuppressor_UnsupportedSuppressionReported(string suppressedDiagnosticId, string supportedSuppressionId, string unsupportedSuppressionId) { _supportedDescriptor = new SuppressionDescriptor( supportedSuppressionId, suppressedDiagnosticId, $"Suppress {suppressedDiagnosticId}"); _unsupportedDescriptor = new SuppressionDescriptor( unsupportedSuppressionId, suppressedDiagnosticId, $"Suppress {suppressedDiagnosticId}"); } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(_supportedDescriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { foreach (var diagnostic in context.ReportedDiagnostics) { Assert.Equal(_unsupportedDescriptor.SuppressedDiagnosticId, diagnostic.Id); context.ReportSuppression(Suppression.Create(_unsupportedDescriptor, diagnostic)); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressor_InvalidDiagnosticSuppressionReported : DiagnosticSuppressor { private readonly SuppressionDescriptor _supportedDescriptor; private readonly SuppressionDescriptor _unsupportedDescriptor; public DiagnosticSuppressor_InvalidDiagnosticSuppressionReported(string suppressedDiagnosticId, string unsupportedSuppressedDiagnosticId) { _supportedDescriptor = new SuppressionDescriptor( "SPR0001", suppressedDiagnosticId, $"Suppress {suppressedDiagnosticId}"); _unsupportedDescriptor = new SuppressionDescriptor( "SPR0002", unsupportedSuppressedDiagnosticId, $"Suppress {unsupportedSuppressedDiagnosticId}"); } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(_supportedDescriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { foreach (var diagnostic in context.ReportedDiagnostics) { Assert.Equal(_supportedDescriptor.SuppressedDiagnosticId, diagnostic.Id); context.ReportSuppression(Suppression.Create(_unsupportedDescriptor, diagnostic)); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressor_NonReportedDiagnosticCannotBeSuppressed : DiagnosticSuppressor { private readonly SuppressionDescriptor _descriptor1, _descriptor2; private readonly string _nonReportedDiagnosticId; public DiagnosticSuppressor_NonReportedDiagnosticCannotBeSuppressed(string reportedDiagnosticId, string nonReportedDiagnosticId) { _descriptor1 = new SuppressionDescriptor( "SPR0001", reportedDiagnosticId, $"Suppress {reportedDiagnosticId}"); _descriptor2 = new SuppressionDescriptor( "SPR0002", nonReportedDiagnosticId, $"Suppress {nonReportedDiagnosticId}"); _nonReportedDiagnosticId = nonReportedDiagnosticId; } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(_descriptor1, _descriptor2); public override void ReportSuppressions(SuppressionAnalysisContext context) { var nonReportedDiagnostic = Diagnostic.Create( id: _nonReportedDiagnosticId, category: "Category", message: "Message", severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 1); context.ReportSuppression(Suppression.Create(_descriptor2, nonReportedDiagnostic)); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class NamedTypeAnalyzer : DiagnosticAnalyzer { public enum AnalysisKind { Symbol, SymbolStartEnd, CompilationStartEnd } public const string RuleId = "ID1"; public const string RuleCategory = "Category1"; private readonly DiagnosticDescriptor _rule; private readonly AnalysisKind _analysisKind; private readonly GeneratedCodeAnalysisFlags _analysisFlags; private readonly ConcurrentSet<ISymbol> _symbolCallbacks; public NamedTypeAnalyzer(AnalysisKind analysisKind, GeneratedCodeAnalysisFlags analysisFlags = GeneratedCodeAnalysisFlags.None, bool configurable = true) { _analysisKind = analysisKind; _analysisFlags = analysisFlags; _symbolCallbacks = new ConcurrentSet<ISymbol>(); var customTags = configurable ? Array.Empty<string>() : new[] { WellKnownDiagnosticTags.NotConfigurable }; _rule = new DiagnosticDescriptor( RuleId, "Title1", "Symbol: {0}", RuleCategory, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: customTags); } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public string GetSortedSymbolCallbacksString() => string.Join(", ", _symbolCallbacks.Select(s => s.Name).Order()); public override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(_analysisFlags); switch (_analysisKind) { case AnalysisKind.Symbol: context.RegisterSymbolAction(c => { _symbolCallbacks.Add(c.Symbol); ReportDiagnostic(c.Symbol, c.ReportDiagnostic); }, SymbolKind.NamedType); break; case AnalysisKind.SymbolStartEnd: context.RegisterSymbolStartAction(symbolStartContext => { symbolStartContext.RegisterSymbolEndAction(symbolEndContext => { _symbolCallbacks.Add(symbolEndContext.Symbol); ReportDiagnostic(symbolEndContext.Symbol, symbolEndContext.ReportDiagnostic); }); }, SymbolKind.NamedType); break; case AnalysisKind.CompilationStartEnd: context.RegisterCompilationStartAction(compilationStartContext => { compilationStartContext.RegisterSymbolAction(c => { _symbolCallbacks.Add(c.Symbol); }, SymbolKind.NamedType); compilationStartContext.RegisterCompilationEndAction( compilationEndContext => compilationEndContext.ReportDiagnostic( Diagnostic.Create(_rule, Location.None, GetSortedSymbolCallbacksString()))); }); break; } } private void ReportDiagnostic(ISymbol symbol, Action<Diagnostic> reportDiagnostic) => reportDiagnostic(Diagnostic.Create(_rule, symbol.Locations[0], symbol.Name)); } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithNoLocationDiagnostics : DiagnosticAnalyzer { public AnalyzerWithNoLocationDiagnostics(bool isEnabledByDefault) { Descriptor = new DiagnosticDescriptor( "ID0001", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault); } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None))); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class NamedTypeAnalyzerWithConfigurableEnabledByDefault : DiagnosticAnalyzer { private readonly bool _throwOnAllNamedTypes; public NamedTypeAnalyzerWithConfigurableEnabledByDefault(bool isEnabledByDefault, DiagnosticSeverity defaultSeverity, bool throwOnAllNamedTypes = false) { Descriptor = new DiagnosticDescriptor( "ID0001", "Title1", "Message1", "Category1", defaultSeverity, isEnabledByDefault); _throwOnAllNamedTypes = throwOnAllNamedTypes; } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(context => { if (_throwOnAllNamedTypes) { throw new NotImplementedException(); } context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Symbol.Locations[0])); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class RegisterOperationBlockAndOperationActionAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor( "ID0001", "Title", "Message", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor); public override void Initialize(AnalysisContext analysisContext) { analysisContext.RegisterOperationAction(_ => { }, OperationKind.Invocation); analysisContext.RegisterOperationBlockStartAction(OnOperationBlockStart); } private void OnOperationBlockStart(OperationBlockStartAnalysisContext context) { context.RegisterOperationBlockEndAction( endContext => endContext.ReportDiagnostic(Diagnostic.Create(s_descriptor, context.OwningSymbol.Locations[0]))); } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class FieldAnalyzer : DiagnosticAnalyzer { private readonly bool _syntaxTreeAction; public FieldAnalyzer(string diagnosticId, bool syntaxTreeAction) { _syntaxTreeAction = syntaxTreeAction; Descriptor = new DiagnosticDescriptor( diagnosticId, "Title", "Message", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { if (_syntaxTreeAction) { context.RegisterSyntaxTreeAction(context => { var fields = context.Tree.GetRoot().DescendantNodes().OfType<CSharp.Syntax.FieldDeclarationSyntax>(); foreach (var variable in fields.SelectMany(f => f.Declaration.Variables)) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, variable.Identifier.GetLocation())); } }); } else { context.RegisterSymbolAction( context => context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Symbol.Locations[0])), SymbolKind.Field); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AdditionalFileAnalyzer : DiagnosticAnalyzer { private readonly bool _registerFromInitialize; private readonly TextSpan _diagnosticSpan; public AdditionalFileAnalyzer(bool registerFromInitialize, TextSpan diagnosticSpan, string id = "ID0001") { _registerFromInitialize = registerFromInitialize; _diagnosticSpan = diagnosticSpan; Descriptor = new DiagnosticDescriptor( id, "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { if (_registerFromInitialize) { context.RegisterAdditionalFileAction(AnalyzeAdditionalFile); } else { context.RegisterCompilationStartAction(context => context.RegisterAdditionalFileAction(AnalyzeAdditionalFile)); } } private void AnalyzeAdditionalFile(AdditionalFileAnalysisContext context) { if (context.AdditionalFile.Path == null) { return; } var text = context.AdditionalFile.GetText(); var location = Location.Create(context.AdditionalFile.Path, _diagnosticSpan, text.Lines.GetLinePositionSpan(_diagnosticSpan)); context.ReportDiagnostic(Diagnostic.Create(Descriptor, location)); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class RegisterSyntaxTreeCancellationAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "ID0001"; private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor( DiagnosticId, "Title", "Message", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); public CancellationToken CancellationToken => _cancellationTokenSource.Token; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxTreeAction(context => { // Mimic cancellation by throwing an OperationCanceledException in first callback. if (!_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource.Cancel(); while (true) { context.CancellationToken.ThrowIfCancellationRequested(); } throw ExceptionUtilities.Unreachable; } context.ReportDiagnostic(Diagnostic.Create(s_descriptor, context.Tree.GetRoot().GetLocation())); }); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis { public static class CommonDiagnosticAnalyzers { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AnalyzerForErrorLogTest : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor( "ID1", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "Description1", helpLinkUri: "HelpLink1", customTags: new[] { "1_CustomTag1", "1_CustomTag2" }); public static readonly DiagnosticDescriptor Descriptor2 = new DiagnosticDescriptor( "ID2", "Title2", "Message2", "Category2", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true, description: "Description2", helpLinkUri: "HelpLink2", customTags: new[] { "2_CustomTag1", "2_CustomTag2" }); private static readonly ImmutableDictionary<string, string> s_properties = new Dictionary<string, string> { { "Key1", "Value1" }, { "Key2", "Value2" } }.ToImmutableDictionary(); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1, Descriptor2); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => { // With location diagnostic. var location = compilationContext.Compilation.SyntaxTrees.First().GetRoot().GetLocation(); compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor1, location, s_properties)); // No location diagnostic. compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor2, Location.None, s_properties)); }); } private static string GetExpectedPropertiesMapText() { var expectedText = @" ""customProperties"": {"; foreach (var kvp in s_properties.OrderBy(kvp => kvp.Key)) { if (!expectedText.EndsWith("{")) { expectedText += ","; } expectedText += string.Format(@" ""{0}"": ""{1}""", kvp.Key, kvp.Value); } expectedText += @" }"; return expectedText; } public static string GetExpectedV1ErrorLogResultsAndRulesText(Compilation compilation) { var tree = compilation.SyntaxTrees.First(); var root = tree.GetRoot(); var expectedLineSpan = root.GetLocation().GetLineSpan(); var filePath = GetUriForPath(tree.FilePath); return @" ""results"": [ { ""ruleId"": """ + Descriptor1.Id + @""", ""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": """ + Descriptor1.MessageFormat + @""", ""locations"": [ { ""resultFile"": { ""uri"": """ + filePath + @""", ""region"": { ""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @", ""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @", ""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @", ""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @" } } } ], ""properties"": { ""warningLevel"": 1," + GetExpectedPropertiesMapText() + @" } }, { ""ruleId"": """ + Descriptor2.Id + @""", ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": """ + Descriptor2.MessageFormat + @""", ""properties"": {" + GetExpectedPropertiesMapText() + @" } } ], ""rules"": { """ + Descriptor1.Id + @""": { ""id"": """ + Descriptor1.Id + @""", ""shortDescription"": """ + Descriptor1.Title + @""", ""fullDescription"": """ + Descriptor1.Description + @""", ""defaultLevel"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""helpUri"": """ + Descriptor1.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor1.Category + @""", ""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @" ] } }, """ + Descriptor2.Id + @""": { ""id"": """ + Descriptor2.Id + @""", ""shortDescription"": """ + Descriptor2.Title + @""", ""fullDescription"": """ + Descriptor2.Description + @""", ""defaultLevel"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""helpUri"": """ + Descriptor2.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor2.Category + @""", ""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @" ] } } } } ] }"; } public static string GetExpectedV1ErrorLogWithSuppressionResultsAndRulesText(Compilation compilation) { var tree = compilation.SyntaxTrees.First(); var root = tree.GetRoot(); var expectedLineSpan = root.GetLocation().GetLineSpan(); var filePath = GetUriForPath(tree.FilePath); return @" ""results"": [ { ""ruleId"": """ + Descriptor1.Id + @""", ""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": """ + Descriptor1.MessageFormat + @""", ""suppressionStates"": [ ""suppressedInSource"" ], ""locations"": [ { ""resultFile"": { ""uri"": """ + filePath + @""", ""region"": { ""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @", ""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @", ""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @", ""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @" } } } ], ""properties"": { ""warningLevel"": 1," + GetExpectedPropertiesMapText() + @" } }, { ""ruleId"": """ + Descriptor2.Id + @""", ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": """ + Descriptor2.MessageFormat + @""", ""properties"": {" + GetExpectedPropertiesMapText() + @" } } ], ""rules"": { """ + Descriptor1.Id + @""": { ""id"": """ + Descriptor1.Id + @""", ""shortDescription"": """ + Descriptor1.Title + @""", ""fullDescription"": """ + Descriptor1.Description + @""", ""defaultLevel"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""helpUri"": """ + Descriptor1.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor1.Category + @""", ""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @" ] } }, """ + Descriptor2.Id + @""": { ""id"": """ + Descriptor2.Id + @""", ""shortDescription"": """ + Descriptor2.Title + @""", ""fullDescription"": """ + Descriptor2.Description + @""", ""defaultLevel"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""helpUri"": """ + Descriptor2.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor2.Category + @""", ""isEnabledByDefault"": " + (Descriptor2.IsEnabledByDefault ? "true" : "false") + @", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @" ] } } } } ] }"; } public static string GetExpectedV2ErrorLogResultsText(Compilation compilation) { var tree = compilation.SyntaxTrees.First(); var root = tree.GetRoot(); var expectedLineSpan = root.GetLocation().GetLineSpan(); var filePath = GetUriForPath(tree.FilePath); return @" ""results"": [ { ""ruleId"": """ + Descriptor1.Id + @""", ""ruleIndex"": 0, ""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": { ""text"": """ + Descriptor1.MessageFormat + @""" }, ""locations"": [ { ""physicalLocation"": { ""artifactLocation"": { ""uri"": """ + filePath + @""" }, ""region"": { ""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @", ""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @", ""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @", ""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @" } } } ], ""properties"": { ""warningLevel"": 1," + GetExpectedPropertiesMapText() + @" } }, { ""ruleId"": """ + Descriptor2.Id + @""", ""ruleIndex"": 1, ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": { ""text"": """ + Descriptor2.MessageFormat + @""" }, ""properties"": {" + GetExpectedPropertiesMapText() + @" } } ]"; } public static string GetExpectedV2ErrorLogWithSuppressionResultsText(Compilation compilation, string justification) { var tree = compilation.SyntaxTrees.First(); var root = tree.GetRoot(); var expectedLineSpan = root.GetLocation().GetLineSpan(); var filePath = GetUriForPath(tree.FilePath); return @" ""results"": [ { ""ruleId"": """ + Descriptor1.Id + @""", ""ruleIndex"": 0, ""level"": """ + (Descriptor1.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": { ""text"": """ + Descriptor1.MessageFormat + @""" }, ""suppressions"": [ { ""kind"": ""inSource""" + (justification == null ? "" : @", ""justification"": """ + (justification) + @"""") + @" } ], ""locations"": [ { ""physicalLocation"": { ""artifactLocation"": { ""uri"": """ + filePath + @""" }, ""region"": { ""startLine"": " + (expectedLineSpan.StartLinePosition.Line + 1) + @", ""startColumn"": " + (expectedLineSpan.StartLinePosition.Character + 1) + @", ""endLine"": " + (expectedLineSpan.EndLinePosition.Line + 1) + @", ""endColumn"": " + (expectedLineSpan.EndLinePosition.Character + 1) + @" } } } ], ""properties"": { ""warningLevel"": 1," + GetExpectedPropertiesMapText() + @" } }, { ""ruleId"": """ + Descriptor2.Id + @""", ""ruleIndex"": 1, ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""", ""message"": { ""text"": """ + Descriptor2.MessageFormat + @""" }, ""properties"": {" + GetExpectedPropertiesMapText() + @" } } ]"; } public static string GetExpectedV2ErrorLogRulesText() { return @" ""rules"": [ { ""id"": """ + Descriptor1.Id + @""", ""shortDescription"": { ""text"": """ + Descriptor1.Title + @""" }, ""fullDescription"": { ""text"": """ + Descriptor1.Description + @""" }, ""helpUri"": """ + Descriptor1.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor1.Category + @""", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor1.CustomTags.Select(s => $"\"{s}\"")) + @" ] } }, { ""id"": """ + Descriptor2.Id + @""", ""shortDescription"": { ""text"": """ + Descriptor2.Title + @""" }, ""fullDescription"": { ""text"": """ + Descriptor2.Description + @""" }, ""defaultConfiguration"": { ""level"": """ + (Descriptor2.DefaultSeverity == DiagnosticSeverity.Error ? "error" : "warning") + @""" }, ""helpUri"": """ + Descriptor2.HelpLinkUri + @""", ""properties"": { ""category"": """ + Descriptor2.Category + @""", ""tags"": [ " + String.Join("," + Environment.NewLine + " ", Descriptor2.CustomTags.Select(s => $"\"{s}\"")) + @" ] } } ]"; } public static string GetUriForPath(string path) { var uri = new Uri(path, UriKind.RelativeOrAbsolute); return uri.IsAbsoluteUri ? uri.AbsoluteUri : WebUtility.UrlEncode(uri.ToString()); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class NotConfigurableDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor EnabledRule = new DiagnosticDescriptor( "ID1", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.NotConfigurable); public static readonly DiagnosticDescriptor DisabledRule = new DiagnosticDescriptor( "ID2", "Title2", "Message2", "Category2", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: false, customTags: WellKnownDiagnosticTags.NotConfigurable); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(EnabledRule, DisabledRule); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => { // Report enabled diagnostic. compilationContext.ReportDiagnostic(Diagnostic.Create(EnabledRule, Location.None)); // Try to report disabled diagnostic. compilationContext.ReportDiagnostic(Diagnostic.Create(DisabledRule, Location.None)); }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CodeBlockActionAnalyzer : DiagnosticAnalyzer { private readonly bool _onlyStatelessAction; public CodeBlockActionAnalyzer(bool onlyStatelessAction = false) { _onlyStatelessAction = onlyStatelessAction; } public static readonly DiagnosticDescriptor CodeBlockTopLevelRule = new DiagnosticDescriptor( "CodeBlockTopLevelRuleId", "CodeBlockTopLevelRuleTitle", "CodeBlock : {0}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor CodeBlockPerCompilationRule = new DiagnosticDescriptor( "CodeBlockPerCompilationRuleId", "CodeBlockPerCompilationRuleTitle", "CodeBlock : {0}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(CodeBlockTopLevelRule, CodeBlockPerCompilationRule); } } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(codeBlockContext => { codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockTopLevelRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name)); }); if (!_onlyStatelessAction) { context.RegisterCompilationStartAction(compilationStartContext => { compilationStartContext.RegisterCodeBlockAction(codeBlockContext => { codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockPerCompilationRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name)); }); }); } } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class CSharpCodeBlockObjectCreationAnalyzer : CodeBlockObjectCreationAnalyzer<SyntaxKind> { protected override SyntaxKind ObjectCreationExpressionKind => SyntaxKind.ObjectCreationExpression; } [DiagnosticAnalyzer(LanguageNames.VisualBasic)] public class VisualBasicCodeBlockObjectCreationAnalyzer : CodeBlockObjectCreationAnalyzer<VisualBasic.SyntaxKind> { protected override VisualBasic.SyntaxKind ObjectCreationExpressionKind => VisualBasic.SyntaxKind.ObjectCreationExpression; } public abstract class CodeBlockObjectCreationAnalyzer<TLanguageKindEnum> : DiagnosticAnalyzer where TLanguageKindEnum : struct { public static readonly DiagnosticDescriptor DiagnosticDescriptor = new DiagnosticDescriptor( "Id", "Title", "Message", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DiagnosticDescriptor); protected abstract TLanguageKindEnum ObjectCreationExpressionKind { get; } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<TLanguageKindEnum>(codeBlockStartContext => { codeBlockStartContext.RegisterSyntaxNodeAction(syntaxNodeContext => { syntaxNodeContext.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptor, syntaxNodeContext.Node.GetLocation())); }, ObjectCreationExpressionKind); }); } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class CSharpGenericNameAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = nameof(DiagnosticId); public const string Title = nameof(Title); public const string Message = nameof(Message); public const string Category = nameof(Category); public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, Severity, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.GenericName); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation())); } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class CSharpNamespaceDeclarationAnalyzer : AbstractNamespaceDeclarationAnalyzer<SyntaxKind> { protected override SyntaxKind NamespaceDeclarationSyntaxKind => SyntaxKind.NamespaceDeclaration; } [DiagnosticAnalyzer(LanguageNames.VisualBasic)] public class VisualBasicNamespaceDeclarationAnalyzer : AbstractNamespaceDeclarationAnalyzer<VisualBasic.SyntaxKind> { protected override VisualBasic.SyntaxKind NamespaceDeclarationSyntaxKind => VisualBasic.SyntaxKind.NamespaceStatement; } public abstract class AbstractNamespaceDeclarationAnalyzer<TLanguageKindEnum> : DiagnosticAnalyzer where TLanguageKindEnum : struct { public const string DiagnosticId = nameof(DiagnosticId); public const string Title = nameof(Title); public const string Message = nameof(Message); public const string Category = nameof(Category); public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, Severity, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); protected abstract TLanguageKindEnum NamespaceDeclarationSyntaxKind { get; } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, NamespaceDeclarationSyntaxKind); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation())); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithNoActions : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor DummyRule = new DiagnosticDescriptor( "ID1", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DummyRule); public override void Initialize(AnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithDisabledRules : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( "ID1", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(_ => { }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class EnsureNoMergedNamespaceSymbolAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = nameof(DiagnosticId); public const string Title = nameof(Title); public const string Message = nameof(Message); public const string Category = nameof(Category); public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, Severity, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Namespace); } private void AnalyzeSymbol(SymbolAnalysisContext context) { // Ensure we are not invoked for merged namespace symbol, but instead for constituent namespace scoped to the source assembly. var ns = (INamespaceSymbol)context.Symbol; if (ns.ContainingAssembly != context.Compilation.Assembly || ns.ConstituentNamespaces.Length > 1) { context.ReportDiagnostic(Diagnostic.Create(Rule, ns.Locations[0])); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithNoSupportedDiagnostics : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public override void Initialize(AnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithInvalidDiagnosticId : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "Invalid ID", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None))); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithNullDescriptor : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create((DiagnosticDescriptor)null); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(_ => { }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithCSharpCompilerDiagnosticId : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( #pragma warning disable RS1029 // Do not use reserved diagnostic IDs. "CS101", #pragma warning restore RS1029 // Do not use reserved diagnostic IDs. "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None))); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithBasicCompilerDiagnosticId : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( #pragma warning disable RS1029 // Do not use reserved diagnostic IDs. "BC101", #pragma warning restore RS1029 // Do not use reserved diagnostic IDs. "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None))); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithInvalidDiagnosticSpan : DiagnosticAnalyzer { private readonly TextSpan _badSpan; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title1", "Message", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public AnalyzerWithInvalidDiagnosticSpan(TextSpan badSpan) => _badSpan = badSpan; public Exception ThrownException { get; set; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxTreeAction(c => { try { ThrownException = null; c.ReportDiagnostic(Diagnostic.Create(Descriptor, SourceLocation.Create(c.Tree, _badSpan))); } catch (Exception e) { ThrownException = e; throw; } }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithInvalidDiagnosticLocation : DiagnosticAnalyzer { private readonly Location _invalidLocation; private readonly ActionKind _actionKind; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title1", "Message {0}", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public enum ActionKind { Symbol, CodeBlock, Operation, OperationBlockEnd, Compilation, CompilationEnd, SyntaxTree } public AnalyzerWithInvalidDiagnosticLocation(SyntaxTree treeInAnotherCompilation, ActionKind actionKind) { _invalidLocation = treeInAnotherCompilation.GetRoot().GetLocation(); _actionKind = actionKind; } private void ReportDiagnostic(Action<Diagnostic> addDiagnostic, ActionKind actionKindBeingRun) { if (_actionKind == actionKindBeingRun) { var diagnostic = Diagnostic.Create(Descriptor, _invalidLocation); addDiagnostic(diagnostic); } } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(cc => { cc.RegisterSymbolAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.Symbol), SymbolKind.NamedType); cc.RegisterCodeBlockAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.CodeBlock)); cc.RegisterCompilationEndAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.CompilationEnd)); cc.RegisterOperationBlockStartAction(oc => { oc.RegisterOperationAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.Operation), OperationKind.VariableDeclarationGroup); oc.RegisterOperationBlockEndAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.OperationBlockEnd)); }); }); context.RegisterSyntaxTreeAction(c => ReportDiagnostic(c.ReportDiagnostic, ActionKind.SyntaxTree)); context.RegisterCompilationAction(cc => ReportDiagnostic(cc.ReportDiagnostic, ActionKind.Compilation)); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerThatThrowsInSupportedDiagnostics : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(); public override void Initialize(AnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerThatThrowsInGetMessage : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( "ID1", "Title1", new MyLocalizableStringThatThrows(), "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(symbolContext => { symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0])); }, SymbolKind.NamedType); } private sealed class MyLocalizableStringThatThrows : LocalizableString { protected override bool AreEqual(object other) { return ReferenceEquals(this, other); } protected override int GetHash() { return 0; } protected override string GetText(IFormatProvider formatProvider) { throw new NotImplementedException(); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerReportingMisformattedDiagnostic : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( "ID1", "Title1", "Symbol Name: {0}, Extra argument: {1}", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(symbolContext => { // Report diagnostic with incorrect number of message format arguments. symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name)); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class CompilationAnalyzerWithSeverity : DiagnosticAnalyzer { public const string DiagnosticId = "ID1000"; public CompilationAnalyzerWithSeverity( DiagnosticSeverity severity, bool configurable) { var customTags = !configurable ? new[] { WellKnownDiagnosticTags.NotConfigurable } : Array.Empty<string>(); Descriptor = new DiagnosticDescriptor( DiagnosticId, "Description1", string.Empty, "Analysis", severity, true, customTags: customTags); } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(this.OnCompilation); } private void OnCompilation(CompilationAnalysisContext context) { // Report the diagnostic on all trees in compilation. foreach (var tree in context.Compilation.SyntaxTrees) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, tree.GetRoot().GetLocation())); } } } /// <summary> /// This analyzer is intended to be used only when concurrent execution is enabled for analyzers. /// This analyzer will deadlock if the driver runs analyzers on a single thread OR takes a lock around callbacks into this analyzer to prevent concurrent analyzer execution /// Former indicates a bug in the test using this analyzer and the latter indicates a bug in the analyzer driver. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class ConcurrentAnalyzer : DiagnosticAnalyzer { private readonly ImmutableHashSet<string> _symbolNames; private int _token; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ConcurrentAnalyzerId", "Title", "ConcurrentAnalyzerMessage for symbol '{0}'", "Category", DiagnosticSeverity.Warning, true); public ConcurrentAnalyzer(IEnumerable<string> symbolNames) { Assert.True(Environment.ProcessorCount > 1, "This analyzer is intended to be used only in a concurrent environment."); _symbolNames = symbolNames.ToImmutableHashSet(); _token = 0; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); // Enable concurrent action callbacks on analyzer. context.EnableConcurrentExecution(); } private void OnCompilationStart(CompilationStartAnalysisContext context) { Assert.True(context.Compilation.Options.ConcurrentBuild, "This analyzer is intended to be used only when concurrent build is enabled."); var pendingSymbols = new ConcurrentSet<INamedTypeSymbol>(); foreach (var type in context.Compilation.GlobalNamespace.GetTypeMembers()) { if (_symbolNames.Contains(type.Name)) { pendingSymbols.Add(type); } } context.RegisterSymbolAction(symbolContext => { if (!pendingSymbols.Remove((INamedTypeSymbol)symbolContext.Symbol)) { return; } var myToken = Interlocked.Increment(ref _token); if (myToken == 1) { // Wait for all symbol callbacks to execute. // This analyzer will deadlock if the driver doesn't attempt concurrent callbacks. while (pendingSymbols.Any()) { Thread.Sleep(10); } } // ok, now report diagnostic on the symbol. var diagnostic = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name); symbolContext.ReportDiagnostic(diagnostic); }, SymbolKind.NamedType); } } /// <summary> /// This analyzer will report diagnostics only if it receives any concurrent action callbacks, which would be a /// bug in the analyzer driver as this analyzer doesn't invoke <see cref="AnalysisContext.EnableConcurrentExecution"/>. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class NonConcurrentAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "NonConcurrentAnalyzerId", "Title", "Analyzer driver made concurrent action callbacks, when analyzer didn't register for concurrent execution", "Category", DiagnosticSeverity.Warning, true); private const int registeredActionCounts = 1000; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { SemaphoreSlim gate = new SemaphoreSlim(initialCount: registeredActionCounts); for (var i = 0; i < registeredActionCounts; i++) { context.RegisterSymbolAction(symbolContext => { using (gate.DisposableWait(symbolContext.CancellationToken)) { ReportDiagnosticIfActionInvokedConcurrently(gate, symbolContext); } }, SymbolKind.NamedType); } } private void ReportDiagnosticIfActionInvokedConcurrently(SemaphoreSlim gate, SymbolAnalysisContext symbolContext) { if (gate.CurrentCount != registeredActionCounts - 1) { var diagnostic = Diagnostic.Create(Descriptor, symbolContext.Symbol.Locations[0]); symbolContext.ReportDiagnostic(diagnostic); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class OperationAnalyzer : DiagnosticAnalyzer { private readonly ActionKind _actionKind; private readonly bool _verifyGetControlFlowGraph; private readonly ConcurrentDictionary<IOperation, (ControlFlowGraph Graph, ISymbol AssociatedSymbol)> _controlFlowGraphMapOpt; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title1", "{0} diagnostic", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public enum ActionKind { Operation, OperationInOperationBlockStart, OperationBlock, OperationBlockEnd } public OperationAnalyzer(ActionKind actionKind, bool verifyGetControlFlowGraph = false) { _actionKind = actionKind; _verifyGetControlFlowGraph = verifyGetControlFlowGraph; _controlFlowGraphMapOpt = verifyGetControlFlowGraph ? new ConcurrentDictionary<IOperation, (ControlFlowGraph, ISymbol)>() : null; } public ImmutableArray<(ControlFlowGraph Graph, ISymbol AssociatedSymbol)> GetControlFlowGraphs() { Assert.True(_verifyGetControlFlowGraph); return _controlFlowGraphMapOpt.Values.OrderBy(flowGraphAndSymbol => flowGraphAndSymbol.Graph.OriginalOperation.Syntax.SpanStart).ToImmutableArray(); } private void ReportDiagnostic(Action<Diagnostic> addDiagnostic, Location location) { var diagnostic = Diagnostic.Create(Descriptor, location, _actionKind); addDiagnostic(diagnostic); } private void CacheAndVerifyControlFlowGraph(ImmutableArray<IOperation> operationBlocks, Func<IOperation, (ControlFlowGraph Graph, ISymbol AssociatedSymbol)> getControlFlowGraph) { if (_verifyGetControlFlowGraph) { foreach (var operationBlock in operationBlocks) { var controlFlowGraphAndSymbol = getControlFlowGraph(operationBlock); Assert.NotNull(controlFlowGraphAndSymbol); Assert.Same(operationBlock.GetRootOperation(), controlFlowGraphAndSymbol.Graph.OriginalOperation); _controlFlowGraphMapOpt.Add(controlFlowGraphAndSymbol.Graph.OriginalOperation, controlFlowGraphAndSymbol); // Verify analyzer driver caches the flow graph. Assert.Same(controlFlowGraphAndSymbol.Graph, getControlFlowGraph(operationBlock).Graph); // Verify exceptions for invalid inputs. try { _ = getControlFlowGraph(null); } catch (ArgumentNullException ex) { Assert.Equal(new ArgumentNullException("operationBlock").Message, ex.Message); } try { _ = getControlFlowGraph(operationBlock.Descendants().First()); } catch (ArgumentException ex) { Assert.Equal(new ArgumentException(CodeAnalysisResources.InvalidOperationBlockForAnalysisContext, "operationBlock").Message, ex.Message); } } } } private void VerifyControlFlowGraph(OperationAnalysisContext operationContext, bool inBlockAnalysisContext) { if (_verifyGetControlFlowGraph) { var controlFlowGraph = operationContext.GetControlFlowGraph(); Assert.NotNull(controlFlowGraph); // Verify analyzer driver caches the flow graph. Assert.Same(controlFlowGraph, operationContext.GetControlFlowGraph()); var rootOperation = operationContext.Operation.GetRootOperation(); if (inBlockAnalysisContext) { // Verify same flow graph returned from containing block analysis context. Assert.Same(controlFlowGraph, _controlFlowGraphMapOpt[rootOperation].Graph); } else { _controlFlowGraphMapOpt[rootOperation] = (controlFlowGraph, operationContext.ContainingSymbol); } } } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { switch (_actionKind) { case ActionKind.OperationBlockEnd: context.RegisterOperationBlockStartAction(blockStartContext => { blockStartContext.RegisterOperationBlockEndAction(c => ReportDiagnostic(c.ReportDiagnostic, c.OwningSymbol.Locations[0])); CacheAndVerifyControlFlowGraph(blockStartContext.OperationBlocks, op => (blockStartContext.GetControlFlowGraph(op), blockStartContext.OwningSymbol)); }); break; case ActionKind.OperationBlock: context.RegisterOperationBlockAction(blockContext => { ReportDiagnostic(blockContext.ReportDiagnostic, blockContext.OwningSymbol.Locations[0]); CacheAndVerifyControlFlowGraph(blockContext.OperationBlocks, op => (blockContext.GetControlFlowGraph(op), blockContext.OwningSymbol)); }); break; case ActionKind.Operation: context.RegisterOperationAction(operationContext => { ReportDiagnostic(operationContext.ReportDiagnostic, operationContext.Operation.Syntax.GetLocation()); VerifyControlFlowGraph(operationContext, inBlockAnalysisContext: false); }, OperationKind.Literal); break; case ActionKind.OperationInOperationBlockStart: context.RegisterOperationBlockStartAction(blockContext => { CacheAndVerifyControlFlowGraph(blockContext.OperationBlocks, op => (blockContext.GetControlFlowGraph(op), blockContext.OwningSymbol)); blockContext.RegisterOperationAction(operationContext => { ReportDiagnostic(operationContext.ReportDiagnostic, operationContext.Operation.Syntax.GetLocation()); VerifyControlFlowGraph(operationContext, inBlockAnalysisContext: true); }, OperationKind.Literal); }); break; } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class OperationBlockAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title1", "OperationBlock for {0}: {1}", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(c => { foreach (var operationRoot in c.OperationBlocks) { var diagnostic = Diagnostic.Create(Descriptor, c.OwningSymbol.Locations[0], c.OwningSymbol.Name, operationRoot.Kind); c.ReportDiagnostic(diagnostic); } }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class FieldReferenceOperationAnalyzer : DiagnosticAnalyzer { private readonly bool _doOperationBlockAnalysis; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title", "Field {0} = {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public FieldReferenceOperationAnalyzer(bool doOperationBlockAnalysis) { _doOperationBlockAnalysis = doOperationBlockAnalysis; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { if (_doOperationBlockAnalysis) { context.RegisterOperationBlockAction(operationBlockAnalysisContext => { foreach (var operationBlock in operationBlockAnalysisContext.OperationBlocks) { foreach (var operation in operationBlock.DescendantsAndSelf().OfType<IFieldReferenceOperation>()) { AnalyzerFieldReferenceOperation(operation, operationBlockAnalysisContext.ReportDiagnostic); } } }); } else { context.RegisterOperationAction(AnalyzerOperation, OperationKind.FieldReference); } } private static void AnalyzerOperation(OperationAnalysisContext operationAnalysisContext) { AnalyzerFieldReferenceOperation((IFieldReferenceOperation)operationAnalysisContext.Operation, operationAnalysisContext.ReportDiagnostic); } private static void AnalyzerFieldReferenceOperation(IFieldReferenceOperation operation, Action<Diagnostic> reportDiagnostic) { var diagnostic = Diagnostic.Create(Descriptor, operation.Syntax.GetLocation(), operation.Field.Name, operation.Field.ConstantValue); reportDiagnostic(diagnostic); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class MethodOrConstructorBodyOperationAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( "ID", "Title", "Method {0}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(operationContext => { var diagnostic = Diagnostic.Create(Descriptor, operationContext.Operation.Syntax.GetLocation(), operationContext.ContainingSymbol.Name); operationContext.ReportDiagnostic(diagnostic); }, OperationKind.MethodBody, OperationKind.ConstructorBody); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class GeneratedCodeAnalyzer : DiagnosticAnalyzer { private readonly GeneratedCodeAnalysisFlags? _generatedCodeAnalysisFlagsOpt; public static readonly DiagnosticDescriptor Warning = new DiagnosticDescriptor( "GeneratedCodeAnalyzerWarning", "Title", "GeneratedCodeAnalyzerMessage for '{0}'", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor Error = new DiagnosticDescriptor( "GeneratedCodeAnalyzerError", "Title", "GeneratedCodeAnalyzerMessage for '{0}'", "Category", DiagnosticSeverity.Error, true); public static readonly DiagnosticDescriptor Summary = new DiagnosticDescriptor( "GeneratedCodeAnalyzerSummary", "Title2", "GeneratedCodeAnalyzer received callbacks for: '{0}' types and '{1}' files", "Category", DiagnosticSeverity.Warning, true); public GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { _generatedCodeAnalysisFlagsOpt = generatedCodeAnalysisFlagsOpt; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Warning, Error, Summary); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); if (_generatedCodeAnalysisFlagsOpt.HasValue) { // Configure analysis on generated code. context.ConfigureGeneratedCodeAnalysis(_generatedCodeAnalysisFlagsOpt.Value); } } private void OnCompilationStart(CompilationStartAnalysisContext context) { var sortedCallbackSymbolNames = new SortedSet<string>(); var sortedCallbackTreePaths = new SortedSet<string>(); context.RegisterSymbolAction(symbolContext => { sortedCallbackSymbolNames.Add(symbolContext.Symbol.Name); ReportSymbolDiagnostics(symbolContext.Symbol, symbolContext.ReportDiagnostic); }, SymbolKind.NamedType); context.RegisterSyntaxTreeAction(treeContext => { sortedCallbackTreePaths.Add(treeContext.Tree.FilePath); ReportTreeDiagnostics(treeContext.Tree, treeContext.ReportDiagnostic); }); context.RegisterCompilationEndAction(endContext => { var arg1 = sortedCallbackSymbolNames.Join(","); var arg2 = sortedCallbackTreePaths.Join(","); // Summary diagnostics about received callbacks. var diagnostic = Diagnostic.Create(Summary, Location.None, arg1, arg2); endContext.ReportDiagnostic(diagnostic); }); } private void ReportSymbolDiagnostics(ISymbol symbol, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, symbol.Locations[0], symbol.Name); } private void ReportTreeDiagnostics(SyntaxTree tree, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, tree.GetRoot().GetLastToken().GetLocation(), tree.FilePath); } private void ReportDiagnosticsCore(Action<Diagnostic> addDiagnostic, Location location, params object[] messageArguments) { // warning diagnostic var diagnostic = Diagnostic.Create(Warning, location, messageArguments); addDiagnostic(diagnostic); // error diagnostic diagnostic = Diagnostic.Create(Error, location, messageArguments); addDiagnostic(diagnostic); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class GeneratedCodeAnalyzer2 : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( "GeneratedCodeAnalyzer2Warning", "Title", "GeneratedCodeAnalyzer2Message for '{0}'; Total types analyzed: '{1}'", "Category", DiagnosticSeverity.Warning, true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { // Analyze but don't report diagnostics on generated code. context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); context.RegisterCompilationStartAction(compilationStartContext => { var namedTypes = new HashSet<ISymbol>(); compilationStartContext.RegisterSymbolAction(symbolContext => namedTypes.Add(symbolContext.Symbol), SymbolKind.NamedType); compilationStartContext.RegisterCompilationEndAction(compilationEndContext => { foreach (var namedType in namedTypes) { var diagnostic = Diagnostic.Create(Rule, namedType.Locations[0], namedType.Name, namedTypes.Count); compilationEndContext.ReportDiagnostic(diagnostic); } }); }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class SharedStateAnalyzer : DiagnosticAnalyzer { private readonly SyntaxTreeValueProvider<bool> _treeValueProvider; private readonly HashSet<SyntaxTree> _treeCallbackSet; private readonly SourceTextValueProvider<int> _textValueProvider; private readonly HashSet<SourceText> _textCallbackSet; public static readonly DiagnosticDescriptor GeneratedCodeDescriptor = new DiagnosticDescriptor( "GeneratedCodeDiagnostic", "Title1", "GeneratedCodeDiagnostic {0}", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor NonGeneratedCodeDescriptor = new DiagnosticDescriptor( "UserCodeDiagnostic", "Title2", "UserCodeDiagnostic {0}", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor UniqueTextFileDescriptor = new DiagnosticDescriptor( "UniqueTextFileDiagnostic", "Title3", "UniqueTextFileDiagnostic {0}", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor NumberOfUniqueTextFileDescriptor = new DiagnosticDescriptor( "NumberOfUniqueTextFileDescriptor", "Title4", "NumberOfUniqueTextFileDescriptor {0}", "Category", DiagnosticSeverity.Warning, true); public SharedStateAnalyzer() { _treeValueProvider = new SyntaxTreeValueProvider<bool>(IsGeneratedCode); _treeCallbackSet = new HashSet<SyntaxTree>(SyntaxTreeComparer.Instance); _textValueProvider = new SourceTextValueProvider<int>(GetCharacterCount); _textCallbackSet = new HashSet<SourceText>(SourceTextComparer.Instance); } private bool IsGeneratedCode(SyntaxTree tree) { lock (_treeCallbackSet) { if (!_treeCallbackSet.Add(tree)) { throw new Exception("Expected driver to make a single callback per tree"); } } var fileNameWithoutExtension = PathUtilities.GetFileName(tree.FilePath, includeExtension: false); return fileNameWithoutExtension.EndsWith(".designer", StringComparison.OrdinalIgnoreCase) || fileNameWithoutExtension.EndsWith(".generated", StringComparison.OrdinalIgnoreCase); } private int GetCharacterCount(SourceText text) { lock (_textCallbackSet) { if (!_textCallbackSet.Add(text)) { throw new Exception("Expected driver to make a single callback per text"); } } return text.Length; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(GeneratedCodeDescriptor, NonGeneratedCodeDescriptor, UniqueTextFileDescriptor, NumberOfUniqueTextFileDescriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); } private void OnCompilationStart(CompilationStartAnalysisContext context) { context.RegisterSymbolAction(symbolContext => { var descriptor = GeneratedCodeDescriptor; foreach (var location in symbolContext.Symbol.Locations) { context.TryGetValue(location.SourceTree, _treeValueProvider, out var isGeneratedCode); if (!isGeneratedCode) { descriptor = NonGeneratedCodeDescriptor; break; } } var diagnostic = Diagnostic.Create(descriptor, symbolContext.Symbol.Locations[0], symbolContext.Symbol.Name); symbolContext.ReportDiagnostic(diagnostic); }, SymbolKind.NamedType); context.RegisterSyntaxTreeAction(treeContext => { context.TryGetValue(treeContext.Tree, _treeValueProvider, out var isGeneratedCode); var descriptor = isGeneratedCode ? GeneratedCodeDescriptor : NonGeneratedCodeDescriptor; var diagnostic = Diagnostic.Create(descriptor, Location.None, treeContext.Tree.FilePath); treeContext.ReportDiagnostic(diagnostic); context.TryGetValue(treeContext.Tree.GetText(), _textValueProvider, out var length); diagnostic = Diagnostic.Create(UniqueTextFileDescriptor, Location.None, treeContext.Tree.FilePath); treeContext.ReportDiagnostic(diagnostic); }); context.RegisterCompilationEndAction(endContext => { if (_treeCallbackSet.Count != endContext.Compilation.SyntaxTrees.Count()) { throw new Exception("Expected driver to make a callback for every tree"); } var diagnostic = Diagnostic.Create(NumberOfUniqueTextFileDescriptor, Location.None, _textCallbackSet.Count); endContext.ReportDiagnostic(diagnostic); }); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AnalyzerForParameters : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ParameterDescriptor = new DiagnosticDescriptor( "Parameter_ID", "Parameter_Title", "Parameter_Message", "Parameter_Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ParameterDescriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(SymbolAction, SymbolKind.Parameter); } private void SymbolAction(SymbolAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(ParameterDescriptor, context.Symbol.Locations[0])); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class SymbolStartAnalyzer : DiagnosticAnalyzer { private readonly SymbolKind _symbolKind; private readonly bool _topLevelAction; private readonly OperationKind? _operationKind; private readonly string _analyzerId; public SymbolStartAnalyzer(bool topLevelAction, SymbolKind symbolKind, OperationKind? operationKindOpt = null, int? analyzerId = null) { _topLevelAction = topLevelAction; _symbolKind = symbolKind; _operationKind = operationKindOpt; _analyzerId = $"Analyzer{(analyzerId.HasValue ? analyzerId.Value : 1)}"; SymbolsStarted = new ConcurrentSet<ISymbol>(); } internal ConcurrentSet<ISymbol> SymbolsStarted { get; } public static readonly DiagnosticDescriptor SymbolStartTopLevelRule = new DiagnosticDescriptor( "SymbolStartTopLevelRuleId", "SymbolStartTopLevelRuleTitle", "Symbol : {0}, Analyzer: {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor SymbolStartCompilationLevelRule = new DiagnosticDescriptor( "SymbolStartRuleId", "SymbolStartRuleTitle", "Symbol : {0}, Analyzer: {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor SymbolStartedEndedDifferRule = new DiagnosticDescriptor( "SymbolStartedEndedDifferRuleId", "SymbolStartedEndedDifferRuleTitle", "Symbols Started: '{0}', Symbols Ended: '{1}', Analyzer: {2}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor SymbolStartedOrderingRule = new DiagnosticDescriptor( "SymbolStartedOrderingRuleId", "SymbolStartedOrderingRuleTitle", "Member '{0}' started before container '{1}', Analyzer: {2}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor SymbolEndedOrderingRule = new DiagnosticDescriptor( "SymbolEndedOrderingRuleId", "SymbolEndedOrderingRuleTitle", "Container '{0}' ended before member '{1}', Analyzer: {2}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OperationOrderingRule = new DiagnosticDescriptor( "OperationOrderingRuleId", "OperationOrderingRuleTitle", "Container '{0}' started after operation '{1}', Analyzer: {2}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor DuplicateStartActionRule = new DiagnosticDescriptor( "DuplicateStartActionRuleId", "DuplicateStartActionRuleTitle", "Symbol : {0}, Analyzer: {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor DuplicateEndActionRule = new DiagnosticDescriptor( "DuplicateEndActionRuleId", "DuplicateEndActionRuleTitle", "Symbol : {0}, Analyzer: {1}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor OperationRule = new DiagnosticDescriptor( "OperationRuleId", "OperationRuleTitle", "Symbol Started: '{0}', Owning Symbol: '{1}' Operation : {2}, Analyzer: {3}", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create( SymbolStartTopLevelRule, SymbolStartCompilationLevelRule, SymbolStartedEndedDifferRule, SymbolStartedOrderingRule, SymbolEndedOrderingRule, DuplicateStartActionRule, DuplicateEndActionRule, OperationRule, OperationOrderingRule); } } public override void Initialize(AnalysisContext context) { var diagnostics = new ConcurrentBag<Diagnostic>(); var symbolsEnded = new ConcurrentSet<ISymbol>(); var seenOperationContainers = new ConcurrentDictionary<OperationAnalysisContext, ISet<ISymbol>>(); if (_topLevelAction) { context.RegisterSymbolStartAction(onSymbolStart, _symbolKind); context.RegisterCompilationStartAction(compilationStartContext => { compilationStartContext.RegisterCompilationEndAction(compilationEndContext => { reportDiagnosticsAtCompilationEnd(compilationEndContext); }); }); } else { context.RegisterCompilationStartAction(compilationStartContext => { compilationStartContext.RegisterSymbolStartAction(onSymbolStart, _symbolKind); compilationStartContext.RegisterCompilationEndAction(compilationEndContext => { reportDiagnosticsAtCompilationEnd(compilationEndContext); }); }); } return; void onSymbolStart(SymbolStartAnalysisContext symbolStartContext) { performSymbolStartActionVerification(symbolStartContext); if (_operationKind.HasValue) { symbolStartContext.RegisterOperationAction(operationContext => { performOperationActionVerification(operationContext, symbolStartContext); }, _operationKind.Value); } symbolStartContext.RegisterSymbolEndAction(symbolEndContext => { performSymbolEndActionVerification(symbolEndContext, symbolStartContext); }); } void reportDiagnosticsAtCompilationEnd(CompilationAnalysisContext compilationEndContext) { if (!SymbolsStarted.SetEquals(symbolsEnded)) { // Symbols Started: '{0}', Symbols Ended: '{1}', Analyzer: {2} var symbolsStartedStr = string.Join(", ", SymbolsStarted.Select(s => s.ToDisplayString()).Order()); var symbolsEndedStr = string.Join(", ", symbolsEnded.Select(s => s.ToDisplayString()).Order()); compilationEndContext.ReportDiagnostic(Diagnostic.Create(SymbolStartedEndedDifferRule, Location.None, symbolsStartedStr, symbolsEndedStr, _analyzerId)); } foreach (var diagnostic in diagnostics) { compilationEndContext.ReportDiagnostic(diagnostic); } } void performSymbolStartActionVerification(SymbolStartAnalysisContext symbolStartContext) { verifySymbolStartOrdering(symbolStartContext); verifySymbolStartAndOperationOrdering(symbolStartContext); if (!SymbolsStarted.Add(symbolStartContext.Symbol)) { diagnostics.Add(Diagnostic.Create(DuplicateStartActionRule, Location.None, symbolStartContext.Symbol.Name, _analyzerId)); } } void performSymbolEndActionVerification(SymbolAnalysisContext symbolEndContext, SymbolStartAnalysisContext symbolStartContext) { Assert.Equal(symbolStartContext.Symbol, symbolEndContext.Symbol); verifySymbolEndOrdering(symbolEndContext); if (!symbolsEnded.Add(symbolEndContext.Symbol)) { diagnostics.Add(Diagnostic.Create(DuplicateEndActionRule, Location.None, symbolEndContext.Symbol.Name, _analyzerId)); } Assert.False(symbolEndContext.Symbol.IsImplicitlyDeclared); var rule = _topLevelAction ? SymbolStartTopLevelRule : SymbolStartCompilationLevelRule; symbolEndContext.ReportDiagnostic(Diagnostic.Create(rule, Location.None, symbolStartContext.Symbol.Name, _analyzerId)); } void performOperationActionVerification(OperationAnalysisContext operationContext, SymbolStartAnalysisContext symbolStartContext) { var containingSymbols = GetContainingSymbolsAndThis(operationContext.ContainingSymbol).ToSet(); seenOperationContainers.Add(operationContext, containingSymbols); Assert.Contains(symbolStartContext.Symbol, containingSymbols); Assert.All(containingSymbols, s => Assert.DoesNotContain(s, symbolsEnded)); // Symbol Started: '{0}', Owning Symbol: '{1}' Operation : {2}, Analyzer: {3} operationContext.ReportDiagnostic(Diagnostic.Create(OperationRule, Location.None, symbolStartContext.Symbol.Name, operationContext.ContainingSymbol.Name, operationContext.Operation.Syntax.ToString(), _analyzerId)); } IEnumerable<ISymbol> GetContainingSymbolsAndThis(ISymbol symbol) { do { yield return symbol; symbol = symbol.ContainingSymbol; } while (symbol != null && !symbol.IsImplicitlyDeclared); } void verifySymbolStartOrdering(SymbolStartAnalysisContext symbolStartContext) { ISymbol symbolStarted = symbolStartContext.Symbol; IEnumerable<ISymbol> members; switch (symbolStarted) { case INamedTypeSymbol namedType: members = namedType.GetMembers(); break; case INamespaceSymbol namespaceSym: members = namespaceSym.GetMembers(); break; default: return; } foreach (var member in members.Where(m => !m.IsImplicitlyDeclared)) { if (SymbolsStarted.Contains(member)) { // Member '{0}' started before container '{1}', Analyzer {2} diagnostics.Add(Diagnostic.Create(SymbolStartedOrderingRule, Location.None, member, symbolStarted, _analyzerId)); } } } void verifySymbolEndOrdering(SymbolAnalysisContext symbolEndContext) { ISymbol symbolEnded = symbolEndContext.Symbol; IList<ISymbol> containersToVerify = new List<ISymbol>(); if (symbolEnded.ContainingType != null) { containersToVerify.Add(symbolEnded.ContainingType); } if (symbolEnded.ContainingNamespace != null) { containersToVerify.Add(symbolEnded.ContainingNamespace); } foreach (var container in containersToVerify) { if (symbolsEnded.Contains(container)) { // Container '{0}' ended before member '{1}', Analyzer {2} diagnostics.Add(Diagnostic.Create(SymbolEndedOrderingRule, Location.None, container, symbolEnded, _analyzerId)); } } } void verifySymbolStartAndOperationOrdering(SymbolStartAnalysisContext symbolStartContext) { foreach (var kvp in seenOperationContainers) { OperationAnalysisContext operationContext = kvp.Key; ISet<ISymbol> containers = kvp.Value; if (containers.Contains(symbolStartContext.Symbol)) { // Container '{0}' started after operation '{1}', Analyzer {2} diagnostics.Add(Diagnostic.Create(OperationOrderingRule, Location.None, symbolStartContext.Symbol, operationContext.Operation.Syntax.ToString(), _analyzerId)); } } } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressorForId : DiagnosticSuppressor { public SuppressionDescriptor SuppressionDescriptor { get; } public DiagnosticSuppressorForId(string suppressedDiagnosticId, string suppressionId = null) { SuppressionDescriptor = new SuppressionDescriptor( id: suppressionId ?? "SPR0001", suppressedDiagnosticId: suppressedDiagnosticId, justification: $"Suppress {suppressedDiagnosticId}"); } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(SuppressionDescriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { foreach (var diagnostic in context.ReportedDiagnostics) { Assert.Equal(SuppressionDescriptor.SuppressedDiagnosticId, diagnostic.Id); context.ReportSuppression(Suppression.Create(SuppressionDescriptor, diagnostic)); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressorForId_ThrowsOperationCancelledException : DiagnosticSuppressor { public CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource(); public SuppressionDescriptor SuppressionDescriptor { get; } public DiagnosticSuppressorForId_ThrowsOperationCancelledException(string suppressedDiagnosticId) { SuppressionDescriptor = new SuppressionDescriptor( id: "SPR0001", suppressedDiagnosticId: suppressedDiagnosticId, justification: $"Suppress {suppressedDiagnosticId}"); } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(SuppressionDescriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { CancellationTokenSource.Cancel(); context.CancellationToken.ThrowIfCancellationRequested(); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressorThrowsExceptionFromSupportedSuppressions : DiagnosticSuppressor { private readonly NotImplementedException _exception; public DiagnosticSuppressorThrowsExceptionFromSupportedSuppressions(NotImplementedException exception) { _exception = exception; } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => throw _exception; public override void ReportSuppressions(SuppressionAnalysisContext context) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressorThrowsExceptionFromReportedSuppressions : DiagnosticSuppressor { private readonly SuppressionDescriptor _descriptor; private readonly NotImplementedException _exception; public DiagnosticSuppressorThrowsExceptionFromReportedSuppressions(string suppressedDiagnosticId, NotImplementedException exception) { _descriptor = new SuppressionDescriptor( "SPR0001", suppressedDiagnosticId, $"Suppress {suppressedDiagnosticId}"); _exception = exception; } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(_descriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { throw _exception; } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressor_UnsupportedSuppressionReported : DiagnosticSuppressor { private readonly SuppressionDescriptor _supportedDescriptor; private readonly SuppressionDescriptor _unsupportedDescriptor; public DiagnosticSuppressor_UnsupportedSuppressionReported(string suppressedDiagnosticId, string supportedSuppressionId, string unsupportedSuppressionId) { _supportedDescriptor = new SuppressionDescriptor( supportedSuppressionId, suppressedDiagnosticId, $"Suppress {suppressedDiagnosticId}"); _unsupportedDescriptor = new SuppressionDescriptor( unsupportedSuppressionId, suppressedDiagnosticId, $"Suppress {suppressedDiagnosticId}"); } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(_supportedDescriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { foreach (var diagnostic in context.ReportedDiagnostics) { Assert.Equal(_unsupportedDescriptor.SuppressedDiagnosticId, diagnostic.Id); context.ReportSuppression(Suppression.Create(_unsupportedDescriptor, diagnostic)); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressor_InvalidDiagnosticSuppressionReported : DiagnosticSuppressor { private readonly SuppressionDescriptor _supportedDescriptor; private readonly SuppressionDescriptor _unsupportedDescriptor; public DiagnosticSuppressor_InvalidDiagnosticSuppressionReported(string suppressedDiagnosticId, string unsupportedSuppressedDiagnosticId) { _supportedDescriptor = new SuppressionDescriptor( "SPR0001", suppressedDiagnosticId, $"Suppress {suppressedDiagnosticId}"); _unsupportedDescriptor = new SuppressionDescriptor( "SPR0002", unsupportedSuppressedDiagnosticId, $"Suppress {unsupportedSuppressedDiagnosticId}"); } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(_supportedDescriptor); public override void ReportSuppressions(SuppressionAnalysisContext context) { foreach (var diagnostic in context.ReportedDiagnostics) { Assert.Equal(_supportedDescriptor.SuppressedDiagnosticId, diagnostic.Id); context.ReportSuppression(Suppression.Create(_unsupportedDescriptor, diagnostic)); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DiagnosticSuppressor_NonReportedDiagnosticCannotBeSuppressed : DiagnosticSuppressor { private readonly SuppressionDescriptor _descriptor1, _descriptor2; private readonly string _nonReportedDiagnosticId; public DiagnosticSuppressor_NonReportedDiagnosticCannotBeSuppressed(string reportedDiagnosticId, string nonReportedDiagnosticId) { _descriptor1 = new SuppressionDescriptor( "SPR0001", reportedDiagnosticId, $"Suppress {reportedDiagnosticId}"); _descriptor2 = new SuppressionDescriptor( "SPR0002", nonReportedDiagnosticId, $"Suppress {nonReportedDiagnosticId}"); _nonReportedDiagnosticId = nonReportedDiagnosticId; } public override ImmutableArray<SuppressionDescriptor> SupportedSuppressions => ImmutableArray.Create(_descriptor1, _descriptor2); public override void ReportSuppressions(SuppressionAnalysisContext context) { var nonReportedDiagnostic = Diagnostic.Create( id: _nonReportedDiagnosticId, category: "Category", message: "Message", severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, warningLevel: 1); context.ReportSuppression(Suppression.Create(_descriptor2, nonReportedDiagnostic)); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class NamedTypeAnalyzer : DiagnosticAnalyzer { public enum AnalysisKind { Symbol, SymbolStartEnd, CompilationStartEnd } public const string RuleId = "ID1"; public const string RuleCategory = "Category1"; private readonly DiagnosticDescriptor _rule; private readonly AnalysisKind _analysisKind; private readonly GeneratedCodeAnalysisFlags _analysisFlags; private readonly ConcurrentSet<ISymbol> _symbolCallbacks; public NamedTypeAnalyzer(AnalysisKind analysisKind, GeneratedCodeAnalysisFlags analysisFlags = GeneratedCodeAnalysisFlags.None, bool configurable = true) { _analysisKind = analysisKind; _analysisFlags = analysisFlags; _symbolCallbacks = new ConcurrentSet<ISymbol>(); var customTags = configurable ? Array.Empty<string>() : new[] { WellKnownDiagnosticTags.NotConfigurable }; _rule = new DiagnosticDescriptor( RuleId, "Title1", "Symbol: {0}", RuleCategory, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: customTags); } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule); public string GetSortedSymbolCallbacksString() => string.Join(", ", _symbolCallbacks.Select(s => s.Name).Order()); public override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(_analysisFlags); switch (_analysisKind) { case AnalysisKind.Symbol: context.RegisterSymbolAction(c => { _symbolCallbacks.Add(c.Symbol); ReportDiagnostic(c.Symbol, c.ReportDiagnostic); }, SymbolKind.NamedType); break; case AnalysisKind.SymbolStartEnd: context.RegisterSymbolStartAction(symbolStartContext => { symbolStartContext.RegisterSymbolEndAction(symbolEndContext => { _symbolCallbacks.Add(symbolEndContext.Symbol); ReportDiagnostic(symbolEndContext.Symbol, symbolEndContext.ReportDiagnostic); }); }, SymbolKind.NamedType); break; case AnalysisKind.CompilationStartEnd: context.RegisterCompilationStartAction(compilationStartContext => { compilationStartContext.RegisterSymbolAction(c => { _symbolCallbacks.Add(c.Symbol); }, SymbolKind.NamedType); compilationStartContext.RegisterCompilationEndAction( compilationEndContext => compilationEndContext.ReportDiagnostic( Diagnostic.Create(_rule, Location.None, GetSortedSymbolCallbacksString()))); }); break; } } private void ReportDiagnostic(ISymbol symbol, Action<Diagnostic> reportDiagnostic) => reportDiagnostic(Diagnostic.Create(_rule, symbol.Locations[0], symbol.Name)); } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class AnalyzerWithNoLocationDiagnostics : DiagnosticAnalyzer { public AnalyzerWithNoLocationDiagnostics(bool isEnabledByDefault) { Descriptor = new DiagnosticDescriptor( "ID0001", "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault); } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None))); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class NamedTypeAnalyzerWithConfigurableEnabledByDefault : DiagnosticAnalyzer { private readonly bool _throwOnAllNamedTypes; public NamedTypeAnalyzerWithConfigurableEnabledByDefault(bool isEnabledByDefault, DiagnosticSeverity defaultSeverity, bool throwOnAllNamedTypes = false) { Descriptor = new DiagnosticDescriptor( "ID0001", "Title1", "Message1", "Category1", defaultSeverity, isEnabledByDefault); _throwOnAllNamedTypes = throwOnAllNamedTypes; } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(context => { if (_throwOnAllNamedTypes) { throw new NotImplementedException(); } context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Symbol.Locations[0])); }, SymbolKind.NamedType); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class RegisterOperationBlockAndOperationActionAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor( "ID0001", "Title", "Message", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor); public override void Initialize(AnalysisContext analysisContext) { analysisContext.RegisterOperationAction(_ => { }, OperationKind.Invocation); analysisContext.RegisterOperationBlockStartAction(OnOperationBlockStart); } private void OnOperationBlockStart(OperationBlockStartAnalysisContext context) { context.RegisterOperationBlockEndAction( endContext => endContext.ReportDiagnostic(Diagnostic.Create(s_descriptor, context.OwningSymbol.Locations[0]))); } } [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class FieldAnalyzer : DiagnosticAnalyzer { private readonly bool _syntaxTreeAction; public FieldAnalyzer(string diagnosticId, bool syntaxTreeAction) { _syntaxTreeAction = syntaxTreeAction; Descriptor = new DiagnosticDescriptor( diagnosticId, "Title", "Message", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { if (_syntaxTreeAction) { context.RegisterSyntaxTreeAction(context => { var fields = context.Tree.GetRoot().DescendantNodes().OfType<CSharp.Syntax.FieldDeclarationSyntax>(); foreach (var variable in fields.SelectMany(f => f.Declaration.Variables)) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, variable.Identifier.GetLocation())); } }); } else { context.RegisterSymbolAction( context => context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Symbol.Locations[0])), SymbolKind.Field); } } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AdditionalFileAnalyzer : DiagnosticAnalyzer { private readonly bool _registerFromInitialize; private readonly TextSpan _diagnosticSpan; public AdditionalFileAnalyzer(bool registerFromInitialize, TextSpan diagnosticSpan, string id = "ID0001") { _registerFromInitialize = registerFromInitialize; _diagnosticSpan = diagnosticSpan; Descriptor = new DiagnosticDescriptor( id, "Title1", "Message1", "Category1", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); } public DiagnosticDescriptor Descriptor { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { if (_registerFromInitialize) { context.RegisterAdditionalFileAction(AnalyzeAdditionalFile); } else { context.RegisterCompilationStartAction(context => context.RegisterAdditionalFileAction(AnalyzeAdditionalFile)); } } private void AnalyzeAdditionalFile(AdditionalFileAnalysisContext context) { if (context.AdditionalFile.Path == null) { return; } var text = context.AdditionalFile.GetText(); var location = Location.Create(context.AdditionalFile.Path, _diagnosticSpan, text.Lines.GetLinePositionSpan(_diagnosticSpan)); context.ReportDiagnostic(Diagnostic.Create(Descriptor, location)); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class RegisterSyntaxTreeCancellationAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "ID0001"; private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor( DiagnosticId, "Title", "Message", "Category", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); public CancellationToken CancellationToken => _cancellationTokenSource.Token; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(s_descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxTreeAction(context => { // Mimic cancellation by throwing an OperationCanceledException in first callback. if (!_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource.Cancel(); while (true) { context.CancellationToken.ThrowIfCancellationRequested(); } throw ExceptionUtilities.Unreachable; } context.ReportDiagnostic(Diagnostic.Create(s_descriptor, context.Tree.GetRoot().GetLocation())); }); } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Core/Portable/DiagnosticAnalyzer/IAnalyzerAssemblyLoader.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable RS0041 // uses oblivious reference types using System; using System.Reflection; namespace Microsoft.CodeAnalysis { /// <summary> /// Handles loading analyzer assemblies and their dependencies. /// /// Before an analyzer assembly is loaded with <see cref="LoadFromPath(string)"/>, /// its location and the location of all of its dependencies must first be specified /// by calls to <see cref="AddDependencyLocation(string)"/>. /// </summary> /// <remarks> /// To the extent possible, implementations should remain consistent in the face /// of exceptions and allow the caller to handle them. This allows the caller to /// decide how to surface issues to the user and whether or not they are fatal. For /// example, if asked to load an a non-existent or inaccessible file a command line /// tool may wish to exit immediately, while an IDE may wish to keep going and give /// the user a chance to correct the issue. /// </remarks> public interface IAnalyzerAssemblyLoader { /// <summary> /// Given the full path to an assembly on disk, loads and returns the /// corresponding <see cref="Assembly"/> object. /// </summary> /// <remarks> /// Multiple calls with the same path should return the same /// <see cref="Assembly"/> instance. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="fullPath" /> is null.</exception> /// <exception cref="ArgumentException"><paramref name="fullPath" /> is not a full path.</exception> Assembly LoadFromPath(string fullPath); /// <summary> /// Adds a file to consider when loading an analyzer or its dependencies. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="fullPath" /> is null.</exception> /// <exception cref="ArgumentException"><paramref name="fullPath" /> is not a full path.</exception> void AddDependencyLocation(string fullPath); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable RS0041 // uses oblivious reference types using System; using System.Reflection; namespace Microsoft.CodeAnalysis { /// <summary> /// Handles loading analyzer assemblies and their dependencies. /// /// Before an analyzer assembly is loaded with <see cref="LoadFromPath(string)"/>, /// its location and the location of all of its dependencies must first be specified /// by calls to <see cref="AddDependencyLocation(string)"/>. /// </summary> /// <remarks> /// To the extent possible, implementations should remain consistent in the face /// of exceptions and allow the caller to handle them. This allows the caller to /// decide how to surface issues to the user and whether or not they are fatal. For /// example, if asked to load an a non-existent or inaccessible file a command line /// tool may wish to exit immediately, while an IDE may wish to keep going and give /// the user a chance to correct the issue. /// </remarks> public interface IAnalyzerAssemblyLoader { /// <summary> /// Given the full path to an assembly on disk, loads and returns the /// corresponding <see cref="Assembly"/> object. /// </summary> /// <remarks> /// Multiple calls with the same path should return the same /// <see cref="Assembly"/> instance. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="fullPath" /> is null.</exception> /// <exception cref="ArgumentException"><paramref name="fullPath" /> is not a full path.</exception> Assembly LoadFromPath(string fullPath); /// <summary> /// Adds a file to consider when loading an analyzer or its dependencies. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="fullPath" /> is null.</exception> /// <exception cref="ArgumentException"><paramref name="fullPath" /> is not a full path.</exception> void AddDependencyLocation(string fullPath); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Core/Portable/InternalUtilities/ReferenceEqualityComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; namespace Roslyn.Utilities { /// <summary> /// Compares objects based upon their reference identity. /// </summary> internal class ReferenceEqualityComparer : IEqualityComparer<object?> { public static readonly ReferenceEqualityComparer Instance = new(); private ReferenceEqualityComparer() { } bool IEqualityComparer<object?>.Equals(object? a, object? b) { return a == b; } int IEqualityComparer<object?>.GetHashCode(object? a) { return ReferenceEqualityComparer.GetHashCode(a); } public static int GetHashCode(object? a) { // https://github.com/dotnet/roslyn/issues/41539 return RuntimeHelpers.GetHashCode(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. using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Roslyn.Utilities { /// <summary> /// Compares objects based upon their reference identity. /// </summary> internal class ReferenceEqualityComparer : IEqualityComparer<object?> { public static readonly ReferenceEqualityComparer Instance = new(); private ReferenceEqualityComparer() { } bool IEqualityComparer<object?>.Equals(object? a, object? b) { return a == b; } int IEqualityComparer<object?>.GetHashCode(object? a) { return ReferenceEqualityComparer.GetHashCode(a); } public static int GetHashCode(object? a) { // https://github.com/dotnet/roslyn/issues/41539 return RuntimeHelpers.GetHashCode(a!); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Tools/ExternalAccess/OmniSharp/Internal/CodeRefactorings/WorkspaceServices/OmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CodeRefactorings.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Internal.CodeRefactorings.WorkspaceServices { [Shared] [ExportWorkspaceService(typeof(ISymbolRenamedCodeActionOperationFactoryWorkspaceService))] class OmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService : ISymbolRenamedCodeActionOperationFactoryWorkspaceService { private readonly IOmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService(IOmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService service) { _service = service; } public CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution) { return _service.CreateSymbolRenamedOperation(symbol, newName, startingSolution, updatedSolution); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CodeRefactorings.WorkspaceServices; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Internal.CodeRefactorings.WorkspaceServices { [Shared] [ExportWorkspaceService(typeof(ISymbolRenamedCodeActionOperationFactoryWorkspaceService))] class OmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService : ISymbolRenamedCodeActionOperationFactoryWorkspaceService { private readonly IOmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService(IOmniSharpSymbolRenamedCodeActionOperationFactoryWorkspaceService service) { _service = service; } public CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution) { return _service.CreateSymbolRenamedOperation(symbol, newName, startingSolution, updatedSolution); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class FindReferencesSearchEngine { private readonly Solution _solution; private readonly IImmutableSet<Document>? _documents; private readonly ImmutableArray<IReferenceFinder> _finders; private readonly IStreamingProgressTracker _progressTracker; private readonly IStreamingFindReferencesProgress _progress; private readonly FindReferencesSearchOptions _options; /// <summary> /// Scheduler to run our tasks on. If we're in <see cref="FindReferencesSearchOptions.Explicit"/> mode, we'll /// run all our tasks concurrently. Otherwise, we will run them serially using <see cref="s_exclusiveScheduler"/> /// </summary> private readonly TaskScheduler _scheduler; private static readonly TaskScheduler s_exclusiveScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler; private readonly ConcurrentDictionary<ISymbol, SymbolGroup> _symbolToGroup = new(); public FindReferencesSearchEngine( Solution solution, IImmutableSet<Document>? documents, ImmutableArray<IReferenceFinder> finders, IStreamingFindReferencesProgress progress, FindReferencesSearchOptions options) { _documents = documents; _solution = solution; _finders = finders; _progress = progress; _options = options; _progressTracker = progress.ProgressTracker; // If we're an explicit invocation, just defer to the threadpool to execute all our work in parallel to get // things done as quickly as possible. If we're running implicitly, then use a // ConcurrentExclusiveSchedulerPair's exclusive scheduler as that's the most built-in way in the TPL to get // will run things serially. _scheduler = _options.Explicit ? TaskScheduler.Default : s_exclusiveScheduler; } public async Task FindReferencesAsync(ISymbol symbol, CancellationToken cancellationToken) { await _progress.OnStartedAsync(cancellationToken).ConfigureAwait(false); try { var disposable = await _progressTracker.AddSingleItemAsync(cancellationToken).ConfigureAwait(false); await using var _ = disposable.ConfigureAwait(false); // Create the initial set of symbols to search for. As we walk the appropriate projects in the solution // we'll expand this set as we dicover new symbols to search for in each project. var symbolSet = await SymbolSet.CreateAsync(this, symbol, cancellationToken).ConfigureAwait(false); // Report the initial set of symbols to the caller. var allSymbols = symbolSet.GetAllSymbols(); await ReportGroupsAsync(allSymbols, cancellationToken).ConfigureAwait(false); // Determine the set of projects we actually have to walk to find results in. If the caller provided a // set of documents to search, we only bother with those. var projectsToSearch = await GetProjectIdsToSearchAsync(symbolSet.GetAllSymbols(), cancellationToken).ConfigureAwait(false); // We need to process projects in order when updating our symbol set. Say we have three projects (A, B // and C), we cannot necessarily find inherited symbols in C until we have searched B. Importantly, // while we're processing each project linearly to update the symbol set we're searching for, we still // then process the projects in parallel once we know the set of symbols we're searching for in that // project. var dependencyGraph = _solution.GetProjectDependencyGraph(); await _progressTracker.AddItemsAsync(projectsToSearch.Count, cancellationToken).ConfigureAwait(false); using var _1 = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var projectId in dependencyGraph.GetTopologicallySortedProjects(cancellationToken)) { if (!projectsToSearch.Contains(projectId)) continue; var currentProject = _solution.GetRequiredProject(projectId); // As we walk each project, attempt to grow the search set appropriately up and down the inheritance // hierarchy and grab a copy of the symbols to be processed. Note: this has to happen serially // which is why we do it in this loop and not inside the concurrent project processing that happens // below. await symbolSet.InheritanceCascadeAsync(currentProject, cancellationToken).ConfigureAwait(false); allSymbols = symbolSet.GetAllSymbols(); // Report any new symbols we've cascaded to to our caller. await ReportGroupsAsync(allSymbols, cancellationToken).ConfigureAwait(false); tasks.Add(CreateWorkAsync(() => ProcessProjectAsync(currentProject, allSymbols, cancellationToken), cancellationToken)); } // Now, wait for all projects to complete. await Task.WhenAll(tasks).ConfigureAwait(false); } finally { await _progress.OnCompletedAsync(cancellationToken).ConfigureAwait(false); } } public Task CreateWorkAsync(Func<Task> createWorkAsync, CancellationToken cancellationToken) => Task.Factory.StartNew(createWorkAsync, cancellationToken, TaskCreationOptions.None, _scheduler).Unwrap(); /// <summary> /// Notify the caller of the engine about the definitions we've found that we're looking for. We'll only notify /// them once per symbol group, but we may have to notify about new symbols each time we expand our symbol set /// when we walk into a new project. /// </summary> private async Task ReportGroupsAsync(ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { foreach (var symbol in symbols) { // See if this is the first time we're running across this symbol. Note: no locks are needed // here betwen checking and then adding because this is only ever called serially from within // FindReferencesAsync above (though we still need a ConcurrentDictionary as reads of these // symbols will happen later in ProcessDocumentAsync. However, those reads will only happen // after the dependent symbol values were written in, so it will be safe to blindly read them // out. if (!_symbolToGroup.ContainsKey(symbol)) { var linkedSymbols = await SymbolFinder.FindLinkedSymbolsAsync(symbol, _solution, cancellationToken).ConfigureAwait(false); var group = new SymbolGroup(linkedSymbols); foreach (var groupSymbol in group.Symbols) _symbolToGroup.TryAdd(groupSymbol, group); await _progress.OnDefinitionFoundAsync(group, cancellationToken).ConfigureAwait(false); } } } private async Task<HashSet<ProjectId>> GetProjectIdsToSearchAsync( ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { var projects = _documents != null ? _documents.Select(d => d.Project).ToImmutableHashSet() : _solution.Projects.ToImmutableHashSet(); var result = new HashSet<ProjectId>(); foreach (var symbol in symbols) { var dependentProjects = await DependentProjectsFinder.GetDependentProjectsAsync( _solution, symbol, projects, cancellationToken).ConfigureAwait(false); foreach (var project in dependentProjects) result.Add(project.Id); } return result; } private async Task ProcessProjectAsync(Project project, ImmutableArray<ISymbol> allSymbols, CancellationToken cancellationToken) { using var _1 = PooledDictionary<Document, PooledHashSet<ISymbol>>.GetInstance(out var documentToSymbols); try { foreach (var symbol in allSymbols) { foreach (var finder in _finders) { var documents = await finder.DetermineDocumentsToSearchAsync( symbol, project, _documents, _options, cancellationToken).ConfigureAwait(false); foreach (var document in documents) { if (!documentToSymbols.TryGetValue(document, out var docSymbols)) { docSymbols = PooledHashSet<ISymbol>.GetInstance(); documentToSymbols.Add(document, docSymbols); } docSymbols.Add(symbol); } } } using var _2 = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var (document, docSymbols) in documentToSymbols) tasks.Add(CreateWorkAsync(() => ProcessDocumentAsync(document, docSymbols, cancellationToken), cancellationToken)); await Task.WhenAll(tasks).ConfigureAwait(false); } finally { foreach (var (_, symbols) in documentToSymbols) symbols.Free(); await _progressTracker.ItemCompletedAsync(cancellationToken).ConfigureAwait(false); } } private async Task ProcessDocumentAsync( Document document, HashSet<ISymbol> symbols, CancellationToken cancellationToken) { await _progress.OnFindInDocumentStartedAsync(document, cancellationToken).ConfigureAwait(false); SemanticModel? model = null; try { model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // start cache for this semantic model FindReferenceCache.Start(model); foreach (var symbol in symbols) await ProcessDocumentAsync(document, model, symbol, cancellationToken).ConfigureAwait(false); } finally { FindReferenceCache.Stop(model); await _progress.OnFindInDocumentCompletedAsync(document, cancellationToken).ConfigureAwait(false); } } private async Task ProcessDocumentAsync( Document document, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.FindReference_ProcessDocumentAsync, cancellationToken)) { // This is safe to just blindly read. We can only ever get here after the call to ReportGroupsAsync // happened. So tehre must be a group for this symbol in our map. var group = _symbolToGroup[symbol]; foreach (var finder in _finders) { var references = await finder.FindReferencesInDocumentAsync( symbol, document, semanticModel, _options, cancellationToken).ConfigureAwait(false); foreach (var (_, location) in references) await _progress.OnReferenceFoundAsync(group, symbol, location, cancellationToken).ConfigureAwait(false); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class FindReferencesSearchEngine { private readonly Solution _solution; private readonly IImmutableSet<Document>? _documents; private readonly ImmutableArray<IReferenceFinder> _finders; private readonly IStreamingProgressTracker _progressTracker; private readonly IStreamingFindReferencesProgress _progress; private readonly FindReferencesSearchOptions _options; /// <summary> /// Scheduler to run our tasks on. If we're in <see cref="FindReferencesSearchOptions.Explicit"/> mode, we'll /// run all our tasks concurrently. Otherwise, we will run them serially using <see cref="s_exclusiveScheduler"/> /// </summary> private readonly TaskScheduler _scheduler; private static readonly TaskScheduler s_exclusiveScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler; private readonly ConcurrentDictionary<ISymbol, SymbolGroup> _symbolToGroup = new(); public FindReferencesSearchEngine( Solution solution, IImmutableSet<Document>? documents, ImmutableArray<IReferenceFinder> finders, IStreamingFindReferencesProgress progress, FindReferencesSearchOptions options) { _documents = documents; _solution = solution; _finders = finders; _progress = progress; _options = options; _progressTracker = progress.ProgressTracker; // If we're an explicit invocation, just defer to the threadpool to execute all our work in parallel to get // things done as quickly as possible. If we're running implicitly, then use a // ConcurrentExclusiveSchedulerPair's exclusive scheduler as that's the most built-in way in the TPL to get // will run things serially. _scheduler = _options.Explicit ? TaskScheduler.Default : s_exclusiveScheduler; } public async Task FindReferencesAsync(ISymbol symbol, CancellationToken cancellationToken) { await _progress.OnStartedAsync(cancellationToken).ConfigureAwait(false); try { var disposable = await _progressTracker.AddSingleItemAsync(cancellationToken).ConfigureAwait(false); await using var _ = disposable.ConfigureAwait(false); // Create the initial set of symbols to search for. As we walk the appropriate projects in the solution // we'll expand this set as we dicover new symbols to search for in each project. var symbolSet = await SymbolSet.CreateAsync(this, symbol, cancellationToken).ConfigureAwait(false); // Report the initial set of symbols to the caller. var allSymbols = symbolSet.GetAllSymbols(); await ReportGroupsAsync(allSymbols, cancellationToken).ConfigureAwait(false); // Determine the set of projects we actually have to walk to find results in. If the caller provided a // set of documents to search, we only bother with those. var projectsToSearch = await GetProjectIdsToSearchAsync(symbolSet.GetAllSymbols(), cancellationToken).ConfigureAwait(false); // We need to process projects in order when updating our symbol set. Say we have three projects (A, B // and C), we cannot necessarily find inherited symbols in C until we have searched B. Importantly, // while we're processing each project linearly to update the symbol set we're searching for, we still // then process the projects in parallel once we know the set of symbols we're searching for in that // project. var dependencyGraph = _solution.GetProjectDependencyGraph(); await _progressTracker.AddItemsAsync(projectsToSearch.Count, cancellationToken).ConfigureAwait(false); using var _1 = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var projectId in dependencyGraph.GetTopologicallySortedProjects(cancellationToken)) { if (!projectsToSearch.Contains(projectId)) continue; var currentProject = _solution.GetRequiredProject(projectId); // As we walk each project, attempt to grow the search set appropriately up and down the inheritance // hierarchy and grab a copy of the symbols to be processed. Note: this has to happen serially // which is why we do it in this loop and not inside the concurrent project processing that happens // below. await symbolSet.InheritanceCascadeAsync(currentProject, cancellationToken).ConfigureAwait(false); allSymbols = symbolSet.GetAllSymbols(); // Report any new symbols we've cascaded to to our caller. await ReportGroupsAsync(allSymbols, cancellationToken).ConfigureAwait(false); tasks.Add(CreateWorkAsync(() => ProcessProjectAsync(currentProject, allSymbols, cancellationToken), cancellationToken)); } // Now, wait for all projects to complete. await Task.WhenAll(tasks).ConfigureAwait(false); } finally { await _progress.OnCompletedAsync(cancellationToken).ConfigureAwait(false); } } public Task CreateWorkAsync(Func<Task> createWorkAsync, CancellationToken cancellationToken) => Task.Factory.StartNew(createWorkAsync, cancellationToken, TaskCreationOptions.None, _scheduler).Unwrap(); /// <summary> /// Notify the caller of the engine about the definitions we've found that we're looking for. We'll only notify /// them once per symbol group, but we may have to notify about new symbols each time we expand our symbol set /// when we walk into a new project. /// </summary> private async Task ReportGroupsAsync(ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { foreach (var symbol in symbols) { // See if this is the first time we're running across this symbol. Note: no locks are needed // here betwen checking and then adding because this is only ever called serially from within // FindReferencesAsync above (though we still need a ConcurrentDictionary as reads of these // symbols will happen later in ProcessDocumentAsync. However, those reads will only happen // after the dependent symbol values were written in, so it will be safe to blindly read them // out. if (!_symbolToGroup.ContainsKey(symbol)) { var linkedSymbols = await SymbolFinder.FindLinkedSymbolsAsync(symbol, _solution, cancellationToken).ConfigureAwait(false); var group = new SymbolGroup(linkedSymbols); foreach (var groupSymbol in group.Symbols) _symbolToGroup.TryAdd(groupSymbol, group); await _progress.OnDefinitionFoundAsync(group, cancellationToken).ConfigureAwait(false); } } } private async Task<HashSet<ProjectId>> GetProjectIdsToSearchAsync( ImmutableArray<ISymbol> symbols, CancellationToken cancellationToken) { var projects = _documents != null ? _documents.Select(d => d.Project).ToImmutableHashSet() : _solution.Projects.ToImmutableHashSet(); var result = new HashSet<ProjectId>(); foreach (var symbol in symbols) { var dependentProjects = await DependentProjectsFinder.GetDependentProjectsAsync( _solution, symbol, projects, cancellationToken).ConfigureAwait(false); foreach (var project in dependentProjects) result.Add(project.Id); } return result; } private async Task ProcessProjectAsync(Project project, ImmutableArray<ISymbol> allSymbols, CancellationToken cancellationToken) { using var _1 = PooledDictionary<Document, PooledHashSet<ISymbol>>.GetInstance(out var documentToSymbols); try { foreach (var symbol in allSymbols) { foreach (var finder in _finders) { var documents = await finder.DetermineDocumentsToSearchAsync( symbol, project, _documents, _options, cancellationToken).ConfigureAwait(false); foreach (var document in documents) { if (!documentToSymbols.TryGetValue(document, out var docSymbols)) { docSymbols = PooledHashSet<ISymbol>.GetInstance(); documentToSymbols.Add(document, docSymbols); } docSymbols.Add(symbol); } } } using var _2 = ArrayBuilder<Task>.GetInstance(out var tasks); foreach (var (document, docSymbols) in documentToSymbols) tasks.Add(CreateWorkAsync(() => ProcessDocumentAsync(document, docSymbols, cancellationToken), cancellationToken)); await Task.WhenAll(tasks).ConfigureAwait(false); } finally { foreach (var (_, symbols) in documentToSymbols) symbols.Free(); await _progressTracker.ItemCompletedAsync(cancellationToken).ConfigureAwait(false); } } private async Task ProcessDocumentAsync( Document document, HashSet<ISymbol> symbols, CancellationToken cancellationToken) { await _progress.OnFindInDocumentStartedAsync(document, cancellationToken).ConfigureAwait(false); SemanticModel? model = null; try { model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); // start cache for this semantic model FindReferenceCache.Start(model); foreach (var symbol in symbols) await ProcessDocumentAsync(document, model, symbol, cancellationToken).ConfigureAwait(false); } finally { FindReferenceCache.Stop(model); await _progress.OnFindInDocumentCompletedAsync(document, cancellationToken).ConfigureAwait(false); } } private async Task ProcessDocumentAsync( Document document, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.FindReference_ProcessDocumentAsync, cancellationToken)) { // This is safe to just blindly read. We can only ever get here after the call to ReportGroupsAsync // happened. So tehre must be a group for this symbol in our map. var group = _symbolToGroup[symbol]; foreach (var finder in _finders) { var references = await finder.FindReferencesInDocumentAsync( symbol, document, semanticModel, _options, cancellationToken).ConfigureAwait(false); foreach (var (_, location) in references) await _progress.OnReferenceFoundAsync(group, symbol, location, cancellationToken).ConfigureAwait(false); } } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Test/Core/FX/ProcessUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using Xunit; namespace Roslyn.Test.Utilities { public static class ProcessUtilities { /// <summary> /// Launch a process, wait for it to complete, and return output, error, and exit code. /// </summary> public static ProcessResult Run( string fileName, string arguments, string workingDirectory = null, IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVars = null, string stdInput = null, bool redirectStandardInput = false) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = stdInput != null || redirectStandardInput, WorkingDirectory = workingDirectory }; // In case the process is a console application that expects standard input // do not set CreateNoWindow to true to ensure that the input encoding // of both the test and the process fileName is equal. if (stdInput == null) { startInfo.CreateNoWindow = true; } if (additionalEnvironmentVars != null) { foreach (var entry in additionalEnvironmentVars) { startInfo.Environment[entry.Key] = entry.Value; } } using (var process = new Process { StartInfo = startInfo }) { StringBuilder outputBuilder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder(); process.OutputDataReceived += (sender, args) => { if (args.Data != null) outputBuilder.AppendLine(args.Data); }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) errorBuilder.AppendLine(args.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (stdInput != null) { process.StandardInput.Write(stdInput); process.StandardInput.Dispose(); } process.WaitForExit(); // Double check the process has actually exited Debug.Assert(process.HasExited); return new ProcessResult(process.ExitCode, outputBuilder.ToString(), errorBuilder.ToString()); } } /// <summary> /// Launch a process, and return Process object. The process continues to run asynchronously. /// You cannot capture the output. /// </summary> public static Process StartProcess(string fileName, string arguments, string workingDirectory = null) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = workingDirectory }; Process p = new Process { StartInfo = startInfo }; p.Start(); return p; } public static string RunAndGetOutput(string exeFileName, string arguments = null, int expectedRetCode = 0, string startFolder = null) { ProcessStartInfo startInfo = new ProcessStartInfo(exeFileName); if (arguments != null) { startInfo.Arguments = arguments; } string result = null; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; if (startFolder != null) { startInfo.WorkingDirectory = startFolder; } using (var process = System.Diagnostics.Process.Start(startInfo)) { // Do not wait for the child process to exit before reading to the end of its // redirected stream. Read the output stream first and then wait. Doing otherwise // might cause a deadlock. result = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); Assert.True(expectedRetCode == process.ExitCode, $"Unexpected exit code: {process.ExitCode} (expecting {expectedRetCode}). Process output: {result}. Process error: {error}"); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Xunit; namespace Roslyn.Test.Utilities { public static class ProcessUtilities { /// <summary> /// Launch a process, wait for it to complete, and return output, error, and exit code. /// </summary> public static ProcessResult Run( string fileName, string arguments, string workingDirectory = null, IEnumerable<KeyValuePair<string, string>> additionalEnvironmentVars = null, string stdInput = null, bool redirectStandardInput = false) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = stdInput != null || redirectStandardInput, WorkingDirectory = workingDirectory }; // In case the process is a console application that expects standard input // do not set CreateNoWindow to true to ensure that the input encoding // of both the test and the process fileName is equal. if (stdInput == null) { startInfo.CreateNoWindow = true; } if (additionalEnvironmentVars != null) { foreach (var entry in additionalEnvironmentVars) { startInfo.Environment[entry.Key] = entry.Value; } } using (var process = new Process { StartInfo = startInfo }) { StringBuilder outputBuilder = new StringBuilder(); StringBuilder errorBuilder = new StringBuilder(); process.OutputDataReceived += (sender, args) => { if (args.Data != null) outputBuilder.AppendLine(args.Data); }; process.ErrorDataReceived += (sender, args) => { if (args.Data != null) errorBuilder.AppendLine(args.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (stdInput != null) { process.StandardInput.Write(stdInput); process.StandardInput.Dispose(); } process.WaitForExit(); // Double check the process has actually exited Debug.Assert(process.HasExited); return new ProcessResult(process.ExitCode, outputBuilder.ToString(), errorBuilder.ToString()); } } /// <summary> /// Launch a process, and return Process object. The process continues to run asynchronously. /// You cannot capture the output. /// </summary> public static Process StartProcess(string fileName, string arguments, string workingDirectory = null) { if (fileName == null) { throw new ArgumentNullException(nameof(fileName)); } var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = workingDirectory }; Process p = new Process { StartInfo = startInfo }; p.Start(); return p; } public static string RunAndGetOutput(string exeFileName, string arguments = null, int expectedRetCode = 0, string startFolder = null) { ProcessStartInfo startInfo = new ProcessStartInfo(exeFileName); if (arguments != null) { startInfo.Arguments = arguments; } string result = null; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; if (startFolder != null) { startInfo.WorkingDirectory = startFolder; } using (var process = System.Diagnostics.Process.Start(startInfo)) { // Do not wait for the child process to exit before reading to the end of its // redirected stream. Read the output stream first and then wait. Doing otherwise // might cause a deadlock. result = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); Assert.True(expectedRetCode == process.ExitCode, $"Unexpected exit code: {process.ExitCode} (expecting {expectedRetCode}). Process output: {result}. Process error: {error}"); } return result; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/VisualBasicTest/CodeActions/AbstractVisualBasicCodeActionTest.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.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Public MustInherit Class AbstractVisualBasicCodeActionTest Inherits AbstractCodeActionTest Private ReadOnly _compilationOptions As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithParseOptions(New VisualBasicParseOptions(LanguageVersion.Latest)) Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Shared Function NewLines(input As String) As String Return input.Replace("\n", vbCrLf) End Function Protected Overloads Async Function TestAsync(initialMarkup As XElement, expected As XElement, Optional index As Integer = 0, Optional parseOptions As ParseOptions = Nothing) As Threading.Tasks.Task Dim initialMarkupStr = initialMarkup.ConvertTestSourceTag() Dim expectedStr = expected.ConvertTestSourceTag() If parseOptions Is Nothing Then Await MyBase.TestAsync(initialMarkupStr, expectedStr, parseOptions:=_compilationOptions.ParseOptions, compilationOptions:=_compilationOptions, index:=index) Else Await MyBase.TestAsync(initialMarkupStr, expectedStr, parseOptions:=parseOptions, compilationOptions:=_compilationOptions, index:=index) End If End Function Protected Overloads Async Function TestMissingAsync(initialMarkup As XElement) As Threading.Tasks.Task Dim initialMarkupStr = initialMarkup.ConvertTestSourceTag() Await MyBase.TestMissingAsync(initialMarkupStr, New TestParameters(parseOptions:=Nothing, compilationOptions:=_compilationOptions)) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic 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.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Public MustInherit Class AbstractVisualBasicCodeActionTest Inherits AbstractCodeActionTest Private ReadOnly _compilationOptions As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionInfer(True).WithParseOptions(New VisualBasicParseOptions(LanguageVersion.Latest)) Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Shared Function NewLines(input As String) As String Return input.Replace("\n", vbCrLf) End Function Protected Overloads Async Function TestAsync(initialMarkup As XElement, expected As XElement, Optional index As Integer = 0, Optional parseOptions As ParseOptions = Nothing) As Threading.Tasks.Task Dim initialMarkupStr = initialMarkup.ConvertTestSourceTag() Dim expectedStr = expected.ConvertTestSourceTag() If parseOptions Is Nothing Then Await MyBase.TestAsync(initialMarkupStr, expectedStr, parseOptions:=_compilationOptions.ParseOptions, compilationOptions:=_compilationOptions, index:=index) Else Await MyBase.TestAsync(initialMarkupStr, expectedStr, parseOptions:=parseOptions, compilationOptions:=_compilationOptions, index:=index) End If End Function Protected Overloads Async Function TestMissingAsync(initialMarkup As XElement) As Threading.Tasks.Task Dim initialMarkupStr = initialMarkup.ConvertTestSourceTag() Await MyBase.TestMissingAsync(initialMarkupStr, New TestParameters(parseOptions:=Nothing, compilationOptions:=_compilationOptions)) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic End Function End Class End Namespace
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/Wrapping/Edit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Wrapping { /// <summary> /// Represents an edit between two tokens. Specifically, provides the new trailing trivia for /// the <see cref="Left"/> token and the new leading trivia for the <see /// cref="Right"/> token. /// </summary> internal readonly struct Edit { public readonly SyntaxToken Left; public readonly SyntaxToken Right; public readonly SyntaxTriviaList NewLeftTrailingTrivia; public readonly SyntaxTriviaList NewRightLeadingTrivia; private Edit( SyntaxToken left, SyntaxTriviaList newLeftTrailingTrivia, SyntaxToken right, SyntaxTriviaList newRightLeadingTrivia) { Left = left; Right = right; NewLeftTrailingTrivia = newLeftTrailingTrivia; NewRightLeadingTrivia = newRightLeadingTrivia; } public string GetNewTrivia() { var result = PooledStringBuilder.GetInstance(); AppendTrivia(result, NewLeftTrailingTrivia); AppendTrivia(result, NewRightLeadingTrivia); return result.ToStringAndFree(); } private static void AppendTrivia(PooledStringBuilder result, SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { result.Builder.Append(trivia.ToFullString()); } } /// <summary> /// Create the Edit representing the deletion of all trivia between left and right. /// </summary> public static Edit DeleteBetween(SyntaxNodeOrToken left, SyntaxNodeOrToken right) => UpdateBetween(left, default, default(SyntaxTriviaList), right); public static Edit UpdateBetween( SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia, SyntaxTrivia rightLeadingTrivia, SyntaxNodeOrToken right) { return UpdateBetween(left, leftTrailingTrivia, new SyntaxTriviaList(rightLeadingTrivia), right); } public static Edit UpdateBetween( SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia, SyntaxTriviaList rightLeadingTrivia, SyntaxNodeOrToken right) { var leftLastToken = left.IsToken ? left.AsToken() : left.AsNode().GetLastToken(); var rightFirstToken = right.IsToken ? right.AsToken() : right.AsNode().GetFirstToken(); return new Edit(leftLastToken, leftTrailingTrivia, rightFirstToken, rightLeadingTrivia); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Wrapping { /// <summary> /// Represents an edit between two tokens. Specifically, provides the new trailing trivia for /// the <see cref="Left"/> token and the new leading trivia for the <see /// cref="Right"/> token. /// </summary> internal readonly struct Edit { public readonly SyntaxToken Left; public readonly SyntaxToken Right; public readonly SyntaxTriviaList NewLeftTrailingTrivia; public readonly SyntaxTriviaList NewRightLeadingTrivia; private Edit( SyntaxToken left, SyntaxTriviaList newLeftTrailingTrivia, SyntaxToken right, SyntaxTriviaList newRightLeadingTrivia) { Left = left; Right = right; NewLeftTrailingTrivia = newLeftTrailingTrivia; NewRightLeadingTrivia = newRightLeadingTrivia; } public string GetNewTrivia() { var result = PooledStringBuilder.GetInstance(); AppendTrivia(result, NewLeftTrailingTrivia); AppendTrivia(result, NewRightLeadingTrivia); return result.ToStringAndFree(); } private static void AppendTrivia(PooledStringBuilder result, SyntaxTriviaList triviaList) { foreach (var trivia in triviaList) { result.Builder.Append(trivia.ToFullString()); } } /// <summary> /// Create the Edit representing the deletion of all trivia between left and right. /// </summary> public static Edit DeleteBetween(SyntaxNodeOrToken left, SyntaxNodeOrToken right) => UpdateBetween(left, default, default(SyntaxTriviaList), right); public static Edit UpdateBetween( SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia, SyntaxTrivia rightLeadingTrivia, SyntaxNodeOrToken right) { return UpdateBetween(left, leftTrailingTrivia, new SyntaxTriviaList(rightLeadingTrivia), right); } public static Edit UpdateBetween( SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia, SyntaxTriviaList rightLeadingTrivia, SyntaxNodeOrToken right) { var leftLastToken = left.IsToken ? left.AsToken() : left.AsNode().GetLastToken(); var rightFirstToken = right.IsToken ? right.AsToken() : right.AsNode().GetFirstToken(); return new Edit(leftLastToken, leftTrailingTrivia, rightFirstToken, rightLeadingTrivia); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/RQName/Nodes/RQErrorType.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 RQErrorType : RQType { public readonly string Name; public RQErrorType(string name) => Name = name; public override SimpleTreeNode ToSimpleTree() => new SimpleGroupNode(RQNameStrings.Error, 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 Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQErrorType : RQType { public readonly string Name; public RQErrorType(string name) => Name = name; public override SimpleTreeNode ToSimpleTree() => new SimpleGroupNode(RQNameStrings.Error, Name); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/VisualBasic/Portable/Binding/SourceFileBinder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A SourceFileBinder provides the context associated with a give source file, not including the ''' Imports statements (which have their own binders). It primarily provides the services of getting ''' locations of node, since it holds onto a SyntaxTree. ''' </summary> Friend Class SourceFileBinder Inherits Binder ' The source file this binder is associated with Private ReadOnly _sourceFile As SourceFile Public Sub New(containingBinder As Binder, sourceFile As SourceFile, tree As SyntaxTree) MyBase.New(containingBinder, tree) Debug.Assert(sourceFile IsNot Nothing) _sourceFile = sourceFile End Sub Public Overrides Function GetSyntaxReference(node As VisualBasicSyntaxNode) As SyntaxReference Return SyntaxTree.GetReference(node) End Function Public Overrides ReadOnly Property OptionStrict As OptionStrict Get ' If the source file had an option strict declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionStrict.HasValue Then Return If(_sourceFile.OptionStrict.Value, OptionStrict.On, OptionStrict.Off) Else Return m_containingBinder.OptionStrict End If End Get End Property Public Overrides ReadOnly Property OptionInfer As Boolean Get ' If the source file had an option infer declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionInfer.HasValue Then Return _sourceFile.OptionInfer.Value Else Return m_containingBinder.OptionInfer End If End Get End Property Public Overrides ReadOnly Property OptionExplicit As Boolean Get ' If the source file had an option explicit declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionExplicit.HasValue Then Return _sourceFile.OptionExplicit.Value Else Return m_containingBinder.OptionExplicit End If End Get End Property Public Overrides ReadOnly Property OptionCompareText As Boolean Get ' If the source file had an option compare declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionCompareText.HasValue Then Return _sourceFile.OptionCompareText.Value Else Return m_containingBinder.OptionCompareText End If End Get End Property Public Overrides ReadOnly Property QuickAttributeChecker As QuickAttributeChecker Get Return _sourceFile.QuickAttributeChecker 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.Concurrent Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A SourceFileBinder provides the context associated with a give source file, not including the ''' Imports statements (which have their own binders). It primarily provides the services of getting ''' locations of node, since it holds onto a SyntaxTree. ''' </summary> Friend Class SourceFileBinder Inherits Binder ' The source file this binder is associated with Private ReadOnly _sourceFile As SourceFile Public Sub New(containingBinder As Binder, sourceFile As SourceFile, tree As SyntaxTree) MyBase.New(containingBinder, tree) Debug.Assert(sourceFile IsNot Nothing) _sourceFile = sourceFile End Sub Public Overrides Function GetSyntaxReference(node As VisualBasicSyntaxNode) As SyntaxReference Return SyntaxTree.GetReference(node) End Function Public Overrides ReadOnly Property OptionStrict As OptionStrict Get ' If the source file had an option strict declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionStrict.HasValue Then Return If(_sourceFile.OptionStrict.Value, OptionStrict.On, OptionStrict.Off) Else Return m_containingBinder.OptionStrict End If End Get End Property Public Overrides ReadOnly Property OptionInfer As Boolean Get ' If the source file had an option infer declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionInfer.HasValue Then Return _sourceFile.OptionInfer.Value Else Return m_containingBinder.OptionInfer End If End Get End Property Public Overrides ReadOnly Property OptionExplicit As Boolean Get ' If the source file had an option explicit declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionExplicit.HasValue Then Return _sourceFile.OptionExplicit.Value Else Return m_containingBinder.OptionExplicit End If End Get End Property Public Overrides ReadOnly Property OptionCompareText As Boolean Get ' If the source file had an option compare declaration in it, use that. Otherwise ' defer to the global options. If _sourceFile.OptionCompareText.HasValue Then Return _sourceFile.OptionCompareText.Value Else Return m_containingBinder.OptionCompareText End If End Get End Property Public Overrides ReadOnly Property QuickAttributeChecker As QuickAttributeChecker Get Return _sourceFile.QuickAttributeChecker End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/VisualBasic/Portable/BoundTree/BoundAggregateClause.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundAggregateClause Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return UnderlyingExpression.ExpressionSymbol End Get End Property Public Overrides ReadOnly Property ResultKind As LookupResultKind Get Return UnderlyingExpression.ResultKind 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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundAggregateClause Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return UnderlyingExpression.ExpressionSymbol End Get End Property Public Overrides ReadOnly Property ResultKind As LookupResultKind Get Return UnderlyingExpression.ResultKind End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Portable/Compilation/SyntaxAndDeclarationManager.LazyState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class SyntaxAndDeclarationManager : CommonSyntaxAndDeclarationManager { internal sealed class State { internal readonly ImmutableArray<SyntaxTree> SyntaxTrees; // In ordinal order. internal readonly ImmutableDictionary<SyntaxTree, int> OrdinalMap; // Inverse of syntaxTrees array (i.e. maps tree to index) internal readonly ImmutableDictionary<SyntaxTree, ImmutableArray<LoadDirective>> LoadDirectiveMap; internal readonly ImmutableDictionary<string, SyntaxTree> LoadedSyntaxTreeMap; internal readonly ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> RootNamespaces; internal readonly DeclarationTable DeclarationTable; internal State( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableDictionary<SyntaxTree, int> syntaxTreeOrdinalMap, ImmutableDictionary<SyntaxTree, ImmutableArray<LoadDirective>> loadDirectiveMap, ImmutableDictionary<string, SyntaxTree> loadedSyntaxTreeMap, ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> rootNamespaces, DeclarationTable declarationTable) { Debug.Assert(syntaxTrees.All(tree => syntaxTrees[syntaxTreeOrdinalMap[tree]] == tree)); Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer<SyntaxTree>.Default)); this.SyntaxTrees = syntaxTrees; this.OrdinalMap = syntaxTreeOrdinalMap; this.LoadDirectiveMap = loadDirectiveMap; this.LoadedSyntaxTreeMap = loadedSyntaxTreeMap; this.RootNamespaces = rootNamespaces; this.DeclarationTable = declarationTable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class SyntaxAndDeclarationManager : CommonSyntaxAndDeclarationManager { internal sealed class State { internal readonly ImmutableArray<SyntaxTree> SyntaxTrees; // In ordinal order. internal readonly ImmutableDictionary<SyntaxTree, int> OrdinalMap; // Inverse of syntaxTrees array (i.e. maps tree to index) internal readonly ImmutableDictionary<SyntaxTree, ImmutableArray<LoadDirective>> LoadDirectiveMap; internal readonly ImmutableDictionary<string, SyntaxTree> LoadedSyntaxTreeMap; internal readonly ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> RootNamespaces; internal readonly DeclarationTable DeclarationTable; internal State( ImmutableArray<SyntaxTree> syntaxTrees, ImmutableDictionary<SyntaxTree, int> syntaxTreeOrdinalMap, ImmutableDictionary<SyntaxTree, ImmutableArray<LoadDirective>> loadDirectiveMap, ImmutableDictionary<string, SyntaxTree> loadedSyntaxTreeMap, ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> rootNamespaces, DeclarationTable declarationTable) { Debug.Assert(syntaxTrees.All(tree => syntaxTrees[syntaxTreeOrdinalMap[tree]] == tree)); Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer<SyntaxTree>.Default)); this.SyntaxTrees = syntaxTrees; this.OrdinalMap = syntaxTreeOrdinalMap; this.LoadDirectiveMap = loadDirectiveMap; this.LoadedSyntaxTreeMap = loadedSyntaxTreeMap; this.RootNamespaces = rootNamespaces; this.DeclarationTable = declarationTable; } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Def/Implementation/FindReferences/NameMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal class NameMetadata { public string? Name { get; } public NameMetadata(IDictionary<string, object> data) => this.Name = (string?)data.GetValueOrDefault(nameof(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 Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal class NameMetadata { public string? Name { get; } public NameMetadata(IDictionary<string, object> data) => this.Name = (string?)data.GetValueOrDefault(nameof(Name)); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Test/Resources/Core/SymbolsTests/UseSiteErrors/Unavailable.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL\sN! % @@ @%K@`  H.text  `.rsrc@@@.reloc ` @B%H` ( *( *BSJB v4.0.30319lL#~#Strings#US#GUIDX#BlobG %3   kKK+ >  P dy  P  X   # # -4;-D-4;-D1"9 A'. -.6 <Module>Unavailable.dllUnavailableClassUnavailableClass`1UnavailableStructUnavailableStruct`1UnavailableInterfaceUnavailableInterface`1UnavailableDelegateUnavailableDelegate`1mscorlibSystemObjectTValueTypeMulticastDelegate.ctorInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokeobjectmethodcallbackresultSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeUnavailableSystem.Runtime.InteropServicesStructLayoutAttributeLayoutKind *Z L5Xz\V4      %TWrapNonExceptionThrows%% %_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameUnavailable.dll(LegalCopyright HOriginalFilenameUnavailable.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 5
MZ@ !L!This program cannot be run in DOS mode. $PEL\sN! % @@ @%K@`  H.text  `.rsrc@@@.reloc ` @B%H` ( *( *BSJB v4.0.30319lL#~#Strings#US#GUIDX#BlobG %3   kKK+ >  P dy  P  X   # # -4;-D-4;-D1"9 A'. -.6 <Module>Unavailable.dllUnavailableClassUnavailableClass`1UnavailableStructUnavailableStruct`1UnavailableInterfaceUnavailableInterface`1UnavailableDelegateUnavailableDelegate`1mscorlibSystemObjectTValueTypeMulticastDelegate.ctorInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokeobjectmethodcallbackresultSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeUnavailableSystem.Runtime.InteropServicesStructLayoutAttributeLayoutKind *Z L5Xz\V4      %TWrapNonExceptionThrows%% %_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameUnavailable.dll(LegalCopyright HOriginalFilenameUnavailable.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 5
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Core/AnalyzerDriver/DeclarationComputer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal class DeclarationComputer { internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, IEnumerable<SyntaxNode>? executableCodeBlocks, CancellationToken cancellationToken) { var declaredSymbol = GetDeclaredSymbol(model, node, getSymbol, cancellationToken); return GetDeclarationInfo(node, declaredSymbol, executableCodeBlocks); } internal static DeclarationInfo GetDeclarationInfo(SyntaxNode node, ISymbol? declaredSymbol, IEnumerable<SyntaxNode>? executableCodeBlocks) { var codeBlocks = executableCodeBlocks?.Where(c => c != null).AsImmutableOrEmpty() ?? ImmutableArray<SyntaxNode>.Empty; return new DeclarationInfo(node, codeBlocks, declaredSymbol); } internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken) { return GetDeclarationInfo(model, node, getSymbol, (IEnumerable<SyntaxNode>?)null, cancellationToken); } internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, SyntaxNode executableCodeBlock, CancellationToken cancellationToken) { return GetDeclarationInfo(model, node, getSymbol, SpecializedCollections.SingletonEnumerable(executableCodeBlock), cancellationToken); } internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken, params SyntaxNode[] executableCodeBlocks) { return GetDeclarationInfo(model, node, getSymbol, executableCodeBlocks.AsEnumerable(), cancellationToken); } private static ISymbol? GetDeclaredSymbol(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken) { if (!getSymbol) { return null; } var declaredSymbol = model.GetDeclaredSymbol(node, cancellationToken); // For namespace declarations, GetDeclaredSymbol returns a compilation scoped namespace symbol, // which includes declarations across the compilation, including those in referenced assemblies. // However, we are only interested in the namespace symbol scoped to the compilation's source assembly. if (declaredSymbol is INamespaceSymbol namespaceSymbol && namespaceSymbol.ConstituentNamespaces.Length > 1) { var assemblyToScope = model.Compilation.Assembly; var assemblyScopedNamespaceSymbol = namespaceSymbol.ConstituentNamespaces.FirstOrDefault(ns => ns.ContainingAssembly == assemblyToScope); if (assemblyScopedNamespaceSymbol != null) { Debug.Assert(assemblyScopedNamespaceSymbol.ConstituentNamespaces.Length == 1); declaredSymbol = assemblyScopedNamespaceSymbol; } } return declaredSymbol; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal class DeclarationComputer { internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, IEnumerable<SyntaxNode>? executableCodeBlocks, CancellationToken cancellationToken) { var declaredSymbol = GetDeclaredSymbol(model, node, getSymbol, cancellationToken); return GetDeclarationInfo(node, declaredSymbol, executableCodeBlocks); } internal static DeclarationInfo GetDeclarationInfo(SyntaxNode node, ISymbol? declaredSymbol, IEnumerable<SyntaxNode>? executableCodeBlocks) { var codeBlocks = executableCodeBlocks?.Where(c => c != null).AsImmutableOrEmpty() ?? ImmutableArray<SyntaxNode>.Empty; return new DeclarationInfo(node, codeBlocks, declaredSymbol); } internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken) { return GetDeclarationInfo(model, node, getSymbol, (IEnumerable<SyntaxNode>?)null, cancellationToken); } internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, SyntaxNode executableCodeBlock, CancellationToken cancellationToken) { return GetDeclarationInfo(model, node, getSymbol, SpecializedCollections.SingletonEnumerable(executableCodeBlock), cancellationToken); } internal static DeclarationInfo GetDeclarationInfo(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken, params SyntaxNode[] executableCodeBlocks) { return GetDeclarationInfo(model, node, getSymbol, executableCodeBlocks.AsEnumerable(), cancellationToken); } private static ISymbol? GetDeclaredSymbol(SemanticModel model, SyntaxNode node, bool getSymbol, CancellationToken cancellationToken) { if (!getSymbol) { return null; } var declaredSymbol = model.GetDeclaredSymbol(node, cancellationToken); // For namespace declarations, GetDeclaredSymbol returns a compilation scoped namespace symbol, // which includes declarations across the compilation, including those in referenced assemblies. // However, we are only interested in the namespace symbol scoped to the compilation's source assembly. if (declaredSymbol is INamespaceSymbol namespaceSymbol && namespaceSymbol.ConstituentNamespaces.Length > 1) { var assemblyToScope = model.Compilation.Assembly; var assemblyScopedNamespaceSymbol = namespaceSymbol.ConstituentNamespaces.FirstOrDefault(ns => ns.ContainingAssembly == assemblyToScope); if (assemblyScopedNamespaceSymbol != null) { Debug.Assert(assemblyScopedNamespaceSymbol.ConstituentNamespaces.Length == 1); declaredSymbol = assemblyScopedNamespaceSymbol; } } return declaredSymbol; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyleRules.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal class NamingStyleRules { public ImmutableArray<NamingRule> NamingRules { get; } private readonly ImmutableArray<SymbolKind> _symbolKindsThatCanBeOverridden = ImmutableArray.Create( SymbolKind.Method, SymbolKind.Property, SymbolKind.Event); public NamingStyleRules(ImmutableArray<NamingRule> namingRules) => NamingRules = namingRules; internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule) { if (NamingRules != null && IsSymbolNameAnalyzable(symbol)) { foreach (var namingRule in NamingRules) { if (namingRule.SymbolSpecification.AppliesTo(symbol)) { applicableRule = namingRule; return true; } } } applicableRule = default; return false; } private bool IsSymbolNameAnalyzable(ISymbol symbol) { if (_symbolKindsThatCanBeOverridden.Contains(symbol.Kind) && DoesSymbolImplementAnotherSymbol(symbol)) { return false; } if (symbol is IMethodSymbol method) { return method.MethodKind == MethodKind.Ordinary || method.MethodKind == MethodKind.LocalFunction; } if (symbol is IPropertySymbol property) { return !property.IsIndexer; } return true; } private static bool DoesSymbolImplementAnotherSymbol(ISymbol symbol) { if (symbol.IsStatic) { return false; } var containingType = symbol.ContainingType; if (containingType.TypeKind != TypeKind.Class && containingType.TypeKind != TypeKind.Struct) { return false; } return symbol.IsOverride || symbol.ExplicitInterfaceImplementations().Any() || IsInterfaceImplementation(symbol); } /// <summary> /// This does not handle the case where a method in a base type implicitly implements an /// interface method on behalf of one of its derived types. /// </summary> private static bool IsInterfaceImplementation(ISymbol symbol) { if (symbol.DeclaredAccessibility != Accessibility.Public) { return false; } var containingType = symbol.ContainingType; var implementedInterfaces = containingType.AllInterfaces; foreach (var implementedInterface in implementedInterfaces) { var implementedInterfaceMembersWithSameName = implementedInterface.GetMembers(symbol.Name); foreach (var implementedInterfaceMember in implementedInterfaceMembersWithSameName) { if (symbol.Equals(containingType.FindImplementationForInterfaceMember(implementedInterfaceMember))) { return true; } } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal class NamingStyleRules { public ImmutableArray<NamingRule> NamingRules { get; } private readonly ImmutableArray<SymbolKind> _symbolKindsThatCanBeOverridden = ImmutableArray.Create( SymbolKind.Method, SymbolKind.Property, SymbolKind.Event); public NamingStyleRules(ImmutableArray<NamingRule> namingRules) => NamingRules = namingRules; internal bool TryGetApplicableRule(ISymbol symbol, out NamingRule applicableRule) { if (NamingRules != null && IsSymbolNameAnalyzable(symbol)) { foreach (var namingRule in NamingRules) { if (namingRule.SymbolSpecification.AppliesTo(symbol)) { applicableRule = namingRule; return true; } } } applicableRule = default; return false; } private bool IsSymbolNameAnalyzable(ISymbol symbol) { if (_symbolKindsThatCanBeOverridden.Contains(symbol.Kind) && DoesSymbolImplementAnotherSymbol(symbol)) { return false; } if (symbol is IMethodSymbol method) { return method.MethodKind == MethodKind.Ordinary || method.MethodKind == MethodKind.LocalFunction; } if (symbol is IPropertySymbol property) { return !property.IsIndexer; } return true; } private static bool DoesSymbolImplementAnotherSymbol(ISymbol symbol) { if (symbol.IsStatic) { return false; } var containingType = symbol.ContainingType; if (containingType.TypeKind != TypeKind.Class && containingType.TypeKind != TypeKind.Struct) { return false; } return symbol.IsOverride || symbol.ExplicitInterfaceImplementations().Any() || IsInterfaceImplementation(symbol); } /// <summary> /// This does not handle the case where a method in a base type implicitly implements an /// interface method on behalf of one of its derived types. /// </summary> private static bool IsInterfaceImplementation(ISymbol symbol) { if (symbol.DeclaredAccessibility != Accessibility.Public) { return false; } var containingType = symbol.ContainingType; var implementedInterfaces = containingType.AllInterfaces; foreach (var implementedInterface in implementedInterfaces) { var implementedInterfaceMembersWithSameName = implementedInterface.GetMembers(symbol.Name); foreach (var implementedInterfaceMember in implementedInterfaceMembersWithSameName) { if (symbol.Equals(containingType.FindImplementationForInterfaceMember(implementedInterfaceMember))) { return true; } } } return false; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using ASM_CACHE = GlobalAssemblyCacheLocation.ASM_CACHE; /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal sealed class ClrGlobalAssemblyCache : GlobalAssemblyCache { #region Interop private const int MAX_PATH = 260; [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] private interface IAssemblyEnum { [PreserveSig] int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IAssemblyEnum ppEnum); } [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAssemblyCache { void UninstallAssembly(); void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo); void CreateAssemblyCacheItem(); void CreateAssemblyScavenger(); void InstallAssembly(); } [StructLayout(LayoutKind.Sequential)] private unsafe struct ASSEMBLY_INFO { public uint cbAssemblyInfo; public readonly uint dwAssemblyFlags; public readonly ulong uliAssemblySizeInKB; public char* pszCurrentAssemblyPathBuf; public uint cchBuf; } [DllImport("clr", PreserveSig = true)] private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved); [DllImport("clr", PreserveSig = false)] private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); #endregion /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">Optional partial name.</param> /// <param name="architectureFilter">Optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { return GetAssemblyIdentities(FusionAssemblyIdentity.ToAssemblyNameObject(partialName), architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">The optional partial name.</param> /// <param name="architectureFilter">The optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { FusionAssemblyIdentity.IAssemblyName nameObj; if (partialName != null) { nameObj = FusionAssemblyIdentity.ToAssemblyNameObject(partialName); if (nameObj == null) { return SpecializedCollections.EmptyEnumerable<AssemblyIdentity>(); } } else { nameObj = null; } return GetAssemblyIdentities(nameObj, architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning their simple names. /// </summary> /// <param name="architectureFilter">Optional architecture filter.</param> /// <returns>Unique simple names of GAC assemblies.</returns> public override IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { var q = from nameObject in GetAssemblyObjects(partialNameFilter: null, architectureFilter: architectureFilter) select FusionAssemblyIdentity.GetName(nameObject); return q.Distinct(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities( FusionAssemblyIdentity.IAssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter) { return from nameObject in GetAssemblyObjects(partialName, architectureFilter) select FusionAssemblyIdentity.ToAssemblyIdentity(nameObject); } private const int S_OK = 0; private const int S_FALSE = 1; // Internal for testing. internal static IEnumerable<FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects( FusionAssemblyIdentity.IAssemblyName partialNameFilter, ImmutableArray<ProcessorArchitecture> architectureFilter) { IAssemblyEnum enumerator; FusionAssemblyIdentity.IApplicationContext applicationContext = null; int hr = CreateAssemblyEnum(out enumerator, applicationContext, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero); if (hr == S_FALSE) { // no assembly found yield break; } else if (hr != S_OK) { Exception e = Marshal.GetExceptionForHR(hr); if (e is FileNotFoundException || e is DirectoryNotFoundException) { // invalid assembly name: yield break; } else if (e != null) { throw e; } else { // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception: #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName); #else throw new ArgumentException(Editor.EditorFeaturesResources.Invalid_assembly_name); #endif } } while (true) { FusionAssemblyIdentity.IAssemblyName nameObject; hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0); if (hr != 0) { if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } break; } if (!architectureFilter.IsDefault) { var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); if (!architectureFilter.Contains(assemblyArchitecture)) { continue; } } yield return nameObject; } } public override AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter, CultureInfo preferredCulture) { if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } location = null; FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); if (nameObject == null) { return null; } var candidates = GetAssemblyObjects(nameObject, architectureFilter); string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); if (bestMatch == null) { return null; } location = GetAssemblyLocation(bestMatch); return FusionAssemblyIdentity.ToAssemblyIdentity(bestMatch); } internal static unsafe string GetAssemblyLocation(FusionAssemblyIdentity.IAssemblyName nameObject) { // NAME | VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE string fullName = FusionAssemblyIdentity.GetDisplayName(nameObject, FusionAssemblyIdentity.ASM_DISPLAYF.FULL); fixed (char* p = new char[MAX_PATH]) { ASSEMBLY_INFO info = new ASSEMBLY_INFO { cbAssemblyInfo = (uint)Marshal.SizeOf<ASSEMBLY_INFO>(), pszCurrentAssemblyPathBuf = p, cchBuf = MAX_PATH }; IAssemblyCache assemblyCacheObject; CreateAssemblyCache(out assemblyCacheObject, 0); assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); Debug.Assert(info.pszCurrentAssemblyPathBuf != null); Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); Debug.Assert(result.IndexOf('\0') == -1); return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { using ASM_CACHE = GlobalAssemblyCacheLocation.ASM_CACHE; /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal sealed class ClrGlobalAssemblyCache : GlobalAssemblyCache { #region Interop private const int MAX_PATH = 260; [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] private interface IAssemblyEnum { [PreserveSig] int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IAssemblyEnum ppEnum); } [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAssemblyCache { void UninstallAssembly(); void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo); void CreateAssemblyCacheItem(); void CreateAssemblyScavenger(); void InstallAssembly(); } [StructLayout(LayoutKind.Sequential)] private unsafe struct ASSEMBLY_INFO { public uint cbAssemblyInfo; public readonly uint dwAssemblyFlags; public readonly ulong uliAssemblySizeInKB; public char* pszCurrentAssemblyPathBuf; public uint cchBuf; } [DllImport("clr", PreserveSig = true)] private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved); [DllImport("clr", PreserveSig = false)] private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); #endregion /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">Optional partial name.</param> /// <param name="architectureFilter">Optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { return GetAssemblyIdentities(FusionAssemblyIdentity.ToAssemblyNameObject(partialName), architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">The optional partial name.</param> /// <param name="architectureFilter">The optional architecture filter.</param> public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { FusionAssemblyIdentity.IAssemblyName nameObj; if (partialName != null) { nameObj = FusionAssemblyIdentity.ToAssemblyNameObject(partialName); if (nameObj == null) { return SpecializedCollections.EmptyEnumerable<AssemblyIdentity>(); } } else { nameObj = null; } return GetAssemblyIdentities(nameObj, architectureFilter); } /// <summary> /// Enumerates assemblies in the GAC returning their simple names. /// </summary> /// <param name="architectureFilter">Optional architecture filter.</param> /// <returns>Unique simple names of GAC assemblies.</returns> public override IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)) { var q = from nameObject in GetAssemblyObjects(partialNameFilter: null, architectureFilter: architectureFilter) select FusionAssemblyIdentity.GetName(nameObject); return q.Distinct(); } private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities( FusionAssemblyIdentity.IAssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter) { return from nameObject in GetAssemblyObjects(partialName, architectureFilter) select FusionAssemblyIdentity.ToAssemblyIdentity(nameObject); } private const int S_OK = 0; private const int S_FALSE = 1; // Internal for testing. internal static IEnumerable<FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects( FusionAssemblyIdentity.IAssemblyName partialNameFilter, ImmutableArray<ProcessorArchitecture> architectureFilter) { IAssemblyEnum enumerator; FusionAssemblyIdentity.IApplicationContext applicationContext = null; int hr = CreateAssemblyEnum(out enumerator, applicationContext, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero); if (hr == S_FALSE) { // no assembly found yield break; } else if (hr != S_OK) { Exception e = Marshal.GetExceptionForHR(hr); if (e is FileNotFoundException || e is DirectoryNotFoundException) { // invalid assembly name: yield break; } else if (e != null) { throw e; } else { // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception: #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName); #else throw new ArgumentException(Editor.EditorFeaturesResources.Invalid_assembly_name); #endif } } while (true) { FusionAssemblyIdentity.IAssemblyName nameObject; hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0); if (hr != 0) { if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } break; } if (!architectureFilter.IsDefault) { var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); if (!architectureFilter.Contains(assemblyArchitecture)) { continue; } } yield return nameObject; } } public override AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter, CultureInfo preferredCulture) { if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } location = null; FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); if (nameObject == null) { return null; } var candidates = GetAssemblyObjects(nameObject, architectureFilter); string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); if (bestMatch == null) { return null; } location = GetAssemblyLocation(bestMatch); return FusionAssemblyIdentity.ToAssemblyIdentity(bestMatch); } internal static unsafe string GetAssemblyLocation(FusionAssemblyIdentity.IAssemblyName nameObject) { // NAME | VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE string fullName = FusionAssemblyIdentity.GetDisplayName(nameObject, FusionAssemblyIdentity.ASM_DISPLAYF.FULL); fixed (char* p = new char[MAX_PATH]) { ASSEMBLY_INFO info = new ASSEMBLY_INFO { cbAssemblyInfo = (uint)Marshal.SizeOf<ASSEMBLY_INFO>(), pszCurrentAssemblyPathBuf = p, cchBuf = MAX_PATH }; IAssemblyCache assemblyCacheObject; CreateAssemblyCache(out assemblyCacheObject, 0); assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); Debug.Assert(info.pszCurrentAssemblyPathBuf != null); Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); Debug.Assert(result.IndexOf('\0') == -1); return result; } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Analyzers/CSharp/Analyzers/UseNullPropagation/CSharpUseNullPropagationDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.UseNullPropagation; namespace Microsoft.CodeAnalysis.CSharp.UseNullPropagation { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseNullPropagationDiagnosticAnalyzer : AbstractUseNullPropagationDiagnosticAnalyzer< SyntaxKind, ExpressionSyntax, ConditionalExpressionSyntax, BinaryExpressionSyntax, InvocationExpressionSyntax, MemberAccessExpressionSyntax, ConditionalAccessExpressionSyntax, ElementAccessExpressionSyntax> { protected override bool ShouldAnalyze(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken) => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken); protected override bool TryAnalyzePatternCondition( ISyntaxFacts syntaxFacts, SyntaxNode conditionNode, [NotNullWhen(true)] out SyntaxNode? conditionPartToCheck, out bool isEquals) { conditionPartToCheck = null; isEquals = true; if (!(conditionNode is IsPatternExpressionSyntax patternExpression)) { return false; } if (!(patternExpression.Pattern is ConstantPatternSyntax constantPattern)) { return false; } if (!syntaxFacts.IsNullLiteralExpression(constantPattern.Expression)) { return false; } conditionPartToCheck = patternExpression.Expression; 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.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.UseNullPropagation; namespace Microsoft.CodeAnalysis.CSharp.UseNullPropagation { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseNullPropagationDiagnosticAnalyzer : AbstractUseNullPropagationDiagnosticAnalyzer< SyntaxKind, ExpressionSyntax, ConditionalExpressionSyntax, BinaryExpressionSyntax, InvocationExpressionSyntax, MemberAccessExpressionSyntax, ConditionalAccessExpressionSyntax, ElementAccessExpressionSyntax> { protected override bool ShouldAnalyze(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken) => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken); protected override bool TryAnalyzePatternCondition( ISyntaxFacts syntaxFacts, SyntaxNode conditionNode, [NotNullWhen(true)] out SyntaxNode? conditionPartToCheck, out bool isEquals) { conditionPartToCheck = null; isEquals = true; if (!(conditionNode is IsPatternExpressionSyntax patternExpression)) { return false; } if (!(patternExpression.Pattern is ConstantPatternSyntax constantPattern)) { return false; } if (!syntaxFacts.IsNullLiteralExpression(constantPattern.Expression)) { return false; } conditionPartToCheck = patternExpression.Expression; return true; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/UsingBlockHighlighter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class UsingBlockHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken) Dim usingBlock = node.GetAncestor(Of UsingBlockSyntax)() If usingBlock Is Nothing Then Return End If With usingBlock highlights.Add(.UsingStatement.UsingKeyword.Span) highlights.Add(.EndUsingStatement.Span) End With End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class UsingBlockHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken) Dim usingBlock = node.GetAncestor(Of UsingBlockSyntax)() If usingBlock Is Nothing Then Return End If With usingBlock highlights.Add(.UsingStatement.UsingKeyword.Span) highlights.Add(.EndUsingStatement.Span) End With End Sub End Class End Namespace
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/CSharp/Portable/CodeFixes/MakeStatementAsynchronous/CSharpMakeStatementAsynchronousCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.MakeStatementAsynchronous { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeStatementAsynchronous), Shared] internal class CSharpMakeStatementAsynchronousCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpMakeStatementAsynchronousCodeFixProvider() { } // error CS8414: foreach statement cannot operate on variables of type 'IAsyncEnumerable<int>' because 'IAsyncEnumerable<int>' does not contain a public instance definition for 'GetEnumerator'. Did you mean 'await foreach'? // error CS8418: 'IAsyncDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using' rather than 'using'? public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create("CS8414", "CS8418"); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); var constructToFix = TryGetStatementToFix(node); if (constructToFix == null) { return; } context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, diagnostic, c)), context.Diagnostics); } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); var statementToFix = TryGetStatementToFix(node); if (statementToFix != null) { MakeStatementAsynchronous(editor, statementToFix); } } return Task.CompletedTask; } private static void MakeStatementAsynchronous(SyntaxEditor editor, SyntaxNode statementToFix) { SyntaxNode newStatement; switch (statementToFix) { case ForEachStatementSyntax forEach: newStatement = forEach .WithForEachKeyword(forEach.ForEachKeyword.WithLeadingTrivia()) .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(forEach.GetLeadingTrivia())); break; case ForEachVariableStatementSyntax forEachDeconstruction: newStatement = forEachDeconstruction .WithForEachKeyword(forEachDeconstruction.ForEachKeyword.WithLeadingTrivia()) .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(forEachDeconstruction.GetLeadingTrivia())); break; case UsingStatementSyntax usingStatement: newStatement = usingStatement .WithUsingKeyword(usingStatement.UsingKeyword.WithLeadingTrivia()) .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(usingStatement.GetLeadingTrivia())); break; case LocalDeclarationStatementSyntax localDeclaration: newStatement = localDeclaration .WithUsingKeyword(localDeclaration.UsingKeyword.WithLeadingTrivia()) .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(localDeclaration.GetLeadingTrivia())); break; default: return; } editor.ReplaceNode(statementToFix, newStatement); } private static SyntaxNode TryGetStatementToFix(SyntaxNode node) { if (node.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement, SyntaxKind.UsingStatement)) { return node.Parent; } if (node is LocalDeclarationStatementSyntax localDeclaration && localDeclaration.UsingKeyword != default) { return node; } return null; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Add_await, createChangedDocument, CSharpFeaturesResources.Add_await) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.MakeStatementAsynchronous { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeStatementAsynchronous), Shared] internal class CSharpMakeStatementAsynchronousCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpMakeStatementAsynchronousCodeFixProvider() { } // error CS8414: foreach statement cannot operate on variables of type 'IAsyncEnumerable<int>' because 'IAsyncEnumerable<int>' does not contain a public instance definition for 'GetEnumerator'. Did you mean 'await foreach'? // error CS8418: 'IAsyncDisposable': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Did you mean 'await using' rather than 'using'? public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create("CS8414", "CS8418"); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.Compile; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); var constructToFix = TryGetStatementToFix(node); if (constructToFix == null) { return; } context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, diagnostic, c)), context.Diagnostics); } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); var statementToFix = TryGetStatementToFix(node); if (statementToFix != null) { MakeStatementAsynchronous(editor, statementToFix); } } return Task.CompletedTask; } private static void MakeStatementAsynchronous(SyntaxEditor editor, SyntaxNode statementToFix) { SyntaxNode newStatement; switch (statementToFix) { case ForEachStatementSyntax forEach: newStatement = forEach .WithForEachKeyword(forEach.ForEachKeyword.WithLeadingTrivia()) .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(forEach.GetLeadingTrivia())); break; case ForEachVariableStatementSyntax forEachDeconstruction: newStatement = forEachDeconstruction .WithForEachKeyword(forEachDeconstruction.ForEachKeyword.WithLeadingTrivia()) .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(forEachDeconstruction.GetLeadingTrivia())); break; case UsingStatementSyntax usingStatement: newStatement = usingStatement .WithUsingKeyword(usingStatement.UsingKeyword.WithLeadingTrivia()) .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(usingStatement.GetLeadingTrivia())); break; case LocalDeclarationStatementSyntax localDeclaration: newStatement = localDeclaration .WithUsingKeyword(localDeclaration.UsingKeyword.WithLeadingTrivia()) .WithAwaitKeyword(SyntaxFactory.Token(SyntaxKind.AwaitKeyword).WithLeadingTrivia(localDeclaration.GetLeadingTrivia())); break; default: return; } editor.ReplaceNode(statementToFix, newStatement); } private static SyntaxNode TryGetStatementToFix(SyntaxNode node) { if (node.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement, SyntaxKind.UsingStatement)) { return node.Parent; } if (node is LocalDeclarationStatementSyntax localDeclaration && localDeclaration.UsingKeyword != default) { return node; } return null; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Add_await, createChangedDocument, CSharpFeaturesResources.Add_await) { } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Impl/CodeModel/ICodeModelService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface ICodeModelService : ICodeModelNavigationPointService { /// <summary> /// Retrieves the Option nodes (i.e. VB Option statements) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent); /// <summary> /// Retrieves the import nodes (e.g. using/Import directives) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent); /// <summary> /// Retrieves the attributes parented or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent); /// <summary> /// Retrieves the attribute arguments parented by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent); /// <summary> /// Retrieves the Inherits nodes (i.e. VB Inherits statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent); /// <summary> /// Retrieves the Implements nodes (i.e. VB Implements statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent); /// <summary> /// Retrieves the members of a specified <paramref name="container"/> node. The members that are /// returned can be controlled by passing various parameters. /// </summary> /// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param> /// <param name="includeSelf">If true, the container is returned as well.</param> /// <param name="recursive">If true, members are recursed to return descendant members as well /// as immediate children. For example, a namespace would return the namespaces and types within. /// However, if <paramref name="recursive"/> is true, members with the namespaces and types would /// also be returned.</param> /// <param name="logicalFields">If true, field declarations are broken into their respective declarators. /// For example, the field "int x, y" would return two declarators, one for x and one for y in place /// of the field.</param> /// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param> IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes); IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container); SyntaxNodeKey GetNodeKey(SyntaxNode node); SyntaxNodeKey TryGetNodeKey(SyntaxNode node); SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree); bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node); bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope); string Language { get; } string AssemblyAttributeString { get; } /// <summary> /// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/> /// </summary> EnvDTE.CodeElement CreateInternalCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol); EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel); EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol); /// <summary> /// Used by RootCodeModel.CreateCodeTypeRef to create an EnvDTE.CodeTypeRef. /// </summary> EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type); EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol); bool IsParameterNode(SyntaxNode node); bool IsAttributeNode(SyntaxNode node); bool IsAttributeArgumentNode(SyntaxNode node); bool IsOptionNode(SyntaxNode node); bool IsImportNode(SyntaxNode node); ISymbol ResolveSymbol(Microsoft.CodeAnalysis.Workspace workspace, ProjectId projectId, SymbolKey symbolId); string GetUnescapedName(string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.Name property. /// </summary> string GetName(SyntaxNode node); SyntaxNode GetNodeWithName(SyntaxNode node); SyntaxNode SetName(SyntaxNode node, string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property. /// </summary> string GetFullName(SyntaxNode node, SemanticModel semanticModel); /// <summary> /// Given a name, attempts to convert it to a fully qualified name. /// </summary> string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel); void Rename(ISymbol symbol, string newName, Workspace workspace, ProjectCodeModelFactory projectCodeModelFactory); /// <summary> /// Returns true if the given <paramref name="symbol"/> can be used to create an external code element; otherwise, false. /// </summary> bool IsValidExternalSymbol(ISymbol symbol); /// <summary> /// Returns the value to be returned from <see cref="EnvDTE.CodeElement.Name"/> for external code elements. /// </summary> string GetExternalSymbolName(ISymbol symbol); /// <summary> /// Retrieves the value to be returned from <see cref="EnvDTE.CodeElement.FullName"/> for external code elements. /// </summary> string GetExternalSymbolFullName(ISymbol symbol); SyntaxNode GetNodeWithModifiers(SyntaxNode node); SyntaxNode GetNodeWithType(SyntaxNode node); SyntaxNode GetNodeWithInitializer(SyntaxNode node); EnvDTE.vsCMAccess GetAccess(ISymbol symbol); EnvDTE.vsCMAccess GetAccess(SyntaxNode node); SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access); EnvDTE.vsCMElement GetElementKind(SyntaxNode node); bool IsExpressionBodiedProperty(SyntaxNode node); bool IsAccessorNode(SyntaxNode node); MethodKind GetAccessorKind(SyntaxNode node); bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode); bool TryGetAutoPropertyExpressionBody(SyntaxNode parentNode, out SyntaxNode expressionBody); bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode); bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode); bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode); bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode); bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode); bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode); bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode); void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal); void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal); void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal); void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index); void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal); SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode); string GetAttributeTarget(SyntaxNode attributeNode); string GetAttributeValue(SyntaxNode attributeNode); SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value); SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value); /// <summary> /// Given a node, finds the related node that holds on to the attribute information. /// Generally, this will be an ancestor node. For example, given a C# VariableDeclarator, /// looks up the syntax tree to find the FieldDeclaration. /// </summary> SyntaxNode GetNodeWithAttributes(SyntaxNode node); /// <summary> /// Given node for an attribute, returns a node that can represent the parent. /// For example, an attribute on a C# field cannot use the FieldDeclaration (as it is /// not keyed) but instead must use one of the FieldDeclaration's VariableDeclarators. /// </summary> SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node); SyntaxNode CreateAttributeNode(string name, string value, string target = null); SyntaxNode CreateAttributeArgumentNode(string name, string value); SyntaxNode CreateImportNode(string name, string alias = null); SyntaxNode CreateParameterNode(string name, string type); string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode); string GetImportAlias(SyntaxNode node); string GetImportNamespaceOrType(SyntaxNode node); string GetParameterName(SyntaxNode node); string GetParameterFullName(SyntaxNode node); EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node); SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind); IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent); EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode); EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name); bool SupportsEventThrower { get; } bool GetCanOverride(SyntaxNode memberNode); SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value); EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind); string GetComment(SyntaxNode node); SyntaxNode SetComment(SyntaxNode node, string value); EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode); SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind); EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol); SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind); string GetDocComment(SyntaxNode node); SyntaxNode SetDocComment(SyntaxNode node, string value); EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol); EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetInheritanceKind(SyntaxNode node, EnvDTE80.vsCMInheritanceKind kind); bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value); bool GetIsConstant(SyntaxNode memberNode); SyntaxNode SetIsConstant(SyntaxNode memberNode, bool value); bool GetIsDefault(SyntaxNode propertyNode); SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value); bool GetIsGeneric(SyntaxNode memberNode); bool GetIsPropertyStyleEvent(SyntaxNode eventNode); bool GetIsShared(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsShared(SyntaxNode memberNode, bool value); bool GetMustImplement(SyntaxNode memberNode); SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value); EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode); SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind); EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode); SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol); Document Delete(Document document, SyntaxNode node); string GetMethodXml(SyntaxNode node, SemanticModel semanticModel); string GetInitExpression(SyntaxNode node); SyntaxNode AddInitExpression(SyntaxNode node, string value); CodeGenerationDestination GetDestination(SyntaxNode containerNode); /// <summary> /// Retrieves the Accessibility for an EnvDTE.vsCMAccess. If the specified value is /// EnvDTE.vsCMAccess.vsCMAccessDefault, then the SymbolKind and CodeGenerationDestination hints /// will be used to retrieve the correct Accessibility for the current language. /// </summary> Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified); bool GetWithEvents(EnvDTE.vsCMAccess access); /// <summary> /// Given an "type" argument received from a CodeModel client, converts it to an ITypeSymbol. Note that /// this parameter is a VARIANT and could be an EnvDTE.vsCMTypeRef, a string representing a fully-qualified /// type name, or an EnvDTE.CodeTypeRef. /// </summary> ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position); ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation); SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type); int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); SyntaxNode InsertAttribute( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertAttributeArgument( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeArgumentNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertImport( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode importNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertMember( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode newMemberNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertParameter( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode parameterNode, CancellationToken cancellationToken, out Document newDocument); Document UpdateNode( Document document, SyntaxNode node, SyntaxNode newNode, CancellationToken cancellationToken); Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree); bool IsNamespace(SyntaxNode node); bool IsType(SyntaxNode node); IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel); bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel); Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); string[] GetFunctionExtenderNames(); object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetPropertyExtenderNames(); object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetExternalTypeExtenderNames(); object GetExternalTypeExtender(string name, string externalLocation); string[] GetTypeExtenderNames(); object GetTypeExtender(string name, AbstractCodeType codeType); bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags); void AttachFormatTrackingToBuffer(ITextBuffer buffer); void DetachFormatTrackingToBuffer(ITextBuffer buffer); void EnsureBufferFormatted(ITextBuffer buffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface ICodeModelService : ICodeModelNavigationPointService { /// <summary> /// Retrieves the Option nodes (i.e. VB Option statements) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent); /// <summary> /// Retrieves the import nodes (e.g. using/Import directives) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent); /// <summary> /// Retrieves the attributes parented or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent); /// <summary> /// Retrieves the attribute arguments parented by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent); /// <summary> /// Retrieves the Inherits nodes (i.e. VB Inherits statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent); /// <summary> /// Retrieves the Implements nodes (i.e. VB Implements statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent); /// <summary> /// Retrieves the members of a specified <paramref name="container"/> node. The members that are /// returned can be controlled by passing various parameters. /// </summary> /// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param> /// <param name="includeSelf">If true, the container is returned as well.</param> /// <param name="recursive">If true, members are recursed to return descendant members as well /// as immediate children. For example, a namespace would return the namespaces and types within. /// However, if <paramref name="recursive"/> is true, members with the namespaces and types would /// also be returned.</param> /// <param name="logicalFields">If true, field declarations are broken into their respective declarators. /// For example, the field "int x, y" would return two declarators, one for x and one for y in place /// of the field.</param> /// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param> IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes); IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container); SyntaxNodeKey GetNodeKey(SyntaxNode node); SyntaxNodeKey TryGetNodeKey(SyntaxNode node); SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree); bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node); bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope); string Language { get; } string AssemblyAttributeString { get; } /// <summary> /// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/> /// </summary> EnvDTE.CodeElement CreateInternalCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol); EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel); EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol); /// <summary> /// Used by RootCodeModel.CreateCodeTypeRef to create an EnvDTE.CodeTypeRef. /// </summary> EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type); EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol); bool IsParameterNode(SyntaxNode node); bool IsAttributeNode(SyntaxNode node); bool IsAttributeArgumentNode(SyntaxNode node); bool IsOptionNode(SyntaxNode node); bool IsImportNode(SyntaxNode node); ISymbol ResolveSymbol(Microsoft.CodeAnalysis.Workspace workspace, ProjectId projectId, SymbolKey symbolId); string GetUnescapedName(string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.Name property. /// </summary> string GetName(SyntaxNode node); SyntaxNode GetNodeWithName(SyntaxNode node); SyntaxNode SetName(SyntaxNode node, string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property. /// </summary> string GetFullName(SyntaxNode node, SemanticModel semanticModel); /// <summary> /// Given a name, attempts to convert it to a fully qualified name. /// </summary> string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel); void Rename(ISymbol symbol, string newName, Workspace workspace, ProjectCodeModelFactory projectCodeModelFactory); /// <summary> /// Returns true if the given <paramref name="symbol"/> can be used to create an external code element; otherwise, false. /// </summary> bool IsValidExternalSymbol(ISymbol symbol); /// <summary> /// Returns the value to be returned from <see cref="EnvDTE.CodeElement.Name"/> for external code elements. /// </summary> string GetExternalSymbolName(ISymbol symbol); /// <summary> /// Retrieves the value to be returned from <see cref="EnvDTE.CodeElement.FullName"/> for external code elements. /// </summary> string GetExternalSymbolFullName(ISymbol symbol); SyntaxNode GetNodeWithModifiers(SyntaxNode node); SyntaxNode GetNodeWithType(SyntaxNode node); SyntaxNode GetNodeWithInitializer(SyntaxNode node); EnvDTE.vsCMAccess GetAccess(ISymbol symbol); EnvDTE.vsCMAccess GetAccess(SyntaxNode node); SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access); EnvDTE.vsCMElement GetElementKind(SyntaxNode node); bool IsExpressionBodiedProperty(SyntaxNode node); bool IsAccessorNode(SyntaxNode node); MethodKind GetAccessorKind(SyntaxNode node); bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode); bool TryGetAutoPropertyExpressionBody(SyntaxNode parentNode, out SyntaxNode expressionBody); bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode); bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode); bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode); bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode); bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode); bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode); bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode); void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal); void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal); void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal); void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index); void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal); SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode); string GetAttributeTarget(SyntaxNode attributeNode); string GetAttributeValue(SyntaxNode attributeNode); SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value); SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value); /// <summary> /// Given a node, finds the related node that holds on to the attribute information. /// Generally, this will be an ancestor node. For example, given a C# VariableDeclarator, /// looks up the syntax tree to find the FieldDeclaration. /// </summary> SyntaxNode GetNodeWithAttributes(SyntaxNode node); /// <summary> /// Given node for an attribute, returns a node that can represent the parent. /// For example, an attribute on a C# field cannot use the FieldDeclaration (as it is /// not keyed) but instead must use one of the FieldDeclaration's VariableDeclarators. /// </summary> SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node); SyntaxNode CreateAttributeNode(string name, string value, string target = null); SyntaxNode CreateAttributeArgumentNode(string name, string value); SyntaxNode CreateImportNode(string name, string alias = null); SyntaxNode CreateParameterNode(string name, string type); string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode); string GetImportAlias(SyntaxNode node); string GetImportNamespaceOrType(SyntaxNode node); string GetParameterName(SyntaxNode node); string GetParameterFullName(SyntaxNode node); EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node); SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind); IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent); EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode); EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name); bool SupportsEventThrower { get; } bool GetCanOverride(SyntaxNode memberNode); SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value); EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind); string GetComment(SyntaxNode node); SyntaxNode SetComment(SyntaxNode node, string value); EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode); SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind); EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol); SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind); string GetDocComment(SyntaxNode node); SyntaxNode SetDocComment(SyntaxNode node, string value); EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol); EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetInheritanceKind(SyntaxNode node, EnvDTE80.vsCMInheritanceKind kind); bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value); bool GetIsConstant(SyntaxNode memberNode); SyntaxNode SetIsConstant(SyntaxNode memberNode, bool value); bool GetIsDefault(SyntaxNode propertyNode); SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value); bool GetIsGeneric(SyntaxNode memberNode); bool GetIsPropertyStyleEvent(SyntaxNode eventNode); bool GetIsShared(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsShared(SyntaxNode memberNode, bool value); bool GetMustImplement(SyntaxNode memberNode); SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value); EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode); SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind); EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode); SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol); Document Delete(Document document, SyntaxNode node); string GetMethodXml(SyntaxNode node, SemanticModel semanticModel); string GetInitExpression(SyntaxNode node); SyntaxNode AddInitExpression(SyntaxNode node, string value); CodeGenerationDestination GetDestination(SyntaxNode containerNode); /// <summary> /// Retrieves the Accessibility for an EnvDTE.vsCMAccess. If the specified value is /// EnvDTE.vsCMAccess.vsCMAccessDefault, then the SymbolKind and CodeGenerationDestination hints /// will be used to retrieve the correct Accessibility for the current language. /// </summary> Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified); bool GetWithEvents(EnvDTE.vsCMAccess access); /// <summary> /// Given an "type" argument received from a CodeModel client, converts it to an ITypeSymbol. Note that /// this parameter is a VARIANT and could be an EnvDTE.vsCMTypeRef, a string representing a fully-qualified /// type name, or an EnvDTE.CodeTypeRef. /// </summary> ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position); ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation); SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type); int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); SyntaxNode InsertAttribute( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertAttributeArgument( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeArgumentNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertImport( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode importNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertMember( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode newMemberNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertParameter( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode parameterNode, CancellationToken cancellationToken, out Document newDocument); Document UpdateNode( Document document, SyntaxNode node, SyntaxNode newNode, CancellationToken cancellationToken); Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree); bool IsNamespace(SyntaxNode node); bool IsType(SyntaxNode node); IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel); bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel); Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); string[] GetFunctionExtenderNames(); object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetPropertyExtenderNames(); object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetExternalTypeExtenderNames(); object GetExternalTypeExtender(string name, string externalLocation); string[] GetTypeExtenderNames(); object GetTypeExtender(string name, AbstractCodeType codeType); bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags); void AttachFormatTrackingToBuffer(ITextBuffer buffer); void DetachFormatTrackingToBuffer(ITextBuffer buffer); void EnsureBufferFormatted(ITextBuffer buffer); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/TestUtilities/AbstractTypingCommandHandlerTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [UseExportProvider] public abstract class AbstractTypingCommandHandlerTest<TCommandArgs> where TCommandArgs : CommandArgs { internal abstract ICommandHandler<TCommandArgs> GetCommandHandler(TestWorkspace workspace); protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup); protected abstract (TCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer); protected void Verify(string initialMarkup, string expectedMarkup, Action<TestWorkspace> initializeWorkspace = null) { using (var workspace = CreateTestWorkspace(initialMarkup)) { initializeWorkspace?.Invoke(workspace); var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var (args, insertionText) = CreateCommandArgs(view, view.TextBuffer); var nextHandler = CreateInsertTextHandler(view, insertionText); if (!commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create())) { nextHandler(); } MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } } protected void VerifyTabs(string initialMarkup, string expectedMarkup) => Verify(ReplaceTabTags(initialMarkup), ReplaceTabTags(expectedMarkup)); private static string ReplaceTabTags(string markup) => markup.Replace("<tab>", "\t"); private static Action CreateInsertTextHandler(ITextView textView, string text) { return () => { var caretPosition = textView.Caret.Position.BufferPosition; var newSpanshot = textView.TextBuffer.Insert(caretPosition, text); textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, (int)caretPosition + text.Length)); }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [UseExportProvider] public abstract class AbstractTypingCommandHandlerTest<TCommandArgs> where TCommandArgs : CommandArgs { internal abstract ICommandHandler<TCommandArgs> GetCommandHandler(TestWorkspace workspace); protected abstract TestWorkspace CreateTestWorkspace(string initialMarkup); protected abstract (TCommandArgs, string insertionText) CreateCommandArgs(ITextView textView, ITextBuffer textBuffer); protected void Verify(string initialMarkup, string expectedMarkup, Action<TestWorkspace> initializeWorkspace = null) { using (var workspace = CreateTestWorkspace(initialMarkup)) { initializeWorkspace?.Invoke(workspace); var testDocument = workspace.Documents.Single(); var view = testDocument.GetTextView(); view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value)); var commandHandler = GetCommandHandler(workspace); var (args, insertionText) = CreateCommandArgs(view, view.TextBuffer); var nextHandler = CreateInsertTextHandler(view, insertionText); if (!commandHandler.ExecuteCommand(args, TestCommandExecutionContext.Create())) { nextHandler(); } MarkupTestFile.GetPosition(expectedMarkup, out var expectedCode, out int expectedPosition); Assert.Equal(expectedCode, view.TextSnapshot.GetText()); var caretPosition = view.Caret.Position.BufferPosition.Position; Assert.True(expectedPosition == caretPosition, string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition)); } } protected void VerifyTabs(string initialMarkup, string expectedMarkup) => Verify(ReplaceTabTags(initialMarkup), ReplaceTabTags(expectedMarkup)); private static string ReplaceTabTags(string markup) => markup.Replace("<tab>", "\t"); private static Action CreateInsertTextHandler(ITextView textView, string text) { return () => { var caretPosition = textView.Caret.Position.BufferPosition; var newSpanshot = textView.TextBuffer.Insert(caretPosition, text); textView.Caret.MoveTo(new SnapshotPoint(newSpanshot, (int)caretPosition + text.Length)); }; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Def/Implementation/Log/VisualStudioErrorLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using static Microsoft.CodeAnalysis.RoslynAssemblyHelper; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Log { [ExportWorkspaceService(typeof(IErrorLoggerService), ServiceLayer.Host), Export(typeof(IErrorLoggerService)), Shared] internal class VisualStudioErrorLogger : IErrorLoggerService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioErrorLogger() { } public void LogException(object source, Exception exception) { var name = source.GetType().Name; ActivityLog.LogError(name, ToLogFormat(exception)); if (ShouldReportCrashDumps(source)) { FatalError.ReportAndCatch(exception); } } private bool ShouldReportCrashDumps(object source) => HasRoslynPublicKey(source); private static string ToLogFormat(Exception exception) => exception.Message + Environment.NewLine + exception.StackTrace; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using static Microsoft.CodeAnalysis.RoslynAssemblyHelper; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Log { [ExportWorkspaceService(typeof(IErrorLoggerService), ServiceLayer.Host), Export(typeof(IErrorLoggerService)), Shared] internal class VisualStudioErrorLogger : IErrorLoggerService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioErrorLogger() { } public void LogException(object source, Exception exception) { var name = source.GetType().Name; ActivityLog.LogError(name, ToLogFormat(exception)); if (ShouldReportCrashDumps(source)) { FatalError.ReportAndCatch(exception); } } private bool ShouldReportCrashDumps(object source) => HasRoslynPublicKey(source); private static string ToLogFormat(Exception exception) => exception.Message + Environment.NewLine + exception.StackTrace; } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/Core/Extensibility/SignatureHelp/PredefinedSignatureHelpPresenterNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 PredefinedSignatureHelpPresenterNames { public const string RoslynSignatureHelpPresenter = "Roslyn Signature Help Presenter"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 PredefinedSignatureHelpPresenterNames { public const string RoslynSignatureHelpPresenter = "Roslyn Signature Help Presenter"; } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Model/PredefinedNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 CSharpSyntaxGenerator { public class PredefinedNode : TreeType { } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 CSharpSyntaxGenerator { public class PredefinedNode : TreeType { } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/VisualBasic/Portable/ConvertCast/VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertCast Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast), [Shared]> Friend Class VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider Inherits AbstractConvertCastCodeRefactoringProvider(Of TypeSyntax, TryCastExpressionSyntax, DirectCastExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetTitle() As String Return VBFeaturesResources.Change_to_DirectCast End Function Protected Overrides ReadOnly Property FromKind As Integer = SyntaxKind.TryCastExpression Protected Overrides Function GetTypeNode(from As TryCastExpressionSyntax) As TypeSyntax Return from.Type End Function Protected Overrides Function ConvertExpression(fromExpression As TryCastExpressionSyntax) As DirectCastExpressionSyntax Return SyntaxFactory.DirectCastExpression( SyntaxFactory.Token(SyntaxKind.DirectCastKeyword), fromExpression.OpenParenToken, fromExpression.Expression, fromExpression.CommaToken, fromExpression.Type, fromExpression.CloseParenToken) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertCast Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast), [Shared]> Friend Class VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider Inherits AbstractConvertCastCodeRefactoringProvider(Of TypeSyntax, TryCastExpressionSyntax, DirectCastExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetTitle() As String Return VBFeaturesResources.Change_to_DirectCast End Function Protected Overrides ReadOnly Property FromKind As Integer = SyntaxKind.TryCastExpression Protected Overrides Function GetTypeNode(from As TryCastExpressionSyntax) As TypeSyntax Return from.Type End Function Protected Overrides Function ConvertExpression(fromExpression As TryCastExpressionSyntax) As DirectCastExpressionSyntax Return SyntaxFactory.DirectCastExpression( SyntaxFactory.Token(SyntaxKind.DirectCastKeyword), fromExpression.OpenParenToken, fromExpression.Expression, fromExpression.CommaToken, fromExpression.Type, fromExpression.CloseParenToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/Differencing/LongestCommonSubsequence.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { internal abstract class LongestCommonSubsequence { // Define the pool in a non-generic base class to allow sharing among instantiations. private static readonly ObjectPool<VBuffer> s_pool = new(() => new VBuffer()); /// <summary> /// Underlying storage for <see cref="VArray"/>s allocated on <see cref="VStack"/>. /// </summary> /// <remarks> /// The LCS algorithm allocates <see cref="VArray"/>s of sizes (3, 2*1 + 1, ..., 2*D + 1), always in this order, /// where D is at most the sum of lengths of the compared sequences. /// The arrays get pushed on a stack as they are built up, then all consumed in the reverse order (stack pop). /// /// Since the exact length of each array in the above sequence is known we avoid allocating each individual array. /// Instead we allocate a large buffer serving as a a backing storage of a contiguous sequence of arrays /// corresponding to stack depths <see cref="MinDepth"/> to <see cref="MaxDepth"/>. /// If more storage is needed we chain next large buffer to the previous one in a linked list. /// /// We pool a few of these linked buffers on <see cref="VStack"/> to conserve allocations. /// </remarks> protected sealed class VBuffer { /// <summary> /// The max stack depth backed by the fist buffer. /// Size of the buffer for 100 is ~10K. /// For 150 it'd be 91KB, which would be allocated on LOH. /// The buffers grow by factor of <see cref="GrowFactor"/>, so the next buffer will be allocated on LOH. /// </summary> private const int FirstBufferMaxDepth = 100; // 3 + Sum { d = 1..maxDepth : 2*d+1 } = (maxDepth + 1)^2 + 2 private const int FirstBufferLength = (FirstBufferMaxDepth + 1) * (FirstBufferMaxDepth + 1) + 2; internal const int GrowFactor = 2; /// <summary> /// Do not pool segments that are too large. /// </summary> internal const int MaxPooledBufferSize = 1024 * 1024; public VBuffer Previous { get; private set; } public VBuffer Next { get; private set; } public readonly int MinDepth; public readonly int MaxDepth; private readonly int[] _array; public VBuffer() { _array = new int[FirstBufferLength]; MaxDepth = FirstBufferMaxDepth; } public VBuffer(VBuffer previous) { Debug.Assert(previous != null); var minDepth = previous.MaxDepth + 1; var maxDepth = previous.MaxDepth * GrowFactor; Debug.Assert(minDepth > 0); Debug.Assert(minDepth <= maxDepth); Previous = previous; _array = new int[GetNextBufferLength(minDepth - 1, maxDepth)]; MinDepth = minDepth; MaxDepth = maxDepth; previous.Next = this; } public VArray GetVArray(int depth) { var length = GetVArrayLength(depth); var start = GetVArrayStart(depth) - GetVArrayStart(MinDepth); Debug.Assert(start >= 0); Debug.Assert(start + length <= _array.Length); return new VArray(_array, start, length); } public bool IsTooLargeToPool => _array.Length > MaxPooledBufferSize; private static int GetVArrayLength(int depth) => 2 * Math.Max(depth, 1) + 1; // 3 + Sum { d = 1..depth-1 : 2*d+1 } = depth^2 + 2 private static int GetVArrayStart(int depth) => (depth == 0) ? 0 : depth * depth + 2; // Sum { d = previousChunkDepth..maxDepth : 2*d+1 } = (maxDepth + 1)^2 - precedingBufferMaxDepth^2 private static int GetNextBufferLength(int precedingBufferMaxDepth, int maxDepth) => (maxDepth + 1) * (maxDepth + 1) - precedingBufferMaxDepth * precedingBufferMaxDepth; public void Unlink() { Previous.Next = null; Previous = null; } } protected struct VStack { private readonly ObjectPool<VBuffer> _bufferPool; private readonly VBuffer _firstBuffer; private VBuffer _currentBuffer; private int _depth; public VStack(ObjectPool<VBuffer> bufferPool) { _bufferPool = bufferPool; _currentBuffer = _firstBuffer = bufferPool.Allocate(); _depth = 0; } public VArray Push() { var depth = _depth++; if (depth > _currentBuffer.MaxDepth) { // If the buffer is not big enough add another segment to the linked list (the constructor takes care of the linking). // Note that the segments are not pooled on their own. The whole linked list of buffers is pooled. _currentBuffer = _currentBuffer.Next ?? new VBuffer(_currentBuffer); } return _currentBuffer.GetVArray(depth); } public IEnumerable<(VArray Array, int Depth)> ConsumeArrays() { var buffer = _currentBuffer; for (var depth = _depth - 1; depth >= 0; depth--) { if (depth < buffer.MinDepth) { var previousBuffer = buffer.Previous; // Trim large buffers from the linked list before we return the whole list back into the pool. if (buffer.IsTooLargeToPool) { buffer.Unlink(); } buffer = previousBuffer; } yield return (buffer.GetVArray(depth), depth); } _bufferPool.Free(_firstBuffer); _currentBuffer = null; } } // VArray struct enables array indexing in range [-d...d]. protected readonly struct VArray { private readonly int[] _buffer; private readonly int _start; private readonly int _length; public VArray(int[] buffer, int start, int length) { _buffer = buffer; _start = start; _length = length; } public void InitializeFrom(VArray other) { int dstCopyStart, srcCopyStart, copyLength; var copyDelta = Offset - other.Offset; if (copyDelta >= 0) { srcCopyStart = 0; dstCopyStart = copyDelta; copyLength = other._length; } else { srcCopyStart = -copyDelta; dstCopyStart = 0; copyLength = _length; } // since we might be reusing previously used arrays, we need to clear slots that are not copied over from the other array: Array.Clear(_buffer, _start, dstCopyStart); Array.Copy(other._buffer, other._start + srcCopyStart, _buffer, _start + dstCopyStart, copyLength); Array.Clear(_buffer, _start + dstCopyStart + copyLength, _length - dstCopyStart - copyLength); } internal void Initialize() => Array.Clear(_buffer, _start, _length); public int this[int index] { get => _buffer[_start + index + Offset]; set => _buffer[_start + index + Offset] = value; } private int Offset => _length / 2; } protected static VStack CreateStack() => new(s_pool); } /// <summary> /// Calculates Longest Common Subsequence. /// </summary> internal abstract class LongestCommonSubsequence<TSequence> : LongestCommonSubsequence { protected abstract bool ItemsEqual(TSequence oldSequence, int oldIndex, TSequence newSequence, int newIndex); // TODO: Consolidate return types between GetMatchingPairs and GetEdit to avoid duplicated code (https://github.com/dotnet/roslyn/issues/16864) protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var stack = ComputeEditPaths(oldSequence, oldLength, newSequence, newLength); var x = oldLength; var y = newLength; var varrays = stack.ConsumeArrays().GetEnumerator(); while (x > 0 || y > 0) { var hasNext = varrays.MoveNext(); Debug.Assert(hasNext); var (currentV, d) = varrays.Current; var k = x - y; // "snake" == single delete or insert followed by 0 or more diagonals // snake end point is in V var yEnd = currentV[k]; var xEnd = yEnd + k; // does the snake first go down (insert) or right(delete)? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // snake start point var yStart = currentV[kPrev]; var xStart = yStart + kPrev; // snake mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // return the matching pairs between (xMid, yMid) and (xEnd, yEnd) = diagonal part of the snake while (xEnd > xMid) { Debug.Assert(yEnd > yMid); xEnd--; yEnd--; yield return new KeyValuePair<int, int>(xEnd, yEnd); } x = xStart; y = yStart; } // make sure we finish the enumeration as it returns the allocated buffers to the pool while (varrays.MoveNext()) { } } protected IEnumerable<SequenceEdit> GetEdits(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var stack = ComputeEditPaths(oldSequence, oldLength, newSequence, newLength); var x = oldLength; var y = newLength; var varrays = stack.ConsumeArrays().GetEnumerator(); while (x > 0 || y > 0) { var hasNext = varrays.MoveNext(); Debug.Assert(hasNext); var (currentV, d) = varrays.Current; var k = x - y; // "snake" == single delete or insert followed by 0 or more diagonals // snake end point is in V var yEnd = currentV[k]; var xEnd = yEnd + k; // does the snake first go down (insert) or right(delete)? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // snake start point var yStart = currentV[kPrev]; var xStart = yStart + kPrev; // snake mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // return the matching pairs between (xMid, yMid) and (xEnd, yEnd) = diagonal part of the snake while (xEnd > xMid) { Debug.Assert(yEnd > yMid); xEnd--; yEnd--; yield return new SequenceEdit(xEnd, yEnd); } // return the insert/delete between (xStart, yStart) and (xMid, yMid) = the vertical/horizontal part of the snake if (xMid > 0 || yMid > 0) { if (xStart == xMid) { // insert yield return new SequenceEdit(-1, --yMid); } else { // delete yield return new SequenceEdit(--xMid, -1); } } x = xStart; y = yStart; } } /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more similar the sequences are. /// </summary> /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more similar the sequences are. /// </summary> protected double ComputeDistance(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { Debug.Assert(oldLength >= 0 && newLength >= 0); if (oldLength == 0 || newLength == 0) { return (oldLength == newLength) ? 0.0 : 1.0; } // If the sequences differ significantly in size their distance will be very close to 1.0 // (even if one is a strict subsequence of the other). // Avoid running an expensive LCS algorithm on such sequences. double lenghtRatio = (oldLength > newLength) ? oldLength / newLength : newLength / oldLength; if (lenghtRatio > 100) { return 1.0; } var lcsLength = 0; foreach (var pair in GetMatchingPairs(oldSequence, oldLength, newSequence, newLength)) { lcsLength++; } var max = Math.Max(oldLength, newLength); Debug.Assert(lcsLength <= max); return 1.0 - (double)lcsLength / (double)max; } /// <summary> /// Calculates a list of "V arrays" using Eugene W. Myers O(ND) Difference Algorithm /// </summary> /// <remarks> /// /// The algorithm was inspired by Myers' Diff Algorithm described in an article by Nicolas Butler: /// https://www.codeproject.com/articles/42279/investigating-myers-diff-algorithm-part-of /// The author has approved the use of his code from the article under the Apache 2.0 license. /// /// The algorithm works on an imaginary edit graph for A and B which has a vertex at each point in the grid(i, j), i in [0, lengthA] and j in [0, lengthB]. /// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph. /// Horizontal edges connect each vertex to its right neighbor. /// Vertical edges connect each vertex to the neighbor below it. /// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true. /// /// Move right along horizontal edge (i-1,j)-(i,j) represents a delete of sequenceA[i-1]. /// Move down along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1]. /// Move along diagonal edge (i-1,j-1)-(i,j) represents an match of sequenceA[i-1] to sequenceB[j-1]. /// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common sub. /// /// The function does not actually allocate this graph. Instead it uses Eugene W. Myers' O(ND) Difference Algoritm to calculate a list of "V arrays" and returns it in a Stack. /// A "V array" is a list of end points of so called "snakes". /// A "snake" is a path with a single horizontal (delete) or vertical (insert) move followed by 0 or more diagonals (matching pairs). /// /// Unlike the algorithm in the article this implementation stores 'y' indexes and prefers 'right' moves instead of 'down' moves in ambiguous situations /// to preserve the behavior of the original diff algorithm (deletes first, inserts after). /// /// The number of items in the list is the length of the shortest edit script = the number of inserts/edits between the two sequences = D. /// The list can be used to determine the matching pairs in the sequences (GetMatchingPairs method) or the full editing script (GetEdits method). /// /// The algorithm uses O(ND) time and memory where D is the number of delete/inserts and N is the sum of lengths of the two sequences. /// /// VArrays store just the y index because x can be calculated: x = y + k. /// </remarks> private VStack ComputeEditPaths(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var reachedEnd = false; VArray currentV = default; var stack = CreateStack(); for (var d = 0; d <= oldLength + newLength && !reachedEnd; d++) { if (d == 0) { // the first "snake" to start at (-1, 0) currentV = stack.Push(); currentV.Initialize(); } else { // V is in range [-d...d] => use d to offset the k-based array indices to non-negative values var previousV = currentV; currentV = stack.Push(); currentV.InitializeFrom(previousV); } for (var k = -d; k <= d; k += 2) { // down or right? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // start point var yStart = currentV[kPrev]; // mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // end point var xEnd = xMid; var yEnd = yMid; // follow diagonal while (xEnd < oldLength && yEnd < newLength && ItemsEqual(oldSequence, xEnd, newSequence, yEnd)) { xEnd++; yEnd++; } // save end point currentV[k] = yEnd; Debug.Assert(xEnd == yEnd + k); // check for solution if (xEnd >= oldLength && yEnd >= newLength) { reachedEnd = true; } } } return stack; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { internal abstract class LongestCommonSubsequence { // Define the pool in a non-generic base class to allow sharing among instantiations. private static readonly ObjectPool<VBuffer> s_pool = new(() => new VBuffer()); /// <summary> /// Underlying storage for <see cref="VArray"/>s allocated on <see cref="VStack"/>. /// </summary> /// <remarks> /// The LCS algorithm allocates <see cref="VArray"/>s of sizes (3, 2*1 + 1, ..., 2*D + 1), always in this order, /// where D is at most the sum of lengths of the compared sequences. /// The arrays get pushed on a stack as they are built up, then all consumed in the reverse order (stack pop). /// /// Since the exact length of each array in the above sequence is known we avoid allocating each individual array. /// Instead we allocate a large buffer serving as a a backing storage of a contiguous sequence of arrays /// corresponding to stack depths <see cref="MinDepth"/> to <see cref="MaxDepth"/>. /// If more storage is needed we chain next large buffer to the previous one in a linked list. /// /// We pool a few of these linked buffers on <see cref="VStack"/> to conserve allocations. /// </remarks> protected sealed class VBuffer { /// <summary> /// The max stack depth backed by the fist buffer. /// Size of the buffer for 100 is ~10K. /// For 150 it'd be 91KB, which would be allocated on LOH. /// The buffers grow by factor of <see cref="GrowFactor"/>, so the next buffer will be allocated on LOH. /// </summary> private const int FirstBufferMaxDepth = 100; // 3 + Sum { d = 1..maxDepth : 2*d+1 } = (maxDepth + 1)^2 + 2 private const int FirstBufferLength = (FirstBufferMaxDepth + 1) * (FirstBufferMaxDepth + 1) + 2; internal const int GrowFactor = 2; /// <summary> /// Do not pool segments that are too large. /// </summary> internal const int MaxPooledBufferSize = 1024 * 1024; public VBuffer Previous { get; private set; } public VBuffer Next { get; private set; } public readonly int MinDepth; public readonly int MaxDepth; private readonly int[] _array; public VBuffer() { _array = new int[FirstBufferLength]; MaxDepth = FirstBufferMaxDepth; } public VBuffer(VBuffer previous) { Debug.Assert(previous != null); var minDepth = previous.MaxDepth + 1; var maxDepth = previous.MaxDepth * GrowFactor; Debug.Assert(minDepth > 0); Debug.Assert(minDepth <= maxDepth); Previous = previous; _array = new int[GetNextBufferLength(minDepth - 1, maxDepth)]; MinDepth = minDepth; MaxDepth = maxDepth; previous.Next = this; } public VArray GetVArray(int depth) { var length = GetVArrayLength(depth); var start = GetVArrayStart(depth) - GetVArrayStart(MinDepth); Debug.Assert(start >= 0); Debug.Assert(start + length <= _array.Length); return new VArray(_array, start, length); } public bool IsTooLargeToPool => _array.Length > MaxPooledBufferSize; private static int GetVArrayLength(int depth) => 2 * Math.Max(depth, 1) + 1; // 3 + Sum { d = 1..depth-1 : 2*d+1 } = depth^2 + 2 private static int GetVArrayStart(int depth) => (depth == 0) ? 0 : depth * depth + 2; // Sum { d = previousChunkDepth..maxDepth : 2*d+1 } = (maxDepth + 1)^2 - precedingBufferMaxDepth^2 private static int GetNextBufferLength(int precedingBufferMaxDepth, int maxDepth) => (maxDepth + 1) * (maxDepth + 1) - precedingBufferMaxDepth * precedingBufferMaxDepth; public void Unlink() { Previous.Next = null; Previous = null; } } protected struct VStack { private readonly ObjectPool<VBuffer> _bufferPool; private readonly VBuffer _firstBuffer; private VBuffer _currentBuffer; private int _depth; public VStack(ObjectPool<VBuffer> bufferPool) { _bufferPool = bufferPool; _currentBuffer = _firstBuffer = bufferPool.Allocate(); _depth = 0; } public VArray Push() { var depth = _depth++; if (depth > _currentBuffer.MaxDepth) { // If the buffer is not big enough add another segment to the linked list (the constructor takes care of the linking). // Note that the segments are not pooled on their own. The whole linked list of buffers is pooled. _currentBuffer = _currentBuffer.Next ?? new VBuffer(_currentBuffer); } return _currentBuffer.GetVArray(depth); } public IEnumerable<(VArray Array, int Depth)> ConsumeArrays() { var buffer = _currentBuffer; for (var depth = _depth - 1; depth >= 0; depth--) { if (depth < buffer.MinDepth) { var previousBuffer = buffer.Previous; // Trim large buffers from the linked list before we return the whole list back into the pool. if (buffer.IsTooLargeToPool) { buffer.Unlink(); } buffer = previousBuffer; } yield return (buffer.GetVArray(depth), depth); } _bufferPool.Free(_firstBuffer); _currentBuffer = null; } } // VArray struct enables array indexing in range [-d...d]. protected readonly struct VArray { private readonly int[] _buffer; private readonly int _start; private readonly int _length; public VArray(int[] buffer, int start, int length) { _buffer = buffer; _start = start; _length = length; } public void InitializeFrom(VArray other) { int dstCopyStart, srcCopyStart, copyLength; var copyDelta = Offset - other.Offset; if (copyDelta >= 0) { srcCopyStart = 0; dstCopyStart = copyDelta; copyLength = other._length; } else { srcCopyStart = -copyDelta; dstCopyStart = 0; copyLength = _length; } // since we might be reusing previously used arrays, we need to clear slots that are not copied over from the other array: Array.Clear(_buffer, _start, dstCopyStart); Array.Copy(other._buffer, other._start + srcCopyStart, _buffer, _start + dstCopyStart, copyLength); Array.Clear(_buffer, _start + dstCopyStart + copyLength, _length - dstCopyStart - copyLength); } internal void Initialize() => Array.Clear(_buffer, _start, _length); public int this[int index] { get => _buffer[_start + index + Offset]; set => _buffer[_start + index + Offset] = value; } private int Offset => _length / 2; } protected static VStack CreateStack() => new(s_pool); } /// <summary> /// Calculates Longest Common Subsequence. /// </summary> internal abstract class LongestCommonSubsequence<TSequence> : LongestCommonSubsequence { protected abstract bool ItemsEqual(TSequence oldSequence, int oldIndex, TSequence newSequence, int newIndex); // TODO: Consolidate return types between GetMatchingPairs and GetEdit to avoid duplicated code (https://github.com/dotnet/roslyn/issues/16864) protected IEnumerable<KeyValuePair<int, int>> GetMatchingPairs(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var stack = ComputeEditPaths(oldSequence, oldLength, newSequence, newLength); var x = oldLength; var y = newLength; var varrays = stack.ConsumeArrays().GetEnumerator(); while (x > 0 || y > 0) { var hasNext = varrays.MoveNext(); Debug.Assert(hasNext); var (currentV, d) = varrays.Current; var k = x - y; // "snake" == single delete or insert followed by 0 or more diagonals // snake end point is in V var yEnd = currentV[k]; var xEnd = yEnd + k; // does the snake first go down (insert) or right(delete)? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // snake start point var yStart = currentV[kPrev]; var xStart = yStart + kPrev; // snake mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // return the matching pairs between (xMid, yMid) and (xEnd, yEnd) = diagonal part of the snake while (xEnd > xMid) { Debug.Assert(yEnd > yMid); xEnd--; yEnd--; yield return new KeyValuePair<int, int>(xEnd, yEnd); } x = xStart; y = yStart; } // make sure we finish the enumeration as it returns the allocated buffers to the pool while (varrays.MoveNext()) { } } protected IEnumerable<SequenceEdit> GetEdits(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var stack = ComputeEditPaths(oldSequence, oldLength, newSequence, newLength); var x = oldLength; var y = newLength; var varrays = stack.ConsumeArrays().GetEnumerator(); while (x > 0 || y > 0) { var hasNext = varrays.MoveNext(); Debug.Assert(hasNext); var (currentV, d) = varrays.Current; var k = x - y; // "snake" == single delete or insert followed by 0 or more diagonals // snake end point is in V var yEnd = currentV[k]; var xEnd = yEnd + k; // does the snake first go down (insert) or right(delete)? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // snake start point var yStart = currentV[kPrev]; var xStart = yStart + kPrev; // snake mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // return the matching pairs between (xMid, yMid) and (xEnd, yEnd) = diagonal part of the snake while (xEnd > xMid) { Debug.Assert(yEnd > yMid); xEnd--; yEnd--; yield return new SequenceEdit(xEnd, yEnd); } // return the insert/delete between (xStart, yStart) and (xMid, yMid) = the vertical/horizontal part of the snake if (xMid > 0 || yMid > 0) { if (xStart == xMid) { // insert yield return new SequenceEdit(-1, --yMid); } else { // delete yield return new SequenceEdit(--xMid, -1); } } x = xStart; y = yStart; } } /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more similar the sequences are. /// </summary> /// <summary> /// Returns a distance [0..1] of the specified sequences. /// The smaller distance the more similar the sequences are. /// </summary> protected double ComputeDistance(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { Debug.Assert(oldLength >= 0 && newLength >= 0); if (oldLength == 0 || newLength == 0) { return (oldLength == newLength) ? 0.0 : 1.0; } // If the sequences differ significantly in size their distance will be very close to 1.0 // (even if one is a strict subsequence of the other). // Avoid running an expensive LCS algorithm on such sequences. double lenghtRatio = (oldLength > newLength) ? oldLength / newLength : newLength / oldLength; if (lenghtRatio > 100) { return 1.0; } var lcsLength = 0; foreach (var pair in GetMatchingPairs(oldSequence, oldLength, newSequence, newLength)) { lcsLength++; } var max = Math.Max(oldLength, newLength); Debug.Assert(lcsLength <= max); return 1.0 - (double)lcsLength / (double)max; } /// <summary> /// Calculates a list of "V arrays" using Eugene W. Myers O(ND) Difference Algorithm /// </summary> /// <remarks> /// /// The algorithm was inspired by Myers' Diff Algorithm described in an article by Nicolas Butler: /// https://www.codeproject.com/articles/42279/investigating-myers-diff-algorithm-part-of /// The author has approved the use of his code from the article under the Apache 2.0 license. /// /// The algorithm works on an imaginary edit graph for A and B which has a vertex at each point in the grid(i, j), i in [0, lengthA] and j in [0, lengthB]. /// The vertices of the edit graph are connected by horizontal, vertical, and diagonal directed edges to form a directed acyclic graph. /// Horizontal edges connect each vertex to its right neighbor. /// Vertical edges connect each vertex to the neighbor below it. /// Diagonal edges connect vertex (i,j) to vertex (i-1,j-1) if <see cref="ItemsEqual"/>(sequenceA[i-1],sequenceB[j-1]) is true. /// /// Move right along horizontal edge (i-1,j)-(i,j) represents a delete of sequenceA[i-1]. /// Move down along vertical edge (i,j-1)-(i,j) represents an insert of sequenceB[j-1]. /// Move along diagonal edge (i-1,j-1)-(i,j) represents an match of sequenceA[i-1] to sequenceB[j-1]. /// The number of diagonal edges on the path from (0,0) to (lengthA, lengthB) is the length of the longest common sub. /// /// The function does not actually allocate this graph. Instead it uses Eugene W. Myers' O(ND) Difference Algoritm to calculate a list of "V arrays" and returns it in a Stack. /// A "V array" is a list of end points of so called "snakes". /// A "snake" is a path with a single horizontal (delete) or vertical (insert) move followed by 0 or more diagonals (matching pairs). /// /// Unlike the algorithm in the article this implementation stores 'y' indexes and prefers 'right' moves instead of 'down' moves in ambiguous situations /// to preserve the behavior of the original diff algorithm (deletes first, inserts after). /// /// The number of items in the list is the length of the shortest edit script = the number of inserts/edits between the two sequences = D. /// The list can be used to determine the matching pairs in the sequences (GetMatchingPairs method) or the full editing script (GetEdits method). /// /// The algorithm uses O(ND) time and memory where D is the number of delete/inserts and N is the sum of lengths of the two sequences. /// /// VArrays store just the y index because x can be calculated: x = y + k. /// </remarks> private VStack ComputeEditPaths(TSequence oldSequence, int oldLength, TSequence newSequence, int newLength) { var reachedEnd = false; VArray currentV = default; var stack = CreateStack(); for (var d = 0; d <= oldLength + newLength && !reachedEnd; d++) { if (d == 0) { // the first "snake" to start at (-1, 0) currentV = stack.Push(); currentV.Initialize(); } else { // V is in range [-d...d] => use d to offset the k-based array indices to non-negative values var previousV = currentV; currentV = stack.Push(); currentV.InitializeFrom(previousV); } for (var k = -d; k <= d; k += 2) { // down or right? var right = k == d || (k != -d && currentV[k - 1] > currentV[k + 1]); var kPrev = right ? k - 1 : k + 1; // start point var yStart = currentV[kPrev]; // mid point var yMid = right ? yStart : yStart + 1; var xMid = yMid + k; // end point var xEnd = xMid; var yEnd = yMid; // follow diagonal while (xEnd < oldLength && yEnd < newLength && ItemsEqual(oldSequence, xEnd, newSequence, yEnd)) { xEnd++; yEnd++; } // save end point currentV[k] = yEnd; Debug.Assert(xEnd == yEnd + k); // check for solution if (xEnd >= oldLength && yEnd >= newLength) { reachedEnd = true; } } } return stack; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/VisualBasic/Portable/CodeFixes/MoveToTopOfFile/MoveToTopOfFileCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.MoveToTopOfFile <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.MoveToTopOfFile), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.ImplementInterface)> Partial Friend Class MoveToTopOfFileCodeFixProvider Inherits CodeFixProvider Friend Const BC30465 As String = "BC30465" ' 'Imports' statements must precede any declarations. Friend Const BC30637 As String = "BC30637" ' Assembly or Module attribute statements must precede any declarations in a file. Friend Const BC30627 As String = "BC30627" ' 'Option' statements must precede any declarations or 'Imports' statements. <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC30465, BC30637, BC30627) End Get End Property Public Overrides Function GetFixAllProvider() As FixAllProvider ' Fix All is not supported for this code fix ' https://github.com/dotnet/roslyn/issues/34471 Return Nothing End Function Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task Dim document = context.Document Dim span = context.Span Dim cancellationToken = context.CancellationToken Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(span.Start) If Not token.Span.IntersectsWith(span) Then Return End If Dim node = token _ .GetAncestors(Of DeclarationStatementSyntax) _ .FirstOrDefault(Function(c) c.Span.IntersectsWith(span)) If node Is Nothing Then Return End If Dim compilationUnit = CType(root, CompilationUnitSyntax) Dim result = SpecializedCollections.EmptyEnumerable(Of CodeAction)() If node.Kind = SyntaxKind.ImportsStatement Then Dim importsStatement = DirectCast(node, ImportsStatementSyntax) If Not compilationUnit.Imports.Contains(importsStatement) Then If DeclarationsExistAfterImports(node, compilationUnit) OrElse compilationUnit.Attributes.Any(Function(a) a.SpanStart < node.SpanStart) Then result = CreateActionForImports(document, importsStatement, compilationUnit, cancellationToken) End If End If End If If node.Kind = SyntaxKind.OptionStatement Then Dim optionStatement = DirectCast(node, OptionStatementSyntax) If Not compilationUnit.Options.Contains(optionStatement) Then result = CreateActionForOptions(document, optionStatement, compilationUnit, cancellationToken) End If End If If node.Kind = SyntaxKind.AttributesStatement Then Dim attributesStatement = DirectCast(node, AttributesStatementSyntax) If Not compilationUnit.Attributes.Contains(attributesStatement) Then result = CreateActionForAttribute(document, attributesStatement, compilationUnit, cancellationToken) End If End If If result IsNot Nothing Then context.RegisterFixes(result, context.Diagnostics) End If End Function Private Shared Function DeclarationsExistAfterImports(node As SyntaxNode, root As CompilationUnitSyntax) As Boolean Return root.Members.Any( Function(m) m IsNot node AndAlso Not m.IsKind(SyntaxKind.OptionStatement, SyntaxKind.AttributesStatement) AndAlso node.Span.End > m.SpanStart) End Function Private Shared Function CreateActionForImports(document As Document, node As ImportsStatementSyntax, root As CompilationUnitSyntax, cancellationToken As CancellationToken) As IEnumerable(Of CodeAction) Dim destinationLine As Integer = 0 If root.Imports.Any() Then destinationLine = FindLastContiguousStatement(root.Imports, root.GetLeadingBannerAndPreprocessorDirectives()) ElseIf root.Options.Any() Then destinationLine = root.Options.Last().GetLocation().GetLineSpan().EndLinePosition.Line + 1 End If If DestinationPositionIsHidden(root, destinationLine, cancellationToken) Then Return Nothing End If Return { New MoveToLineCodeAction(document, node.ImportsKeyword, destinationLine, MoveStatement("Imports", destinationLine)), New RemoveStatementCodeAction(document, node, DeleteStatement("Imports")) } End Function Private Shared Function CreateActionForOptions(document As Document, node As OptionStatementSyntax, root As CompilationUnitSyntax, cancellationToken As CancellationToken) As IEnumerable(Of CodeAction) Dim destinationLine = FindLastContiguousStatement(root.Options, root.GetLeadingBannerAndPreprocessorDirectives()) If DestinationPositionIsHidden(root, destinationLine, cancellationToken) Then Return Nothing End If Return { New MoveToLineCodeAction(document, node.OptionKeyword, destinationLine, MoveStatement("Option", destinationLine)), New RemoveStatementCodeAction(document, node, DeleteStatement("Option")) } End Function Private Shared Function CreateActionForAttribute(document As Document, node As AttributesStatementSyntax, root As CompilationUnitSyntax, cancellationToken As CancellationToken) As IEnumerable(Of CodeAction) Dim destinationLine As Integer = 0 If root.Attributes.Any() Then destinationLine = FindLastContiguousStatement(root.Attributes, root.GetLeadingBannerAndPreprocessorDirectives()) ElseIf root.Imports.Any() Then destinationLine = root.Imports.Last().GetLocation().GetLineSpan().EndLinePosition.Line + 1 ElseIf root.Options.Any() Then destinationLine = root.Options.Last().GetLocation().GetLineSpan().EndLinePosition.Line + 1 End If If DestinationPositionIsHidden(root, destinationLine, cancellationToken) Then Return Nothing End If Return { New MoveToLineCodeAction(document, node.GetFirstToken(), destinationLine, MoveStatement("Attribute", destinationLine)), New RemoveStatementCodeAction(document, node, DeleteStatement("Attribute")) } End Function Private Shared Function FindLastContiguousStatement(nodes As IEnumerable(Of SyntaxNode), trivia As IEnumerable(Of SyntaxTrivia)) As Integer If Not nodes.Any() Then Dim lastBannerText = trivia.LastOrDefault(Function(t) t.IsKind(SyntaxKind.CommentTrivia)) If lastBannerText = Nothing Then Return 0 Else Return lastBannerText.GetLocation().GetLineSpan().StartLinePosition.Line + 1 End If End If ' Advance through the list of nodes until we find one that doesn't start on the ' line immediately following the one before it. Dim expectedLine = nodes.First().GetLocation().GetLineSpan().StartLinePosition.Line For Each node In nodes Dim actualLine = node.GetLocation().GetLineSpan().StartLinePosition.Line If actualLine <> expectedLine Then Exit For End If expectedLine += 1 Next Return expectedLine End Function Private Shared Function MoveStatement(kind As String, line As Integer) As String Return String.Format(VBFeaturesResources.Move_the_0_statement_to_line_1, kind, line + 1) End Function Private Shared Function DeleteStatement(kind As String) As String Return String.Format(VBFeaturesResources.Delete_the_0_statement2, kind) End Function Private Shared Function DestinationPositionIsHidden(root As CompilationUnitSyntax, destinationLine As Integer, cancellationToken As CancellationToken) As Boolean Dim text = root.GetText() Dim position = text.Lines(destinationLine).Start Return root.SyntaxTree.IsHiddenPosition(destinationLine, cancellationToken) 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.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.MoveToTopOfFile <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.MoveToTopOfFile), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.ImplementInterface)> Partial Friend Class MoveToTopOfFileCodeFixProvider Inherits CodeFixProvider Friend Const BC30465 As String = "BC30465" ' 'Imports' statements must precede any declarations. Friend Const BC30637 As String = "BC30637" ' Assembly or Module attribute statements must precede any declarations in a file. Friend Const BC30627 As String = "BC30627" ' 'Option' statements must precede any declarations or 'Imports' statements. <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC30465, BC30637, BC30627) End Get End Property Public Overrides Function GetFixAllProvider() As FixAllProvider ' Fix All is not supported for this code fix ' https://github.com/dotnet/roslyn/issues/34471 Return Nothing End Function Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task Dim document = context.Document Dim span = context.Span Dim cancellationToken = context.CancellationToken Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(span.Start) If Not token.Span.IntersectsWith(span) Then Return End If Dim node = token _ .GetAncestors(Of DeclarationStatementSyntax) _ .FirstOrDefault(Function(c) c.Span.IntersectsWith(span)) If node Is Nothing Then Return End If Dim compilationUnit = CType(root, CompilationUnitSyntax) Dim result = SpecializedCollections.EmptyEnumerable(Of CodeAction)() If node.Kind = SyntaxKind.ImportsStatement Then Dim importsStatement = DirectCast(node, ImportsStatementSyntax) If Not compilationUnit.Imports.Contains(importsStatement) Then If DeclarationsExistAfterImports(node, compilationUnit) OrElse compilationUnit.Attributes.Any(Function(a) a.SpanStart < node.SpanStart) Then result = CreateActionForImports(document, importsStatement, compilationUnit, cancellationToken) End If End If End If If node.Kind = SyntaxKind.OptionStatement Then Dim optionStatement = DirectCast(node, OptionStatementSyntax) If Not compilationUnit.Options.Contains(optionStatement) Then result = CreateActionForOptions(document, optionStatement, compilationUnit, cancellationToken) End If End If If node.Kind = SyntaxKind.AttributesStatement Then Dim attributesStatement = DirectCast(node, AttributesStatementSyntax) If Not compilationUnit.Attributes.Contains(attributesStatement) Then result = CreateActionForAttribute(document, attributesStatement, compilationUnit, cancellationToken) End If End If If result IsNot Nothing Then context.RegisterFixes(result, context.Diagnostics) End If End Function Private Shared Function DeclarationsExistAfterImports(node As SyntaxNode, root As CompilationUnitSyntax) As Boolean Return root.Members.Any( Function(m) m IsNot node AndAlso Not m.IsKind(SyntaxKind.OptionStatement, SyntaxKind.AttributesStatement) AndAlso node.Span.End > m.SpanStart) End Function Private Shared Function CreateActionForImports(document As Document, node As ImportsStatementSyntax, root As CompilationUnitSyntax, cancellationToken As CancellationToken) As IEnumerable(Of CodeAction) Dim destinationLine As Integer = 0 If root.Imports.Any() Then destinationLine = FindLastContiguousStatement(root.Imports, root.GetLeadingBannerAndPreprocessorDirectives()) ElseIf root.Options.Any() Then destinationLine = root.Options.Last().GetLocation().GetLineSpan().EndLinePosition.Line + 1 End If If DestinationPositionIsHidden(root, destinationLine, cancellationToken) Then Return Nothing End If Return { New MoveToLineCodeAction(document, node.ImportsKeyword, destinationLine, MoveStatement("Imports", destinationLine)), New RemoveStatementCodeAction(document, node, DeleteStatement("Imports")) } End Function Private Shared Function CreateActionForOptions(document As Document, node As OptionStatementSyntax, root As CompilationUnitSyntax, cancellationToken As CancellationToken) As IEnumerable(Of CodeAction) Dim destinationLine = FindLastContiguousStatement(root.Options, root.GetLeadingBannerAndPreprocessorDirectives()) If DestinationPositionIsHidden(root, destinationLine, cancellationToken) Then Return Nothing End If Return { New MoveToLineCodeAction(document, node.OptionKeyword, destinationLine, MoveStatement("Option", destinationLine)), New RemoveStatementCodeAction(document, node, DeleteStatement("Option")) } End Function Private Shared Function CreateActionForAttribute(document As Document, node As AttributesStatementSyntax, root As CompilationUnitSyntax, cancellationToken As CancellationToken) As IEnumerable(Of CodeAction) Dim destinationLine As Integer = 0 If root.Attributes.Any() Then destinationLine = FindLastContiguousStatement(root.Attributes, root.GetLeadingBannerAndPreprocessorDirectives()) ElseIf root.Imports.Any() Then destinationLine = root.Imports.Last().GetLocation().GetLineSpan().EndLinePosition.Line + 1 ElseIf root.Options.Any() Then destinationLine = root.Options.Last().GetLocation().GetLineSpan().EndLinePosition.Line + 1 End If If DestinationPositionIsHidden(root, destinationLine, cancellationToken) Then Return Nothing End If Return { New MoveToLineCodeAction(document, node.GetFirstToken(), destinationLine, MoveStatement("Attribute", destinationLine)), New RemoveStatementCodeAction(document, node, DeleteStatement("Attribute")) } End Function Private Shared Function FindLastContiguousStatement(nodes As IEnumerable(Of SyntaxNode), trivia As IEnumerable(Of SyntaxTrivia)) As Integer If Not nodes.Any() Then Dim lastBannerText = trivia.LastOrDefault(Function(t) t.IsKind(SyntaxKind.CommentTrivia)) If lastBannerText = Nothing Then Return 0 Else Return lastBannerText.GetLocation().GetLineSpan().StartLinePosition.Line + 1 End If End If ' Advance through the list of nodes until we find one that doesn't start on the ' line immediately following the one before it. Dim expectedLine = nodes.First().GetLocation().GetLineSpan().StartLinePosition.Line For Each node In nodes Dim actualLine = node.GetLocation().GetLineSpan().StartLinePosition.Line If actualLine <> expectedLine Then Exit For End If expectedLine += 1 Next Return expectedLine End Function Private Shared Function MoveStatement(kind As String, line As Integer) As String Return String.Format(VBFeaturesResources.Move_the_0_statement_to_line_1, kind, line + 1) End Function Private Shared Function DeleteStatement(kind As String) As String Return String.Format(VBFeaturesResources.Delete_the_0_statement2, kind) End Function Private Shared Function DestinationPositionIsHidden(root As CompilationUnitSyntax, destinationLine As Integer, cancellationToken As CancellationToken) As Boolean Dim text = root.GetText() Dim position = text.Lines(destinationLine).Start Return root.SyntaxTree.IsHiddenPosition(destinationLine, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Workspaces/Core/Portable/Shared/Extensions/ISolutionExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISolutionExtensions { public static async Task<ImmutableArray<INamespaceSymbol>> GetGlobalNamespacesAsync( this Solution solution, CancellationToken cancellationToken) { var results = ArrayBuilder<INamespaceSymbol>.GetInstance(); foreach (var projectId in solution.ProjectIds) { var project = solution.GetProject(projectId)!; if (project.SupportsCompilation) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); #nullable disable // Can 'compilation' be null here? results.Add(compilation.Assembly.GlobalNamespace); #nullable enable } } return results.ToImmutableAndFree(); } public static TextDocumentKind? GetDocumentKind(this Solution solution, DocumentId documentId) => solution.GetTextDocument(documentId)?.Kind; public static Solution WithTextDocumentText(this Solution solution, DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveIdentity) { var documentKind = solution.GetDocumentKind(documentId); switch (documentKind) { case TextDocumentKind.Document: return solution.WithDocumentText(documentId, text, mode); case TextDocumentKind.AnalyzerConfigDocument: return solution.WithAnalyzerConfigDocumentText(documentId, text, mode); case TextDocumentKind.AdditionalDocument: return solution.WithAdditionalDocumentText(documentId, text, mode); case null: throw new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); default: throw ExceptionUtilities.UnexpectedValue(documentKind); } } public static ImmutableArray<DocumentId> FilterDocumentIdsByLanguage(this Solution solution, ImmutableArray<DocumentId> documentIds, string language) => documentIds.WhereAsArray( (documentId, args) => args.solution.GetDocument(documentId)?.Project.Language == args.language, (solution, language)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISolutionExtensions { public static async Task<ImmutableArray<INamespaceSymbol>> GetGlobalNamespacesAsync( this Solution solution, CancellationToken cancellationToken) { var results = ArrayBuilder<INamespaceSymbol>.GetInstance(); foreach (var projectId in solution.ProjectIds) { var project = solution.GetProject(projectId)!; if (project.SupportsCompilation) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); #nullable disable // Can 'compilation' be null here? results.Add(compilation.Assembly.GlobalNamespace); #nullable enable } } return results.ToImmutableAndFree(); } public static TextDocumentKind? GetDocumentKind(this Solution solution, DocumentId documentId) => solution.GetTextDocument(documentId)?.Kind; public static Solution WithTextDocumentText(this Solution solution, DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveIdentity) { var documentKind = solution.GetDocumentKind(documentId); switch (documentKind) { case TextDocumentKind.Document: return solution.WithDocumentText(documentId, text, mode); case TextDocumentKind.AnalyzerConfigDocument: return solution.WithAnalyzerConfigDocumentText(documentId, text, mode); case TextDocumentKind.AdditionalDocument: return solution.WithAdditionalDocumentText(documentId, text, mode); case null: throw new InvalidOperationException(WorkspaceExtensionsResources.The_solution_does_not_contain_the_specified_document); default: throw ExceptionUtilities.UnexpectedValue(documentKind); } } public static ImmutableArray<DocumentId> FilterDocumentIdsByLanguage(this Solution solution, ImmutableArray<DocumentId> documentIds, string language) => documentIds.WhereAsArray( (documentId, args) => args.solution.GetDocument(documentId)?.Project.Language == args.language, (solution, language)); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeActionOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.AddPackage { /// <summary> /// Operation responsible purely for installing a nuget package with a specific /// version, or a the latest version of a nuget package. Is not responsible /// for adding an import to user code. /// </summary> internal class InstallPackageDirectlyCodeActionOperation : CodeActionOperation { private readonly Document _document; private readonly IPackageInstallerService _installerService; private readonly string _source; private readonly string _packageName; private readonly string _versionOpt; private readonly bool _includePrerelease; private readonly bool _isLocal; private readonly List<string> _projectsWithMatchingVersion; public InstallPackageDirectlyCodeActionOperation( IPackageInstallerService installerService, Document document, string source, string packageName, string versionOpt, bool includePrerelease, bool isLocal) { _installerService = installerService; _document = document; _source = source; _packageName = packageName; _versionOpt = versionOpt; _includePrerelease = includePrerelease; _isLocal = isLocal; if (versionOpt != null) { const int projectsToShow = 5; var otherProjects = installerService.GetProjectsWithInstalledPackage( _document.Project.Solution, packageName, versionOpt).ToList(); _projectsWithMatchingVersion = otherProjects.Take(projectsToShow).Select(p => p.Name).ToList(); if (otherProjects.Count > projectsToShow) { _projectsWithMatchingVersion.Add("..."); } } } public override string Title => _versionOpt == null ? string.Format(FeaturesResources.Find_and_install_latest_version_of_0, _packageName) : _isLocal ? string.Format(FeaturesResources.Use_locally_installed_0_version_1_This_version_used_in_colon_2, _packageName, _versionOpt, string.Join(", ", _projectsWithMatchingVersion)) : string.Format(FeaturesResources.Install_0_1, _packageName, _versionOpt); internal override bool ApplyDuringTests => true; internal override bool TryApply( Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) { return _installerService.TryInstallPackage( workspace, _document.Id, _source, _packageName, _versionOpt, _includePrerelease, 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.AddPackage { /// <summary> /// Operation responsible purely for installing a nuget package with a specific /// version, or a the latest version of a nuget package. Is not responsible /// for adding an import to user code. /// </summary> internal class InstallPackageDirectlyCodeActionOperation : CodeActionOperation { private readonly Document _document; private readonly IPackageInstallerService _installerService; private readonly string _source; private readonly string _packageName; private readonly string _versionOpt; private readonly bool _includePrerelease; private readonly bool _isLocal; private readonly List<string> _projectsWithMatchingVersion; public InstallPackageDirectlyCodeActionOperation( IPackageInstallerService installerService, Document document, string source, string packageName, string versionOpt, bool includePrerelease, bool isLocal) { _installerService = installerService; _document = document; _source = source; _packageName = packageName; _versionOpt = versionOpt; _includePrerelease = includePrerelease; _isLocal = isLocal; if (versionOpt != null) { const int projectsToShow = 5; var otherProjects = installerService.GetProjectsWithInstalledPackage( _document.Project.Solution, packageName, versionOpt).ToList(); _projectsWithMatchingVersion = otherProjects.Take(projectsToShow).Select(p => p.Name).ToList(); if (otherProjects.Count > projectsToShow) { _projectsWithMatchingVersion.Add("..."); } } } public override string Title => _versionOpt == null ? string.Format(FeaturesResources.Find_and_install_latest_version_of_0, _packageName) : _isLocal ? string.Format(FeaturesResources.Use_locally_installed_0_version_1_This_version_used_in_colon_2, _packageName, _versionOpt, string.Join(", ", _projectsWithMatchingVersion)) : string.Format(FeaturesResources.Install_0_1, _packageName, _versionOpt); internal override bool ApplyDuringTests => true; internal override bool TryApply( Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) { return _installerService.TryInstallPackage( workspace, _document.Id, _source, _packageName, _versionOpt, _includePrerelease, cancellationToken); } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/VisualBasic/Test/Semantic/Semantics/QueryExpressions_SemanticModel.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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GetExtendedSemanticInfoTests <Fact()> Public Sub Query1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q 'BIND6:"s" Where s > 0 'BIND3:"s" Where 10 > s 'BIND2:"s" Where DirectCast(Function() System.Console.WriteLine(s) 'BIND1:"s" Return True End Function, Func(Of Boolean)).Invoke() Dim q2 As Object = From s In 'BIND7:"s" (From s In q 'BIND8:"s" Where s > 0) 'BIND5:"s" Where 10 > s 'BIND4:"s" End Sub End Module ]]></file> </compilation>) 'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary '---------------------------- Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node1, node2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Assert.NotEqual(node1, node3) Assert.NotEqual(node2, node3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim s6 = semanticModel1.GetDeclaredSymbol(node6) Assert.Same(s1, s6) Assert.Same(s6, semanticModel1.GetDeclaredSymbol(DirectCast(node6, VisualBasicSyntaxNode))) Assert.Same(s6, semanticModel1.GetDeclaredSymbol(DirectCast(node6.Parent, CollectionRangeVariableSyntax))) Assert.Same(s6, semanticModel1.GetDeclaredSymbol(node6.Parent)) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.NotSame(s1, s7) Assert.Equal("s", s7.Name) Assert.Equal("System.Int32", s7.Type.ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = semanticInfo.Symbol Assert.Same(s7, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s4) Assert.NotSame(s3, s4) Assert.Equal("s", s4.Name) Assert.Equal("System.Int32", s4.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8)) '---------------------------- Dim semanticModel2 = compilation.GetSemanticModel(tree) Assert.NotSame(semanticModel1, semanticModel2) Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s2) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node_3, node_2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.NotEqual(node_3, node_1) Assert.NotEqual(node_2, node_1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub Query2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim lambda As Action = Sub() Dim q1 As Object = From s In q 'BIND6:"s" Where s > 0 'BIND3:"s" Where 10 > s 'BIND2:"s" Where DirectCast(Function() System.Console.WriteLine(s) 'BIND1:"s" Return True End Function, Func(Of Boolean)).Invoke() Dim q2 As Object = From s In 'BIND7:"s" (From s In q 'BIND8:"s" Where s > 0) 'BIND5:"s" Where 10 > s 'BIND4:"s" End Sub End Sub End Module ]]></file> </compilation>) 'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary '---------------------------- Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node1, node2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Assert.NotEqual(node1, node3) Assert.NotEqual(node2, node3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim s6 = semanticModel1.GetDeclaredSymbol(node6) Assert.Same(s1, s6) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.NotSame(s1, s7) Assert.Equal("s", s7.Name) Assert.Equal("System.Int32", s7.Type.ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = semanticInfo.Symbol Assert.Same(s7, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s4) Assert.NotSame(s3, s4) Assert.Equal("s", s4.Name) Assert.Equal("System.Int32", s4.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8)) '---------------------------- Dim semanticModel2 = compilation.GetSemanticModel(tree) Assert.NotSame(semanticModel1, semanticModel2) Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s2) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node_3, node_2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.NotEqual(node_3, node_1) Assert.NotEqual(node_2, node_1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub Query3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Dim q As New QueryAble() Dim q1 As Object = From s In q 'BIND6:"s" Where s > 0 'BIND3:"s" Where 10 > s 'BIND2:"s" Where DirectCast(Function() System.Console.WriteLine(s) 'BIND1:"s" Return True End Function, Func(Of Boolean)).Invoke() Dim q2 As Object = From s In 'BIND7:"s" (From s In q 'BIND8:"s" Where s > 0) 'BIND5:"s" Where 10 > s 'BIND4:"s" Sub Main(args As String()) End Sub End Module ]]></file> </compilation>) 'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary '---------------------------- Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node1, node2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Assert.NotEqual(node1, node3) Assert.NotEqual(node2, node3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim s6 = semanticModel1.GetDeclaredSymbol(node6) Assert.Same(s1, s6) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.NotSame(s1, s7) Assert.Equal("s", s7.Name) Assert.Equal("System.Int32", s7.Type.ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = semanticInfo.Symbol Assert.Same(s7, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s4) Assert.NotSame(s3, s4) Assert.Equal("s", s4.Name) Assert.Equal("System.Int32", s4.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8)) '---------------------------- Dim semanticModel2 = compilation.GetSemanticModel(tree) Assert.NotSame(semanticModel1, semanticModel2) Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s2) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node_3, node_2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.NotEqual(node_3, node_1) Assert.NotEqual(node_2, node_1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub Query4() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function Public Function Take(x As Integer) As QueryAble Return Me End Function Public Function Skip(x As Integer) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim lambda1 As Func(Of Object) = Function() From s In q 'BIND6:"s" Where s > 0 'BIND3:"s" Where 10 > s 'BIND2:"s" Where DirectCast(Function() s > 1, Func(Of Boolean)).Invoke() 'BIND1:"s" Dim lambda2 As Func(Of Object) = Function() From s In 'BIND7:"s" (From s In q 'BIND8:"s" Where s > 0) 'BIND5:"s" Where 10 > s 'BIND4:"s" Dim q2 As Object = From s In q Where CByte(s) 'BIND9:"Where CByte(s)" Dim q3 As Object = From s In q Take While s > 0 'BIND10:"Take While s > 0" Dim q4 As Object = From s In q Skip While s > 0 'BIND11:"Skip While s > 0" Dim q5 As Object = From s In q Take 1 'BIND12:"Take 1" Dim q6 As Object = From s In q Skip 1 'BIND13:"Skip 1" End Sub End Module ]]></file> </compilation>) 'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary '---------------------------- Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node1, node2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Assert.NotEqual(node1, node3) Assert.NotEqual(node2, node3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim s6 = semanticModel1.GetDeclaredSymbol(node6) Assert.Same(s1, s6) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.NotSame(s1, s7) Assert.Equal("s", s7.Name) Assert.Equal("System.Int32", s7.Type.ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = semanticInfo.Symbol Assert.Same(s7, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s4) Assert.NotSame(s3, s4) Assert.Equal("s", s4.Name) Assert.Equal("System.Int32", s4.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8)) '---------------------------- Dim semanticModel2 = compilation.GetSemanticModel(tree) Assert.NotSame(semanticModel1, semanticModel2) Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s2) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node_3, node_2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.NotEqual(node_3, node_1) Assert.NotEqual(node_2, node_1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node9 As WhereClauseSyntax = CompilationUtils.FindBindingText(Of WhereClauseSyntax)(compilation, "a.vb", 9) Dim symbolInfo = semanticModel2.GetSymbolInfo(node9) Assert.Equal("Function QueryAble.Where(x As System.Func(Of System.Int32, System.Byte)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node10 As PartitionWhileClauseSyntax = CompilationUtils.FindBindingText(Of PartitionWhileClauseSyntax)(compilation, "a.vb", 10) symbolInfo = semanticModel2.GetSymbolInfo(node10) Assert.Equal("Function QueryAble.TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node11 As PartitionWhileClauseSyntax = CompilationUtils.FindBindingText(Of PartitionWhileClauseSyntax)(compilation, "a.vb", 11) symbolInfo = semanticModel2.GetSymbolInfo(node11) Assert.Equal("Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node12 As PartitionClauseSyntax = CompilationUtils.FindBindingText(Of PartitionClauseSyntax)(compilation, "a.vb", 12) symbolInfo = semanticModel2.GetSymbolInfo(node12) Assert.Equal("Function QueryAble.Take(x As System.Int32) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node13 As PartitionClauseSyntax = CompilationUtils.FindBindingText(Of PartitionClauseSyntax)(compilation, "a.vb", 13) symbolInfo = semanticModel2.GetSymbolInfo(node13) Assert.Equal("Function QueryAble.Skip(x As System.Int32) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub Query5() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q Where s > 0 'BIND:"s > 0" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.NarrowingBoolean, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_GreaterThan(left As System.Int32, right As System.Int32) As System.Boolean", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub Select1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function Public Function Join(inner As QueryAble, outer As Func(Of Integer, Integer), inner As Func(Of Integer, Integer), x as Func(Of Integer, Integer, Integer)) As QueryAble Return Me End Function Public Function Distinct() As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q 'BIND2:"s" Select x = s+1 'BIND1:"s" Select y = x 'BIND3:"y = x" Where y > 0 'BIND4:"y" Select y 'BIND5:"y" Where y > 0 'BIND6:"y" Select y = y 'BIND7:"y = y" Where y > 0 'BIND8:"y" Select y + 1 'BIND9:"y + 1" Select z = 1 'BIND10:"z" q1 = From s In q Select s 'BIND11:"Select s" q1 = From s In q Select CStr(s) 'BIND12:"Select CStr(s)" q1 = From s In q Take 1 Select s + 1 'BIND13:"Select s + 1" q1 = From s1 In q, s2 In q Select s1 + s2 'BIND14:"Select s1 + s2" q1 = From s1 In q Join s2 In q On s1 Equals s2 'BIND15:"Join s2 In q On s1 Equals s2" Select s1 + s2 'BIND16:"Select s1 + s2" q1 = From s In q Distinct 'BIND17:"Distinct" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Assert.Same(s1, semanticModel.GetDeclaredSymbol(node2)) Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3) Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("y", y1.Name) Assert.Equal("System.Int32", y1.Type.ToTestDisplayString()) Dim symbolInfo As SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(node3) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Same(y1, semanticInfo.Symbol) Dim node5_1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5_1, ExpressionSyntax)) Assert.Same(y1, semanticInfo.Symbol) Dim node5_2 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5) Dim y2 = DirectCast(semanticModel.GetDeclaredSymbol(node5_2), RangeVariableSymbol) Assert.Equal("y", y2.Name) Assert.Equal("System.Int32", y2.Type.ToTestDisplayString()) Assert.NotSame(y1, y2) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Assert.Same(y2, semanticInfo.Symbol) Dim node7 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 7) Dim y3 = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.Equal("y", y3.Name) Assert.Equal("System.Int32", y3.Type.ToTestDisplayString()) Assert.NotSame(y1, y3) Assert.NotSame(y2, y3) Assert.Same(y3, semanticModel.GetDeclaredSymbol(DirectCast(node7, VisualBasicSyntaxNode))) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node7.Expression) Assert.Same(y2, semanticInfo.Symbol) Dim node8 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 8) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax)) Assert.Same(y3, semanticInfo.Symbol) Dim node9 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 9) Assert.Null(semanticModel.GetDeclaredSymbol(node9)) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node9.Expression) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_Addition(left As System.Int32, right As System.Int32) As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node10 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 10) Dim z = DirectCast(semanticModel.GetDeclaredSymbol(node10), RangeVariableSymbol) Assert.Equal("z", z.Name) Assert.Equal("System.Int32", z.Type.ToTestDisplayString()) Assert.Same(z, semanticModel.GetDeclaredSymbol(DirectCast(node10, VisualBasicSyntaxNode))) Dim commonSymbolInfo As SymbolInfo Dim node11 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 11) symbolInfo = semanticModel.GetSymbolInfo(node11) Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(DirectCast(node11, SyntaxNode)) Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol) Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Dim node12 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 12) symbolInfo = semanticModel.GetSymbolInfo(node12) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim node13 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 13) symbolInfo = semanticModel.GetSymbolInfo(node13) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node14 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 14) symbolInfo = semanticModel.GetSymbolInfo(node14) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node15 As SimpleJoinClauseSyntax = CompilationUtils.FindBindingText(Of SimpleJoinClauseSyntax)(compilation, "a.vb", 15) symbolInfo = semanticModel.GetSymbolInfo(node15) Assert.Equal("Function QueryAble.Join(inner As QueryAble, outer As System.Func(Of System.Int32, System.Int32), inner As System.Func(Of System.Int32, System.Int32), x As System.Func(Of System.Int32, System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node16 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 16) symbolInfo = semanticModel.GetSymbolInfo(node16) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node17 As DistinctClauseSyntax = CompilationUtils.FindBindingText(Of DistinctClauseSyntax)(compilation, "a.vb", 17) symbolInfo = semanticModel.GetSymbolInfo(node17) Assert.Equal("Function QueryAble.Distinct() As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub ImplicitSelect1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As Integer In q Where s > 1 'BIND2:"q" System.Console.WriteLine("------") Dim q2 As Object = From s As Long In q Where s > 1 'BIND1:"q" System.Console.WriteLine("------") Dim q3 As Object = From s In q 'BIND3:"From s In q" 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 tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("QueryAble", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("QueryAble", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.Equal("q", s1.Name) Assert.Equal("QueryAble", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Same(s1, semanticInfo.Symbol) Dim node3 As QueryExpressionSyntax = CompilationUtils.FindBindingText(Of QueryExpressionSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node3, ExpressionSyntax)) Assert.Equal("QueryAble", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub OrderBy1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, 'BIND1:"x" x+1, 'BIND2:"x" x Descending 'BIND3:"x" Order By x Descending 'BIND4:"x" Select x 'BIND5:"x" Dim q2 As Object = From x In q Order By x 'BIND6:"Order By x" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("x", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) For i As Integer = 2 To 5 Dim node2to5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2to5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Next Dim node6 As OrderByClauseSyntax = CompilationUtils.FindBindingText(Of OrderByClauseSyntax)(compilation, "a.vb", 6) Dim symbolInfo = semanticModel.GetSymbolInfo(node6) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim orderBy = DirectCast(node1.Parent.Parent, OrderByClauseSyntax) For Each ordering In orderBy.Orderings symbolInfo = semanticModel.GetSymbolInfo(ordering) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(ordering) Assert.Null(commonSymbolInfo.Symbol) Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Next End Sub <Fact()> Public Sub OrderBy2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, 'BIND1:"x" x+1 'BIND2:"x+1" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As OrderingSyntax = CompilationUtils.FindBindingText(Of OrderingSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel.GetSymbolInfo(node1) Assert.Equal("Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node1) Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol) Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Dim node2 As OrderingSyntax = CompilationUtils.FindBindingText(Of OrderingSyntax)(compilation, "a.vb", 2) symbolInfo = semanticModel.GetSymbolInfo(node2) Assert.Equal("Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node2) Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol) Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub Select2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q Select x = s, 'BIND1:"s" y = s, 'BIND2:"s" z = s, 'BIND3:"z = s" w = s, 'BIND4:"w" s, 'BIND5:"s" z = s 'BIND6:"z = s" Where z > 0 'BIND7:"z" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.Same(s1, CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)).Symbol) Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3) Dim z1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("z", z1.Name) Assert.Equal("System.Int32", z1.Type.ToTestDisplayString()) Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol) Assert.Equal("w", w1.Name) Assert.Equal("System.Int32", w1.Type.ToTestDisplayString()) Dim node5 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5) Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.NotSame(s1, s2) Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6) Dim z2 = DirectCast(semanticModel.GetDeclaredSymbol(node6), RangeVariableSymbol) Assert.Equal("z", z2.Name) Assert.Equal("System.Int32", z2.Type.ToTestDisplayString()) Assert.NotSame(z1, z2) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) Assert.Same(z1, CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)).Symbol) End Sub <Fact()> Public Sub Let1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q Let x = s, 'BIND1:"s" y = x+1, 'BIND2:"x" x = s, 'BIND3:"x = s" w = x 'BIND4:"x" Dim q2 As Object = From s In q Let x = s 'BIND5:"Let x = s" q2 = From s In q, s2 In q Let x = s 'BIND6:"x = s" q2 = From s In q Join s2 In q On s Equals s2 Let x = s 'BIND7:"x = s" q2 = From s In q Select s+1 Let x = 1 'BIND8:"x = 1" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier)) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim symbolInfo = semanticModel.GetSymbolInfo(node3) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent), RangeVariableSymbol) Assert.Equal("w", w1.Name) Assert.Equal("System.Int32", w1.Type.ToTestDisplayString()) Assert.Same(w1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier)) Dim node5 As LetClauseSyntax = CompilationUtils.FindBindingText(Of LetClauseSyntax)(compilation, "a.vb", 5) symbolInfo = semanticModel.GetSymbolInfo(node5) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6) symbolInfo = semanticModel.GetSymbolInfo(node6) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node6) Assert.Null(commonSymbolInfo.Symbol) Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Dim node7 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 7) symbolInfo = semanticModel.GetSymbolInfo(node7) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node8 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 8) symbolInfo = semanticModel.GetSymbolInfo(node8) Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node8) Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol) Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub Let2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Program Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = From s In qi Let x = s, 'BIND1:"x = s" y = x+1, 'BIND2:"y = x+1" x = s 'BIND3:"x = s" Dim q2 As Object = From s In qi Join s2 In qi On s Equals s2 'BIND7:"Join s2 In qi On s Equals s2" Let x = s, 'BIND4:"x = s" y = x+1, 'BIND5:"y = x+1" x = s 'BIND6:"x = s" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel.GetSymbolInfo(node1) Assert.Equal("Function QueryAble(Of System.Int32).Select(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>)(x As System.Func(Of System.Int32, <anonymous type: Key s As System.Int32, Key x As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node2 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 2) symbolInfo = semanticModel.GetSymbolInfo(node2) Assert.Equal("Function QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)(x As System.Func(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3) symbolInfo = semanticModel.GetSymbolInfo(node3) Assert.Equal("Function QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>).Select(Of <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)(x As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>, <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node4 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 4) symbolInfo = semanticModel.GetSymbolInfo(node4) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node5 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5) symbolInfo = semanticModel.GetSymbolInfo(node5) Assert.Equal("Function QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)(x As System.Func(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6) symbolInfo = semanticModel.GetSymbolInfo(node6) Assert.Equal("Function QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>).Select(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)(x As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node7 As SimpleJoinClauseSyntax = CompilationUtils.FindBindingText(Of SimpleJoinClauseSyntax)(compilation, "a.vb", 7) symbolInfo = semanticModel.GetSymbolInfo(node7) Assert.Equal("Function QueryAble(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)(inner As QueryAble(Of System.Int32), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Int32, System.Int32), x As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub BindingMemberAccessInsideQuery() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="BindingMemberAccessInsideQuery"> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(x As Integer) Dim xxx = From i In New Integer() {1, 2, x.ToString().Length } Select y = x 'BIND1:"x.ToString" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Public Overrides Function ToString() As String", symbolInfo.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub BindingMemberAccessInsideQuery2() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="BindingMemberAccessInsideQuery2"> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(x As String) Dim xxx = From i In New Integer() {1, 2, x.Length } Select y = x 'BIND1:"x.Length" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Public Overloads ReadOnly Property Length As Integer", symbolInfo.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub BindingMemberAccessInsideQuery3() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="BindingMemberAccessInsideQuery3"> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(x As Integer) Dim xxx = From i In New Integer() {1, 2 } Select y = x.ToString.Length 'BIND1:"x.ToString" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Public Overrides Function ToString() As String", symbolInfo.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub BindingMemberAccessInsideQuery4() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="BindingMemberAccessInsideQuery4"> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(x As String) Dim xxx = From i In New Integer() {1, 2 } Select y = x.Length.ToString() 'BIND1:"x.Length" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Public Overloads ReadOnly Property Length As Integer", symbolInfo.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub From1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New() End Sub Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Class QueryAble2(Of T) Public Function AsQueryable As QueryAble(Of T) Return New QueryAble(Of T)(1) End Function End Class Class QueryAble3(Of T) Public Function AsEnumerable As QueryAble(Of T) Return New QueryAble(Of T)(1) End Function End Class Class QueryAble4(Of T) Inherits QueryAble(Of T) End Class Class QueryAble5 Public Function Cast(Of T)() As QueryAble4(Of T) Return New QueryAble4(Of T)() End Function End Class Public Function AsEnumerable As QueryAble(Of T) Return New QueryAble(Of T)(1) End Function End Class Module Program Function Test(Of T)(x As T) As T return x End Function Sub Main(args As String()) Dim qi As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s In qi From x In s, 'BIND1:"s" y In Test(x), 'BIND2:"x" x In s, 'BIND3:"x In s" w In x 'BIND4:"x" Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim q2 As Object = From s1 In qb, s2 In qs Select s1+s2 'BIND5:"s2" Dim q3 As Object = From s1 In qb, s2 In qs Select s1+s2 'BIND6:"s1+s2" Dim q4 As Object = From s1 In qb, s2 In qs Select s3 = s1+s2 'BIND7:"s3" Dim q5 As Object = From s1 In qb, s2 In qs Let s3 = 'BIND8:"s3" CInt(s1+s2) 'BIND9:"s1" Dim q6 As Object = From s In qi 'BIND10:"From s In qi" From x In s 'BIND11:"From x In s" Dim q6 As Object = From s In qi 'BIND12:"From s In qi" Dim q As Object q = From s In qi 'BIND13:"s In qi" q = From s In qi, s2 In s 'BIND14:"s2 In s" q = From s In qi, s2 In s, s5 As Integer In s2 'BIND15:"s5 As Integer In s2" Dim qii As New QueryAble(Of Integer)(0) q = From s3 As Integer In qii 'BIND16:"s3 As Integer In qii" q = From s4 As Long In qii 'BIND17:"s4 As Long In qii" q = From s In qi, s2 In s From s6 As Long In s2 'BIND18:"s6 As Long In s2" Dim qj As New QueryAble2(Of Integer)() q = From s7 In qj 'BIND19:"s7 In qj" Dim qjj As New QueryAble(Of QueryAble2(Of Integer))(0) q = From s in qjj, s8 In s 'BIND20:"s8 In s" q = From s9 As Integer In New QueryAble3(Of Integer)() 'BIND21:"s9 As Integer In New QueryAble3(Of Integer)()" q = From s10 As Long In qj 'BIND22:"s10 As Long In qj" q = From s in qjj, s11 As Integer In s 'BIND23:"s11 As Integer In s" q = From s in qjj, s12 As Long In s 'BIND24:"s12 As Long In s" q = From s In qi, s2 In s, s13 In s2 'BIND25:"s13 In s2" Select s13 q = From s In qi, s2 In s, s14 In s2 'BIND26:"s14 In s2" Let s15 = 0 q = From s16 In New QueryAble5() 'BIND27:"s16 In New QueryAble5()" Take 10 End Sub <System.Runtime.CompilerServices.Extension()> Public Function Take(Of T)(this As QueryAble(Of T), x as Integer) As QueryAble(Of T) Return this End Function End Module Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("QueryAble(Of System.Int32)", x1.Type.ToTestDisplayString()) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax).Identifier)) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim node3 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 3) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("QueryAble(Of System.Int32)", x1.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent), RangeVariableSymbol) Assert.Equal("w", w1.Name) Assert.Equal("System.Int32", w1.Type.ToTestDisplayString()) Assert.Same(w1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent, CollectionRangeVariableSyntax).Identifier)) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s2", s2.Name) Assert.Equal("System.Int16", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6) Assert.Null(semanticModel.GetDeclaredSymbol(node6)) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s3 = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.Equal("s3", s3.Name) Assert.Equal("System.Int16", s3.Type.ToTestDisplayString()) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) s3 = DirectCast(semanticModel.GetDeclaredSymbol(node8), RangeVariableSymbol) Assert.Equal("s3", s3.Name) Assert.Equal("System.Int32", s3.Type.ToTestDisplayString()) Dim node9 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 9) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node9, ExpressionSyntax)) Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s1", s2.Name) Assert.Equal("System.Byte", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node10 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 10) Dim symbolInfo = semanticModel.GetSymbolInfo(node10) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node11 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 11) symbolInfo = semanticModel.GetSymbolInfo(node11) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node12 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 12) symbolInfo = semanticModel.GetSymbolInfo(node12) Assert.Equal("Function QueryAble(Of QueryAble(Of QueryAble(Of System.Int32))).Select(Of QueryAble(Of QueryAble(Of System.Int32)))(x As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of QueryAble(Of System.Int32)))) As QueryAble(Of QueryAble(Of QueryAble(Of System.Int32)))", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim collectionInfo As CollectionRangeVariableSymbolInfo Dim node13 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 13) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node13) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s As QueryAble(Of QueryAble(Of System.Int32))", semanticModel.GetDeclaredSymbol(node13).ToTestDisplayString()) If True Then Dim node14 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 14) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node14) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of QueryAble(Of QueryAble(Of System.Int32))).SelectMany(Of QueryAble(Of System.Int32), <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)(m As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of QueryAble(Of System.Int32))), x As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of System.Int32), <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s2 As QueryAble(Of System.Int32)", semanticModel.GetDeclaredSymbol(node14).ToTestDisplayString()) Dim node15 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 14) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node14) End If If True Then Dim node15 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 15) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node15) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s5 As System.Int32", semanticModel.GetDeclaredSymbol(node15).ToTestDisplayString()) End If If True Then Dim node16 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 16) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node16) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s3 As System.Int32", semanticModel.GetDeclaredSymbol(node16).ToTestDisplayString()) End If If True Then Dim node17 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 17) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node17) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) symbolInfo = collectionInfo.AsClauseConversion Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s4 As System.Int64", semanticModel.GetDeclaredSymbol(node17).ToTestDisplayString()) End If If True Then Dim node18 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 18) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node18) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) symbolInfo = collectionInfo.AsClauseConversion Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int64, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int64)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int64, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s6 As System.Int64", semanticModel.GetDeclaredSymbol(node18).ToTestDisplayString()) End If If True Then Dim node19 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 19) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node19) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s7 As System.Int32", semanticModel.GetDeclaredSymbol(node19).ToTestDisplayString()) End If If True Then Dim node20 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 20) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node20) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int32)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s8 As System.Int32", semanticModel.GetDeclaredSymbol(node20).ToTestDisplayString()) End If If True Then Dim node21 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 21) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node21) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble3(Of System.Int32).AsEnumerable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s9 As System.Int32", semanticModel.GetDeclaredSymbol(node21).ToTestDisplayString()) End If If True Then Dim node22 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 22) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node22) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = collectionInfo.AsClauseConversion Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s10 As System.Int64", semanticModel.GetDeclaredSymbol(node22).ToTestDisplayString()) End If If True Then Dim node23 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 23) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node23) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int32)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s11 As System.Int32", semanticModel.GetDeclaredSymbol(node23).ToTestDisplayString()) End If If True Then Dim node24 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 24) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node24) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = collectionInfo.AsClauseConversion Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int64, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int64)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int64, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s12 As System.Int64", semanticModel.GetDeclaredSymbol(node24).ToTestDisplayString()) End If If True Then Dim node25 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 25) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node25) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, System.Int32)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, System.Int32)) As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s13 As System.Int32", semanticModel.GetDeclaredSymbol(node25).ToTestDisplayString()) End If If True Then Dim node26 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 26) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node26) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s14 As System.Int32", semanticModel.GetDeclaredSymbol(node26).ToTestDisplayString()) End If If True Then Dim node27 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 27) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node27) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble5.Cast(Of System.Object)() As QueryAble4(Of System.Object)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s16 As System.Object", semanticModel.GetDeclaredSymbol(node27).ToTestDisplayString()) End If End Sub <Fact()> Public Sub Join1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Program Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s In qi Join x In qb 'BIND1:"x" On s Equals x + 1 'BIND2:"x" Join y In qs 'BIND3:"y" Join x In qu 'BIND4:"x" On y + 1 Equals 'BIND5:"y" x 'BIND6:"x" On y Equals s Join w In ql On w Equals y And w Equals x 'BIND7:"x" End Sub End Module ]]></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 node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("System.Byte", x1.Type.ToTestDisplayString()) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Dim x2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("System.Byte", x2.Type.ToTestDisplayString()) Assert.Same(x1, x2) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("y", y1.Name) Assert.Equal("System.Int16", y1.Type.ToTestDisplayString()) Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol) Assert.Equal("x", x3.Name) Assert.Equal("System.UInt32", x3.Type.ToTestDisplayString()) Assert.NotSame(x1, x3) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax)) Assert.Same(y1, semanticInfo.Symbol) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Assert.Null(semanticInfo.Symbol) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) End Sub <Fact()> Public Sub GroupBy1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Program Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s In qi Join x In qb On s Equals x Join y In qs Join x In qu On y Equals x On y Equals s Join w In ql On w Equals y And w Equals x Group i1 = s+1, 'BIND1:"s" x, 'BIND2:"x" x 'BIND3:"x" By k1 = y+1S, 'BIND4:"y" w, 'BIND5:"w" w 'BIND6:"w" Into Group, 'BIND7:"Group" k1= Count(), 'BIND8:"k1" k1= Count(), 'BIND9:"k1" r2 = Count(i1+ 'BIND10:"i1" x) 'BIND11:"x" Select w, 'BIND12:"w" k1 'BIND13:"k1" Dim q2 As Object = From s In qi Group By s Into Group 'BIND14:"Group By s Into Group" End Sub End Module ]]></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 node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s.Name) Assert.Equal("System.Int32", s.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim i1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent.Parent), RangeVariableSymbol) Assert.Equal("i1", i1.Name) Assert.Equal("System.Int32", i1.Type.ToTestDisplayString()) Assert.Same(i1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier)) Assert.Same(i1, semanticModel.GetDeclaredSymbol(DirectCast(DirectCast(node1.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier, VisualBasicSyntaxNode))) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Dim x1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("System.Byte", x1.Type.ToTestDisplayString()) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node2.Parent), RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("System.Byte", x2.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node2.Parent, ExpressionRangeVariableSyntax)) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Dim x3 = semanticModel.GetDeclaredSymbol(node3.Parent) Assert.NotSame(x1, x3) Assert.NotSame(x2, x3) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim y = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("y", y.Name) Assert.Equal("System.Int16", y.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim k1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent.Parent), RangeVariableSymbol) Assert.Equal("k1", k1.Name) Assert.Equal("System.Int16", k1.Type.ToTestDisplayString()) Assert.Same(k1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier)) Assert.Same(k1, semanticModel.GetDeclaredSymbol(DirectCast(DirectCast(node4.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier, VisualBasicSyntaxNode))) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax)) Dim w1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("w", w1.Name) Assert.Equal("System.Int64", w1.Type.ToTestDisplayString()) Dim w2 = DirectCast(semanticModel.GetDeclaredSymbol(node5.Parent), RangeVariableSymbol) Assert.Equal("w", w2.Name) Assert.Equal("System.Int64", w2.Type.ToTestDisplayString()) Assert.NotSame(w1, w2) symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node5.Parent, ExpressionRangeVariableSyntax)) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) Dim w3 = semanticModel.GetDeclaredSymbol(node6.Parent) Assert.NotSame(w1, w3) Assert.NotSame(w2, w3) Dim node7 As AggregationRangeVariableSyntax = CompilationUtils.FindBindingText(Of AggregationRangeVariableSyntax)(compilation, "a.vb", 7) Dim gr = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.Equal("Group", gr.Name) Assert.Equal("QueryAble(Of <anonymous type: Key i1 As System.Int32, Key x As System.Byte, Key $2080 As System.Byte>)", gr.Type.ToTestDisplayString()) Assert.Same(gr, semanticModel.GetDeclaredSymbol(DirectCast(node7, VisualBasicSyntaxNode))) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node7.Aggregation) Assert.Same(gr.Type, semanticInfo.Type) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Same(gr.Type, semanticInfo.ConvertedType) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Null(semanticInfo.Alias) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Dim k2 = DirectCast(semanticModel.GetDeclaredSymbol(node8.Parent.Parent), RangeVariableSymbol) Assert.Equal("k1", k2.Name) Assert.Equal("System.Int32", k2.Type.ToTestDisplayString()) Assert.Same(k2, semanticModel.GetDeclaredSymbol(DirectCast(node8.Parent.Parent, AggregationRangeVariableSyntax))) Assert.Same(k2, semanticModel.GetDeclaredSymbol(DirectCast(node8, VisualBasicSyntaxNode))) Assert.Same(k2, semanticModel.GetDeclaredSymbol(node8)) Assert.NotSame(k1, k2) Dim node9 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 9) Dim k3 = semanticModel.GetDeclaredSymbol(node9) Assert.NotNull(k3) Assert.NotSame(k1, k3) Assert.NotSame(k2, k3) Dim node10 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 10) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node10, ExpressionSyntax)) Assert.Same(i1, semanticInfo.Symbol) Dim node11 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 11) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node11, ExpressionSyntax)) Assert.Same(x2, semanticInfo.Symbol) Dim node12 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 12) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node12, ExpressionSyntax)) Assert.Same(w2, semanticInfo.Symbol) Dim node13 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 13) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node13, ExpressionSyntax)) Assert.Same(k1, semanticInfo.Symbol) Dim node14 As GroupByClauseSyntax = CompilationUtils.FindBindingText(Of GroupByClauseSyntax)(compilation, "a.vb", 14) symbolInfo = semanticModel.GetSymbolInfo(node14) Assert.Equal("Function QueryAble(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)(key As System.Func(Of System.Int32, System.Int32), into As System.Func(Of System.Int32, QueryAble(Of System.Int32), <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact()> <CompilerTrait(CompilerFeature.IOperation)> Public Sub GroupJoin1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Program Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s In qi Group Join x In qb 'BIND1:"x" On s Equals x + 1 'BIND2:"x" Into x = Group 'BIND8:"x" Group Join y In qs 'BIND3:"y" Group Join x In qu 'BIND4:"x" On y + 1 Equals 'BIND5:"y" x 'BIND6:"x" Into Group On y Equals s Into y = Group Group Join w In ql On w Equals y And w Equals x 'BIND7:"x" Into Group Dim q2 As Object = From s In qi Group Join x In qb On s Equals x Into Group 'BIND9:"Group Join x In qb On s Equals x Into Group" End Sub End Module ]]></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 node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("System.Byte", x1.Type.ToTestDisplayString()) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Dim x2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("System.Byte", x2.Type.ToTestDisplayString()) Assert.Same(x1, x2) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Dim x4 = DirectCast(semanticModel.GetDeclaredSymbol(node8), RangeVariableSymbol) Assert.Equal("x", x4.Name) Assert.Equal("QueryAble(Of System.Byte)", x4.Type.ToTestDisplayString()) Assert.Same(x4, semanticModel.GetDeclaredSymbol(DirectCast(node8, VisualBasicSyntaxNode))) Assert.Same(x4, semanticModel.GetDeclaredSymbol(DirectCast(node8.Parent.Parent, AggregationRangeVariableSyntax))) Assert.Same(x4, semanticModel.GetDeclaredSymbol(node8.Parent.Parent)) Assert.NotSame(x1, x4) Assert.NotSame(x2, x4) Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("y", y1.Name) Assert.Equal("System.Int16", y1.Type.ToTestDisplayString()) Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol) Assert.Equal("x", x3.Name) Assert.Equal("System.UInt32", x3.Type.ToTestDisplayString()) Assert.NotSame(x1, x3) Assert.NotSame(x2, x3) Assert.NotSame(x4, x3) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax)) Assert.Same(y1, semanticInfo.Symbol) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Assert.Same(x3, semanticInfo.Symbol) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)) Assert.Same(x4, semanticInfo.Symbol) Dim node9 As GroupJoinClauseSyntax = CompilationUtils.FindBindingText(Of GroupJoinClauseSyntax)(compilation, "a.vb", 9) Dim symbolInfo = semanticModel.GetSymbolInfo(node9) Assert.Equal("Function QueryAble(Of System.Int32).GroupJoin(Of System.Byte, System.Int32, <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)(inner As QueryAble(Of System.Byte), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Byte, System.Int32), x As System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node = tree.GetRoot().DescendantNodes().OfType(Of QueryExpressionSyntax)().First() compilation.VerifyOperationTree(node, expectedOperationTree:= <![CDATA[ ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q ... Into Group') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Children(5): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Children(1): IInvocationOperation ( Function QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>).GroupJoin(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)(inner As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), outerKey As System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, System.Int32), innerKey As System.Func(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32), x As System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>), IsImplicit) (Syntax: 'Group Join ... o y = Group') Instance Receiver: IInvocationOperation ( Function QueryAble(Of System.Int32).GroupJoin(Of System.Byte, System.Int32, <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)(inner As QueryAble(Of System.Byte), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Byte, System.Int32), x As System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>), IsImplicit) (Syntax: 'Group Join ... o x = Group') Instance Receiver: ILocalReferenceOperation: qi (OperationKind.LocalReference, Type: QueryAble(Of System.Int32)) (Syntax: 'qi') Arguments(4): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'qb') ILocalReferenceOperation: qb (OperationKind.LocalReference, Type: QueryAble(Of System.Byte)) (Syntax: 'qb') 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: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's') Target: IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's') ReturnedValue: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + 1') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Byte, System.Int32), IsImplicit) (Syntax: 'x + 1') Target: IAnonymousFunctionOperation (Symbol: Function (x As System.Byte) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + 1') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>), IsImplicit) (Syntax: 'Group Join ... o x = Group') Target: IAnonymousFunctionOperation (Symbol: Function (s As System.Int32, $VB$ItAnonymous As QueryAble(Of System.Byte)) As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's In qi') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group') Right: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.Byte), IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'Group Join ... o x = Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group') Right: IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'Group Join ... o x = Group') 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) Arguments(4): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') IInvocationOperation ( Function QueryAble(Of System.Int16).GroupJoin(Of System.UInt32, System.Int64, <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)(inner As QueryAble(Of System.UInt32), outerKey As System.Func(Of System.Int16, System.Int64), innerKey As System.Func(Of System.UInt32, System.Int64), x As System.Func(Of System.Int16, QueryAble(Of System.UInt32), <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: ILocalReferenceOperation: qs (OperationKind.LocalReference, Type: QueryAble(Of System.Int16)) (Syntax: 'qs') Arguments(4): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'qu') ILocalReferenceOperation: qu (OperationKind.LocalReference, Type: QueryAble(Of System.UInt32)) (Syntax: 'qu') 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: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y + 1') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int16, System.Int64), IsImplicit) (Syntax: 'y + 1') Target: IAnonymousFunctionOperation (Symbol: Function (y As System.Int16) As System.Int64) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y + 1') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y + 1') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y + 1') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'y + 1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y + 1') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'y') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.UInt32, System.Int64), IsImplicit) (Syntax: 'x') Target: IAnonymousFunctionOperation (Symbol: Function (x As System.UInt32) As System.Int64) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.UInt32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int16, QueryAble(Of System.UInt32), <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... Into Group') Target: IAnonymousFunctionOperation (Symbol: Function (y As System.Int16, $VB$ItAnonymous As QueryAble(Of System.UInt32)) As <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int16, IsImplicit) (Syntax: 'y In qs') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.y As System.Int16 (OperationKind.PropertyReference, Type: System.Int16, IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'y') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... o y = Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.Group As QueryAble(Of System.UInt32) (OperationKind.PropertyReference, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... Into Group') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, System.Int32), IsImplicit) (Syntax: 'y') Target: IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y') ReturnedValue: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'y') 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: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32), IsImplicit) (Syntax: 's') Target: IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.y As System.Int16 (OperationKind.PropertyReference, Type: System.Int16) (Syntax: 'y') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>), IsImplicit) (Syntax: 'Group Join ... o y = Group') Target: IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, $VB$ItAnonymous As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') Right: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... o y = Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') Right: IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... o y = Group') 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) ILocalReferenceOperation: ql (OperationKind.LocalReference, Type: QueryAble(Of System.Int64)) (Syntax: 'ql') IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'w') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'w') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'w') ReturnedValue: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Children(2): IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsInvalid) (Syntax: 'y') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'w') IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsInvalid) (Syntax: 'x') Instance Receiver: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'w') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'w') IAnonymousFunctionOperation (Symbol: Function (w As System.Int64) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'y') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'y') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'y') ReturnedValue: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Children(2): IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int64, IsInvalid) (Syntax: 'w') IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int64, IsInvalid) (Syntax: 'w') IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, $VB$ItAnonymous As ?) As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Initializers(4): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's In qi') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's') Instance Receiver: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x =') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x') Instance Receiver: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y =') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.Group As ? (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ]]>.Value) End Sub <Fact()> Public Sub Aggregate1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count() As Integer End Function End Class Module Program Function Test(Of T)(x as T) As T return x End Function Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim q1 As Object = Aggregate s In qi, 'BIND1:"s" s In 'BIND2:"s" Test(qb) 'BIND6:"qb" Into x = 'BIND3:"x" Where(s > 0), 'BIND4:"s" x = Distinct 'BIND5:"x" Dim q2 As Object = Aggregate s1 In New QueryAble(Of QueryAble(Of Integer))(0), s2 In Test(s1) 'BIND7:"s1" Into x = Distinct q2 = DirectCast(qi.Select(Function(i) i), Object) 'BIND8:"qi.Select(Function(i) i)" q2 = Aggregate i In qi Into [Select](i) 'BIND9:"[Select](i)" Dim qii As New QueryAble(Of QueryAble(Of Integer))(0) q2 = Aggregate ii In qii Into [Select](From i In ii) 'BIND10:"ii" q2 = Aggregate i In qi Into Count(i) 'BIND11:"Count(i)" q2 = Aggregate i In qi Into Count() 'BIND12:"Aggregate i In qi Into Count()" q2 = Aggregate i In qi Into Count(), [Select](i) 'BIND13:"Aggregate i In qi Into Count(), [Select](i)" End Sub End Module ]]></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 node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim s1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode))) Assert.Same(s1, semanticModel.GetDeclaredSymbol(node1.Parent)) Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax))) Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), RangeVariableSymbol) Assert.Equal("s", s2.Name) Assert.Equal("System.Byte", s2.Type.ToTestDisplayString()) Assert.NotSame(s1, s2) Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("?", x1.Type.ToTestDisplayString()) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3, VisualBasicSyntaxNode))) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3.Parent.Parent, AggregationRangeVariableSyntax))) Assert.Same(x1, semanticModel.GetDeclaredSymbol(node3.Parent.Parent)) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s3.Name) Assert.Equal("System.Int32", s3.Type.ToTestDisplayString()) Assert.Same(s1, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("?", x1.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Assert.Equal("qb As QueryAble(Of System.Byte)", semanticInfo.Symbol.ToTestDisplayString()) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)) Assert.Equal("s1 As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) For i As Integer = 8 To 9 Dim node8 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", i) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax)) Assert.Equal("QueryAble(Of System.Int32)", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("QueryAble(Of System.Int32)", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int32)(x As System.Func(Of System.Int32, System.Int32)) As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Null(semanticInfo.Alias) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Next Dim node9 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 9) Dim symbolInfo1 = semanticModel.GetSymbolInfo(node9) Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int32)(x As System.Func(Of System.Int32, System.Int32)) As QueryAble(Of System.Int32)", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Dim symbolInfo2 = semanticModel.GetSymbolInfo(DirectCast(node9, FunctionAggregationSyntax)) Assert.Equal(symbolInfo1.CandidateReason, symbolInfo2.CandidateReason) Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol) Assert.Equal(0, symbolInfo2.CandidateSymbols.Length) Dim commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(DirectCast(node9, SyntaxNode)) Assert.Equal(symbolInfo1.CandidateReason, commonSymbolInfo.CandidateReason) Assert.Same(symbolInfo1.Symbol, commonSymbolInfo.Symbol) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Dim node10 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 10) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node10, ExpressionSyntax)) Assert.Equal("ii As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Dim node11 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 11) symbolInfo1 = semanticModel.GetSymbolInfo(node11) Assert.Null(symbolInfo1.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason) Assert.Equal(1, symbolInfo1.CandidateSymbols.Length) Assert.Equal("Function QueryAble(Of System.Int32).Count() As System.Int32", symbolInfo1.CandidateSymbols(0).ToTestDisplayString()) symbolInfo2 = semanticModel.GetSymbolInfo(DirectCast(node11, FunctionAggregationSyntax)) Assert.Equal(symbolInfo1.CandidateReason, symbolInfo2.CandidateReason) Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol) Assert.True(symbolInfo1.CandidateSymbols.SequenceEqual(symbolInfo2.CandidateSymbols)) Dim node12 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 12) symbolInfo1 = semanticModel.GetSymbolInfo(node12) Assert.Null(symbolInfo1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Dim symbolInfo3 As AggregateClauseSymbolInfo = semanticModel.GetAggregateClauseSymbolInfo(node12) Assert.Null(symbolInfo3.Select1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select1.CandidateReason) Assert.Null(symbolInfo3.Select2.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason) Dim node13 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 13) symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node13) Assert.Null(symbolInfo3.Select1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select1.CandidateReason) Assert.Null(symbolInfo3.Select2.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason) End Sub <Fact()> Public Sub Aggregate2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count() As Integer End Function End Class Module Program Function Test(Of T)(x as T) As T return x End Function Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim q1 As Object = From y In qs Aggregate s In qi, 'BIND1:"s" s In qb 'BIND2:"s" Into x = 'BIND3:"x" Where(s > 'BIND4:"s" y), 'BIND6:"y" x = Distinct 'BIND5:"x" Select x 'BIND7:"x" Dim q2 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Aggregate s2 In Test(s1) 'BIND8:"s1" Into x = Distinct Dim q3 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Aggregate s2 In s1 Into Count() 'BIND9:"Aggregate s2 In s1 Into Count()" Dim q4 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Where True Aggregate s2 In s1 Into Count() 'BIND10:"Aggregate s2 In s1 Into Count()" Dim q5 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Aggregate s2 In s1 Into Count(), [Select](s2) 'BIND11:"Aggregate s2 In s1 Into Count(), [Select](s2)" Dim q6 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Where True Aggregate s2 In s1 Into Count(), [Select](s2) 'BIND12:"Aggregate s2 In s1 Into Count(), [Select](s2)" End Sub End Module ]]></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 node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim s1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode))) Assert.Same(s1, semanticModel.GetDeclaredSymbol(node1.Parent)) Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax))) Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), RangeVariableSymbol) Assert.Equal("s", s2.Name) Assert.Equal("System.Byte", s2.Type.ToTestDisplayString()) Assert.NotSame(s1, s2) Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("?", x1.Type.ToTestDisplayString()) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3, VisualBasicSyntaxNode))) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3.Parent.Parent, AggregationRangeVariableSyntax))) Assert.Same(x1, semanticModel.GetDeclaredSymbol(node3.Parent.Parent)) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s3.Name) Assert.Equal("System.Int32", s3.Type.ToTestDisplayString()) Assert.Same(s1, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("?", x1.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Dim y1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("y", y1.Name) Assert.Equal("System.Int16", y1.Type.ToTestDisplayString()) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim node8 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 8) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax)) Assert.Equal("s1 As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Dim node9 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 9) Dim symbolInfo1 = semanticModel.GetSymbolInfo(node9) Assert.Null(symbolInfo1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Dim symbolInfo3 As AggregateClauseSymbolInfo symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node9) symbolInfo1 = symbolInfo3.Select1 Assert.Equal("Function QueryAble(Of QueryAble(Of System.Int32)).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)(x As System.Func(Of QueryAble(Of System.Int32), <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Assert.Null(symbolInfo3.Select2.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason) Dim node10 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 10) symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node10) symbolInfo1 = symbolInfo3.Select1 Assert.Null(symbolInfo1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Assert.Null(symbolInfo3.Select2.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason) Dim node11 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 11) symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node11) symbolInfo1 = symbolInfo3.Select1 Assert.Equal("Function QueryAble(Of QueryAble(Of System.Int32)).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)(x As System.Func(Of QueryAble(Of System.Int32), <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) symbolInfo1 = symbolInfo3.Select2 Assert.Equal("Function QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)(x As System.Func(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>, <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Dim node12 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 12) symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node12) symbolInfo1 = symbolInfo3.Select1 Assert.Null(symbolInfo1.Symbol) Assert.Equal(True, symbolInfo1.IsEmpty) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) symbolInfo1 = symbolInfo3.Select2 Assert.Null(symbolInfo1.Symbol) Assert.Equal(True, symbolInfo1.IsEmpty) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) End Sub <Fact()> Public Sub Aggregate3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) 'Inherits Base 'Public Shadows [Select] As Byte Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T) System.Console.WriteLine("Where {0}", x) Return New QueryAble(Of T)(v + 1) End Function Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T) System.Console.WriteLine("TakeWhile {0}", x) Return New QueryAble(Of T)(v + 1) End Function Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T) System.Console.WriteLine("SkipWhile {0}", x) Return New QueryAble(Of T)(v + 1) End Function Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T) System.Console.WriteLine("OrderBy {0}", x) Return New QueryAble(Of T)(v + 1) End Function Public Function Distinct() As QueryAble(Of T) System.Console.WriteLine("Distinct") Return New QueryAble(Of T)(v + 1) End Function Public Function Skip(count As Integer) As QueryAble(Of T) System.Console.WriteLine("Skip {0}", count) Return New QueryAble(Of T)(v + 1) End Function Public Function Take(count As Integer) As QueryAble(Of T) System.Console.WriteLine("Take {0}", count) Return New QueryAble(Of T)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim q0 As Object q0 = From i In qi, b In qb Aggregate s In qs Into Where(True) 'BIND1:"Aggregate s In qs Into Where(True)" System.Console.WriteLine("------") q0 = From i In qi, b In qb Aggregate s In qs Into Where(True), Distinct() 'BIND2:"Aggregate s In qs Into Where(True), Distinct()" q0 = From i In qi Join b In qb On b Equals i Aggregate s In qs Into Where(True) 'BIND3:"Aggregate s In qs Into Where(True)" System.Console.WriteLine("------") q0 = From i In qi Join b In qb On b Equals i Aggregate s In qs Into Where(True), Distinct() 'BIND4:"Aggregate s In qs Into Where(True), Distinct()" End Sub End Module ]]></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 aggregateInfo As AggregateClauseSymbolInfo For i As Integer = 0 To 1 Dim node1 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 1 + 2 * i) aggregateInfo = semanticModel.GetAggregateClauseSymbolInfo(node1) symbolInfo = aggregateInfo.Select1 Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = aggregateInfo.Select2 Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node2 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 2 + 2 * i) aggregateInfo = semanticModel.GetAggregateClauseSymbolInfo(node2) symbolInfo = aggregateInfo.Select1 Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = aggregateInfo.Select2 Assert.Equal("Function QueryAble(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key $VB$Group As QueryAble(Of System.Int16)>).Select(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)(x As System.Func(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key $VB$Group As QueryAble(Of System.Int16)>, <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)) As QueryAble(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Next End Sub <WorkItem(546132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546132")> <Fact()> Public Sub SymbolInfoForFunctionAgtAregationSyntax() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Module m1 <System.Runtime.CompilerServices.Extension()> Sub aggr4(Of T)(ByVal this As T) End Sub End Module Class cls1 Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1 Return Nothing End Function Function GroupBy(Of K, R)(ByVal key As Func(Of Integer, K), ByVal result As Func(Of K, cls1, R)) As cls1 Return Nothing End Function Sub aggr4(Of T)(ByVal this As T) End Sub End Class Module AggrArgsInvalidmod Sub AggrArgsInvalid() Dim colm As New cls1 Dim q4 = From i In colm Group By vbCrLf Into aggr4(4) End Sub End Module ]]></file> </compilation>, references:={TestMetadata.Net40.SystemCore}) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_QueryOperatorNotFound, "aggr4").WithArguments("aggr4")) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel As SemanticModel = compilation.GetSemanticModel(tree) Dim node = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("aggr4(4)", StringComparison.Ordinal)).Parent, FunctionAggregationSyntax) Dim info = semanticModel.GetSymbolInfo(node) Assert.NotNull(info) Assert.Null(info.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason) Assert.Equal(2, info.CandidateSymbols.Length) End Sub <WorkItem(542521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542521")> <Fact()> Public Sub AddressOfOperatorInQuery() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module CodCov004mod Function scen2() As Object Return Nothing End Function Sub CodCov004() Dim q = From a In AddressOf scen2 End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim diagnostics = semanticModel.GetDiagnostics() Assert.NotEmpty(diagnostics) End Sub <WorkItem(542823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542823")> <Fact()> Public Sub DefaultAggregateClauseInfo() Dim aggrClauseSymInfo = New AggregateClauseSymbolInfo() Assert.Null(aggrClauseSymInfo.Select1.Symbol) Assert.Equal(0, aggrClauseSymInfo.Select1.CandidateSymbols.Length) Assert.Null(aggrClauseSymInfo.Select2.Symbol) Assert.Equal(0, aggrClauseSymInfo.Select2.CandidateSymbols.Length) End Sub <WorkItem(543084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543084")> <Fact()> Public Sub MissingIdentifierNameSyntaxInIncompleteLetClause() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim numbers = New Integer() {4, 5} Dim q1 = From num In numbers Let n As End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("n As", StringComparison.Ordinal)).Parent.Parent.DescendantNodes().OfType(Of IdentifierNameSyntax)().First() Dim info = semanticModel.GetTypeInfo(node) Assert.NotNull(info) Assert.Equal(TypeInfo.None, info) End Sub <WorkItem(542914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542914")> <Fact()> Public Sub Bug10356() Dim compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim numbers = New Integer() {4, 5} Dim d = From z In New Integer() {1, 2, 3} Let Group By End Sub End Module ]]></file> </compilation>, {SystemCoreRef}) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("By", StringComparison.Ordinal)).Parent.Parent.DescendantNodes().OfType(Of IdentifierNameSyntax)().First() Dim containingSymbol = DirectCast(semanticModel, SemanticModel).GetEnclosingSymbol(node.SpanStart) Assert.Equal("Function (z As System.Int32) As <anonymous type: Key z As System.Int32, Key Group As ?>", DirectCast(containingSymbol, Symbol).ToTestDisplayString()) End Sub <WorkItem(543161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543161")> <Fact()> Public Sub InaccessibleQueryMethodOnCollectionType() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Private Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T) System.Console.WriteLine("TakeWhile {0}", x) Return New QueryAble(Of T)(v + 1) End Function Private Function TakeWhile(x As Func(Of T, Integer)) As QueryAble(Of T) System.Console.WriteLine("TakeWhile {0}", x) Return New QueryAble(Of T)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q0 = From s1 In qi Take While False'BIND:"Take While False" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of PartitionWhileClauseSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("Function QueryAble(Of System.Int32).TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble(Of System.Int32)", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(546165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546165")> <Fact()> Public Sub QueryInsideEnumMemberDecl() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Test Enum Enum1 x = (From i In New Integer() {4, 5} Where True Select 1).First 'BIND:"True" End Enum End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) Assert.True(semanticSummary.ConstantValue.HasValue) 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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Partial Public Class GetExtendedSemanticInfoTests <Fact()> Public Sub Query1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q 'BIND6:"s" Where s > 0 'BIND3:"s" Where 10 > s 'BIND2:"s" Where DirectCast(Function() System.Console.WriteLine(s) 'BIND1:"s" Return True End Function, Func(Of Boolean)).Invoke() Dim q2 As Object = From s In 'BIND7:"s" (From s In q 'BIND8:"s" Where s > 0) 'BIND5:"s" Where 10 > s 'BIND4:"s" End Sub End Module ]]></file> </compilation>) 'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary '---------------------------- Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node1, node2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Assert.NotEqual(node1, node3) Assert.NotEqual(node2, node3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim s6 = semanticModel1.GetDeclaredSymbol(node6) Assert.Same(s1, s6) Assert.Same(s6, semanticModel1.GetDeclaredSymbol(DirectCast(node6, VisualBasicSyntaxNode))) Assert.Same(s6, semanticModel1.GetDeclaredSymbol(DirectCast(node6.Parent, CollectionRangeVariableSyntax))) Assert.Same(s6, semanticModel1.GetDeclaredSymbol(node6.Parent)) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.NotSame(s1, s7) Assert.Equal("s", s7.Name) Assert.Equal("System.Int32", s7.Type.ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = semanticInfo.Symbol Assert.Same(s7, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s4) Assert.NotSame(s3, s4) Assert.Equal("s", s4.Name) Assert.Equal("System.Int32", s4.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8)) '---------------------------- Dim semanticModel2 = compilation.GetSemanticModel(tree) Assert.NotSame(semanticModel1, semanticModel2) Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s2) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node_3, node_2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.NotEqual(node_3, node_1) Assert.NotEqual(node_2, node_1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub Query2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim lambda As Action = Sub() Dim q1 As Object = From s In q 'BIND6:"s" Where s > 0 'BIND3:"s" Where 10 > s 'BIND2:"s" Where DirectCast(Function() System.Console.WriteLine(s) 'BIND1:"s" Return True End Function, Func(Of Boolean)).Invoke() Dim q2 As Object = From s In 'BIND7:"s" (From s In q 'BIND8:"s" Where s > 0) 'BIND5:"s" Where 10 > s 'BIND4:"s" End Sub End Sub End Module ]]></file> </compilation>) 'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary '---------------------------- Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node1, node2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Assert.NotEqual(node1, node3) Assert.NotEqual(node2, node3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim s6 = semanticModel1.GetDeclaredSymbol(node6) Assert.Same(s1, s6) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.NotSame(s1, s7) Assert.Equal("s", s7.Name) Assert.Equal("System.Int32", s7.Type.ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = semanticInfo.Symbol Assert.Same(s7, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s4) Assert.NotSame(s3, s4) Assert.Equal("s", s4.Name) Assert.Equal("System.Int32", s4.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8)) '---------------------------- Dim semanticModel2 = compilation.GetSemanticModel(tree) Assert.NotSame(semanticModel1, semanticModel2) Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s2) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node_3, node_2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.NotEqual(node_3, node_1) Assert.NotEqual(node_2, node_1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub Query3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Dim q As New QueryAble() Dim q1 As Object = From s In q 'BIND6:"s" Where s > 0 'BIND3:"s" Where 10 > s 'BIND2:"s" Where DirectCast(Function() System.Console.WriteLine(s) 'BIND1:"s" Return True End Function, Func(Of Boolean)).Invoke() Dim q2 As Object = From s In 'BIND7:"s" (From s In q 'BIND8:"s" Where s > 0) 'BIND5:"s" Where 10 > s 'BIND4:"s" Sub Main(args As String()) End Sub End Module ]]></file> </compilation>) 'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary '---------------------------- Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node1, node2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Assert.NotEqual(node1, node3) Assert.NotEqual(node2, node3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim s6 = semanticModel1.GetDeclaredSymbol(node6) Assert.Same(s1, s6) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.NotSame(s1, s7) Assert.Equal("s", s7.Name) Assert.Equal("System.Int32", s7.Type.ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = semanticInfo.Symbol Assert.Same(s7, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s4) Assert.NotSame(s3, s4) Assert.Equal("s", s4.Name) Assert.Equal("System.Int32", s4.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8)) '---------------------------- Dim semanticModel2 = compilation.GetSemanticModel(tree) Assert.NotSame(semanticModel1, semanticModel2) Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s2) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node_3, node_2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.NotEqual(node_3, node_1) Assert.NotEqual(node_2, node_1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub Query4() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function Public Function TakeWhile(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function Public Function SkipWhile(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function Public Function Take(x As Integer) As QueryAble Return Me End Function Public Function Skip(x As Integer) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim lambda1 As Func(Of Object) = Function() From s In q 'BIND6:"s" Where s > 0 'BIND3:"s" Where 10 > s 'BIND2:"s" Where DirectCast(Function() s > 1, Func(Of Boolean)).Invoke() 'BIND1:"s" Dim lambda2 As Func(Of Object) = Function() From s In 'BIND7:"s" (From s In q 'BIND8:"s" Where s > 0) 'BIND5:"s" Where 10 > s 'BIND4:"s" Dim q2 As Object = From s In q Where CByte(s) 'BIND9:"Where CByte(s)" Dim q3 As Object = From s In q Take While s > 0 'BIND10:"Take While s > 0" Dim q4 As Object = From s In q Skip While s > 0 'BIND11:"Skip While s > 0" Dim q5 As Object = From s In q Take 1 'BIND12:"Take 1" Dim q6 As Object = From s In q Skip 1 'BIND13:"Skip 1" End Sub End Module ]]></file> </compilation>) 'Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb") Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary '---------------------------- Dim semanticModel1 = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node1, node2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Assert.NotEqual(node1, node3) Assert.NotEqual(node2, node3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim s6 = semanticModel1.GetDeclaredSymbol(node6) Assert.Same(s1, s6) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s7 = DirectCast(semanticModel1.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.NotSame(s1, s7) Assert.Equal("s", s7.Name) Assert.Equal("System.Int32", s7.Type.ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = semanticInfo.Symbol Assert.Same(s7, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel1, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s4 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s4) Assert.NotSame(s3, s4) Assert.Equal("s", s4.Name) Assert.Equal("System.Int32", s4.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Assert.Same(s4, semanticModel1.GetDeclaredSymbol(node8)) '---------------------------- Dim semanticModel2 = compilation.GetSemanticModel(tree) Assert.NotSame(semanticModel1, semanticModel2) Dim node_3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_3, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.NotSame(s1, s2) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.NotEqual(node_3, node_2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_2, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node_1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Assert.NotEqual(node_3, node_1) Assert.NotEqual(node_2, node_1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel2, TryCast(node_1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s2, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node9 As WhereClauseSyntax = CompilationUtils.FindBindingText(Of WhereClauseSyntax)(compilation, "a.vb", 9) Dim symbolInfo = semanticModel2.GetSymbolInfo(node9) Assert.Equal("Function QueryAble.Where(x As System.Func(Of System.Int32, System.Byte)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node10 As PartitionWhileClauseSyntax = CompilationUtils.FindBindingText(Of PartitionWhileClauseSyntax)(compilation, "a.vb", 10) symbolInfo = semanticModel2.GetSymbolInfo(node10) Assert.Equal("Function QueryAble.TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node11 As PartitionWhileClauseSyntax = CompilationUtils.FindBindingText(Of PartitionWhileClauseSyntax)(compilation, "a.vb", 11) symbolInfo = semanticModel2.GetSymbolInfo(node11) Assert.Equal("Function QueryAble.SkipWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node12 As PartitionClauseSyntax = CompilationUtils.FindBindingText(Of PartitionClauseSyntax)(compilation, "a.vb", 12) symbolInfo = semanticModel2.GetSymbolInfo(node12) Assert.Equal("Function QueryAble.Take(x As System.Int32) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node13 As PartitionClauseSyntax = CompilationUtils.FindBindingText(Of PartitionClauseSyntax)(compilation, "a.vb", 13) symbolInfo = semanticModel2.GetSymbolInfo(node13) Assert.Equal("Function QueryAble.Skip(x As System.Int32) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub Query5() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Byte)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q Where s > 0 'BIND:"s > 0" End Sub End Module ]]></file> </compilation>) Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of BinaryExpressionSyntax)(compilation, "a.vb") Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.NarrowingBoolean, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_GreaterThan(left As System.Int32, right As System.Int32) As System.Boolean", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub Select1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function Public Function Join(inner As QueryAble, outer As Func(Of Integer, Integer), inner As Func(Of Integer, Integer), x as Func(Of Integer, Integer, Integer)) As QueryAble Return Me End Function Public Function Distinct() As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q 'BIND2:"s" Select x = s+1 'BIND1:"s" Select y = x 'BIND3:"y = x" Where y > 0 'BIND4:"y" Select y 'BIND5:"y" Where y > 0 'BIND6:"y" Select y = y 'BIND7:"y = y" Where y > 0 'BIND8:"y" Select y + 1 'BIND9:"y + 1" Select z = 1 'BIND10:"z" q1 = From s In q Select s 'BIND11:"Select s" q1 = From s In q Select CStr(s) 'BIND12:"Select CStr(s)" q1 = From s In q Take 1 Select s + 1 'BIND13:"Select s + 1" q1 = From s1 In q, s2 In q Select s1 + s2 'BIND14:"Select s1 + s2" q1 = From s1 In q Join s2 In q On s1 Equals s2 'BIND15:"Join s2 In q On s1 Equals s2" Select s1 + s2 'BIND16:"Select s1 + s2" q1 = From s In q Distinct 'BIND17:"Distinct" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Assert.Same(s1, semanticModel.GetDeclaredSymbol(node2)) Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3) Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("y", y1.Name) Assert.Equal("System.Int32", y1.Type.ToTestDisplayString()) Dim symbolInfo As SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(node3) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Same(y1, semanticInfo.Symbol) Dim node5_1 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5_1, ExpressionSyntax)) Assert.Same(y1, semanticInfo.Symbol) Dim node5_2 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5) Dim y2 = DirectCast(semanticModel.GetDeclaredSymbol(node5_2), RangeVariableSymbol) Assert.Equal("y", y2.Name) Assert.Equal("System.Int32", y2.Type.ToTestDisplayString()) Assert.NotSame(y1, y2) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Assert.Same(y2, semanticInfo.Symbol) Dim node7 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 7) Dim y3 = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.Equal("y", y3.Name) Assert.Equal("System.Int32", y3.Type.ToTestDisplayString()) Assert.NotSame(y1, y3) Assert.NotSame(y2, y3) Assert.Same(y3, semanticModel.GetDeclaredSymbol(DirectCast(node7, VisualBasicSyntaxNode))) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node7.Expression) Assert.Same(y2, semanticInfo.Symbol) Dim node8 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 8) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax)) Assert.Same(y3, semanticInfo.Symbol) Dim node9 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 9) Assert.Null(semanticModel.GetDeclaredSymbol(node9)) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node9.Expression) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function System.Int32.op_Addition(left As System.Int32, right As System.Int32) As System.Int32", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node10 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 10) Dim z = DirectCast(semanticModel.GetDeclaredSymbol(node10), RangeVariableSymbol) Assert.Equal("z", z.Name) Assert.Equal("System.Int32", z.Type.ToTestDisplayString()) Assert.Same(z, semanticModel.GetDeclaredSymbol(DirectCast(node10, VisualBasicSyntaxNode))) Dim commonSymbolInfo As SymbolInfo Dim node11 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 11) symbolInfo = semanticModel.GetSymbolInfo(node11) Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(DirectCast(node11, SyntaxNode)) Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol) Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Dim node12 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 12) symbolInfo = semanticModel.GetSymbolInfo(node12) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim node13 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 13) symbolInfo = semanticModel.GetSymbolInfo(node13) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node14 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 14) symbolInfo = semanticModel.GetSymbolInfo(node14) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node15 As SimpleJoinClauseSyntax = CompilationUtils.FindBindingText(Of SimpleJoinClauseSyntax)(compilation, "a.vb", 15) symbolInfo = semanticModel.GetSymbolInfo(node15) Assert.Equal("Function QueryAble.Join(inner As QueryAble, outer As System.Func(Of System.Int32, System.Int32), inner As System.Func(Of System.Int32, System.Int32), x As System.Func(Of System.Int32, System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node16 As SelectClauseSyntax = CompilationUtils.FindBindingText(Of SelectClauseSyntax)(compilation, "a.vb", 16) symbolInfo = semanticModel.GetSymbolInfo(node16) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node17 As DistinctClauseSyntax = CompilationUtils.FindBindingText(Of DistinctClauseSyntax)(compilation, "a.vb", 17) symbolInfo = semanticModel.GetSymbolInfo(node17) Assert.Equal("Function QueryAble.Distinct() As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub ImplicitSelect1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble System.Console.WriteLine("Select") Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble System.Console.WriteLine("Where") Return Me End Function End Class Module Module1 <System.Runtime.CompilerServices.Extension()> Public Function [Select](this As QueryAble, x As Func(Of Integer, Long)) As QueryAble System.Console.WriteLine("[Select]") Return this End Function <System.Runtime.CompilerServices.Extension()> Public Function Where(this As QueryAble, x As Func(Of Long, Boolean)) As QueryAble System.Console.WriteLine("[Where]") Return this End Function Sub Main() Dim q As New QueryAble() Dim q1 As Object = From s As Integer In q Where s > 1 'BIND2:"q" System.Console.WriteLine("------") Dim q2 As Object = From s As Long In q Where s > 1 'BIND1:"q" System.Console.WriteLine("------") Dim q3 As Object = From s In q 'BIND3:"From s In q" 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 tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("QueryAble", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("QueryAble", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, LocalSymbol) Assert.Equal("q", s1.Name) Assert.Equal("QueryAble", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Same(s1, semanticInfo.Symbol) Dim node3 As QueryExpressionSyntax = CompilationUtils.FindBindingText(Of QueryExpressionSyntax)(compilation, "a.vb", 3) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node3, ExpressionSyntax)) Assert.Equal("QueryAble", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningReference, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) End Sub <Fact()> Public Sub OrderBy1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, 'BIND1:"x" x+1, 'BIND2:"x" x Descending 'BIND3:"x" Order By x Descending 'BIND4:"x" Select x 'BIND5:"x" Dim q2 As Object = From x In q Order By x 'BIND6:"Order By x" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("x", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) For i As Integer = 2 To 5 Dim node2to5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2to5, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Same(s1, semanticInfo.Symbol) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Next Dim node6 As OrderByClauseSyntax = CompilationUtils.FindBindingText(Of OrderByClauseSyntax)(compilation, "a.vb", 6) Dim symbolInfo = semanticModel.GetSymbolInfo(node6) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim orderBy = DirectCast(node1.Parent.Parent, OrderByClauseSyntax) For Each ordering In orderBy.Orderings symbolInfo = semanticModel.GetSymbolInfo(ordering) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(ordering) Assert.Null(commonSymbolInfo.Symbol) Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Next End Sub <Fact()> Public Sub OrderBy2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function OrderBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function ThenBy(x As Func(Of Integer, Integer)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From x In q Order By x, 'BIND1:"x" x+1 'BIND2:"x+1" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As OrderingSyntax = CompilationUtils.FindBindingText(Of OrderingSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel.GetSymbolInfo(node1) Assert.Equal("Function QueryAble.OrderBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node1) Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol) Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Dim node2 As OrderingSyntax = CompilationUtils.FindBindingText(Of OrderingSyntax)(compilation, "a.vb", 2) symbolInfo = semanticModel.GetSymbolInfo(node2) Assert.Equal("Function QueryAble.ThenBy(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node2) Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol) Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub Select2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q Select x = s, 'BIND1:"s" y = s, 'BIND2:"s" z = s, 'BIND3:"z = s" w = s, 'BIND4:"w" s, 'BIND5:"s" z = s 'BIND6:"z = s" Where z > 0 'BIND7:"z" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Assert.Same(s1, CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)).Symbol) Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3) Dim z1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("z", z1.Name) Assert.Equal("System.Int32", z1.Type.ToTestDisplayString()) Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol) Assert.Equal("w", w1.Name) Assert.Equal("System.Int32", w1.Type.ToTestDisplayString()) Dim node5 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5) Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol) Assert.Equal("s", s2.Name) Assert.Equal("System.Int32", s2.Type.ToTestDisplayString()) Assert.NotSame(s1, s2) Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6) Dim z2 = DirectCast(semanticModel.GetDeclaredSymbol(node6), RangeVariableSymbol) Assert.Equal("z", z2.Name) Assert.Equal("System.Int32", z2.Type.ToTestDisplayString()) Assert.NotSame(z1, z2) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) Assert.Same(z1, CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)).Symbol) End Sub <Fact()> Public Sub Let1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble Public Function [Select](x As Func(Of Integer, Integer)) As QueryAble Return Me End Function Public Function Where(x As Func(Of Integer, Boolean)) As QueryAble Return Me End Function End Class Module Program Sub Main(args As String()) Dim q As New QueryAble() Dim q1 As Object = From s In q Let x = s, 'BIND1:"s" y = x+1, 'BIND2:"x" x = s, 'BIND3:"x = s" w = x 'BIND4:"x" Dim q2 As Object = From s In q Let x = s 'BIND5:"Let x = s" q2 = From s In q, s2 In q Let x = s 'BIND6:"x = s" q2 = From s In q Join s2 In q On s Equals s2 Let x = s 'BIND7:"x = s" q2 = From s In q Select s+1 Let x = 1 'BIND8:"x = 1" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier)) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("System.Int32", x1.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim symbolInfo = semanticModel.GetSymbolInfo(node3) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason) Assert.Equal(1, symbolInfo.CandidateSymbols.Length) Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.CandidateSymbols(0).ToTestDisplayString()) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent), RangeVariableSymbol) Assert.Equal("w", w1.Name) Assert.Equal("System.Int32", w1.Type.ToTestDisplayString()) Assert.Same(w1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier)) Dim node5 As LetClauseSyntax = CompilationUtils.FindBindingText(Of LetClauseSyntax)(compilation, "a.vb", 5) symbolInfo = semanticModel.GetSymbolInfo(node5) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6) symbolInfo = semanticModel.GetSymbolInfo(node6) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim commonSymbolInfo As SymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node6) Assert.Null(commonSymbolInfo.Symbol) Assert.Equal(CandidateReason.None, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Dim node7 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 7) symbolInfo = semanticModel.GetSymbolInfo(node7) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node8 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 8) symbolInfo = semanticModel.GetSymbolInfo(node8) Assert.Equal("Function QueryAble.Select(x As System.Func(Of System.Int32, System.Int32)) As QueryAble", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(node8) Assert.Same(symbolInfo.Symbol, commonSymbolInfo.Symbol) Assert.Equal(symbolInfo.CandidateReason, commonSymbolInfo.CandidateReason) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub Let2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Program Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim q1 As Object = From s In qi Let x = s, 'BIND1:"x = s" y = x+1, 'BIND2:"y = x+1" x = s 'BIND3:"x = s" Dim q2 As Object = From s In qi Join s2 In qi On s Equals s2 'BIND7:"Join s2 In qi On s Equals s2" Let x = s, 'BIND4:"x = s" y = x+1, 'BIND5:"y = x+1" x = s 'BIND6:"x = s" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 1) Dim symbolInfo = semanticModel.GetSymbolInfo(node1) Assert.Equal("Function QueryAble(Of System.Int32).Select(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>)(x As System.Func(Of System.Int32, <anonymous type: Key s As System.Int32, Key x As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node2 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 2) symbolInfo = semanticModel.GetSymbolInfo(node2) Assert.Equal("Function QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)(x As System.Func(Of <anonymous type: Key s As System.Int32, Key x As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node3 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 3) symbolInfo = semanticModel.GetSymbolInfo(node3) Assert.Equal("Function QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>).Select(Of <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)(x As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As System.Int32>, Key y As System.Int32>, <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $861 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node4 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 4) symbolInfo = semanticModel.GetSymbolInfo(node4) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node5 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 5) symbolInfo = semanticModel.GetSymbolInfo(node5) Assert.Equal("Function QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>).Select(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)(x As System.Func(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6) symbolInfo = semanticModel.GetSymbolInfo(node6) Assert.Equal("Function QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>).Select(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)(x As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>, Key y As System.Int32>, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32, Key y As System.Int32, Key $1136 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node7 As SimpleJoinClauseSyntax = CompilationUtils.FindBindingText(Of SimpleJoinClauseSyntax)(compilation, "a.vb", 7) symbolInfo = semanticModel.GetSymbolInfo(node7) Assert.Equal("Function QueryAble(Of System.Int32).Join(Of System.Int32, System.Int32, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)(inner As QueryAble(Of System.Int32), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Int32, System.Int32), x As System.Func(Of System.Int32, System.Int32, <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key s2 As System.Int32, Key x As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact()> Public Sub BindingMemberAccessInsideQuery() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="BindingMemberAccessInsideQuery"> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(x As Integer) Dim xxx = From i In New Integer() {1, 2, x.ToString().Length } Select y = x 'BIND1:"x.ToString" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Public Overrides Function ToString() As String", symbolInfo.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub BindingMemberAccessInsideQuery2() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="BindingMemberAccessInsideQuery2"> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(x As String) Dim xxx = From i In New Integer() {1, 2, x.Length } Select y = x 'BIND1:"x.Length" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Public Overloads ReadOnly Property Length As Integer", symbolInfo.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub BindingMemberAccessInsideQuery3() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="BindingMemberAccessInsideQuery3"> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(x As Integer) Dim xxx = From i In New Integer() {1, 2 } Select y = x.ToString.Length 'BIND1:"x.ToString" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Public Overrides Function ToString() As String", symbolInfo.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub BindingMemberAccessInsideQuery4() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="BindingMemberAccessInsideQuery4"> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(x As String) Dim xxx = From i In New Integer() {1, 2 } Select y = x.Length.ToString() 'BIND1:"x.Length" End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node As MemberAccessExpressionSyntax = CompilationUtils.FindBindingText(Of MemberAccessExpressionSyntax)(compilation, "a.vb", 1) Dim symbolInfo = model.GetSymbolInfo(node) Assert.NotNull(symbolInfo.Symbol) Assert.Equal("Public Overloads ReadOnly Property Length As Integer", symbolInfo.Symbol.ToDisplayString()) End Sub <Fact()> Public Sub From1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New() End Sub Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Class QueryAble2(Of T) Public Function AsQueryable As QueryAble(Of T) Return New QueryAble(Of T)(1) End Function End Class Class QueryAble3(Of T) Public Function AsEnumerable As QueryAble(Of T) Return New QueryAble(Of T)(1) End Function End Class Class QueryAble4(Of T) Inherits QueryAble(Of T) End Class Class QueryAble5 Public Function Cast(Of T)() As QueryAble4(Of T) Return New QueryAble4(Of T)() End Function End Class Public Function AsEnumerable As QueryAble(Of T) Return New QueryAble(Of T)(1) End Function End Class Module Program Function Test(Of T)(x As T) As T return x End Function Sub Main(args As String()) Dim qi As New QueryAble(Of QueryAble(Of QueryAble(Of Integer)))(0) Dim q1 As Object = From s In qi From x In s, 'BIND1:"s" y In Test(x), 'BIND2:"x" x In s, 'BIND3:"x In s" w In x 'BIND4:"x" Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim q2 As Object = From s1 In qb, s2 In qs Select s1+s2 'BIND5:"s2" Dim q3 As Object = From s1 In qb, s2 In qs Select s1+s2 'BIND6:"s1+s2" Dim q4 As Object = From s1 In qb, s2 In qs Select s3 = s1+s2 'BIND7:"s3" Dim q5 As Object = From s1 In qb, s2 In qs Let s3 = 'BIND8:"s3" CInt(s1+s2) 'BIND9:"s1" Dim q6 As Object = From s In qi 'BIND10:"From s In qi" From x In s 'BIND11:"From x In s" Dim q6 As Object = From s In qi 'BIND12:"From s In qi" Dim q As Object q = From s In qi 'BIND13:"s In qi" q = From s In qi, s2 In s 'BIND14:"s2 In s" q = From s In qi, s2 In s, s5 As Integer In s2 'BIND15:"s5 As Integer In s2" Dim qii As New QueryAble(Of Integer)(0) q = From s3 As Integer In qii 'BIND16:"s3 As Integer In qii" q = From s4 As Long In qii 'BIND17:"s4 As Long In qii" q = From s In qi, s2 In s From s6 As Long In s2 'BIND18:"s6 As Long In s2" Dim qj As New QueryAble2(Of Integer)() q = From s7 In qj 'BIND19:"s7 In qj" Dim qjj As New QueryAble(Of QueryAble2(Of Integer))(0) q = From s in qjj, s8 In s 'BIND20:"s8 In s" q = From s9 As Integer In New QueryAble3(Of Integer)() 'BIND21:"s9 As Integer In New QueryAble3(Of Integer)()" q = From s10 As Long In qj 'BIND22:"s10 As Long In qj" q = From s in qjj, s11 As Integer In s 'BIND23:"s11 As Integer In s" q = From s in qjj, s12 As Long In s 'BIND24:"s12 As Long In s" q = From s In qi, s2 In s, s13 In s2 'BIND25:"s13 In s2" Select s13 q = From s In qi, s2 In s, s14 In s2 'BIND26:"s14 In s2" Let s15 = 0 q = From s16 In New QueryAble5() 'BIND27:"s16 In New QueryAble5()" Take 10 End Sub <System.Runtime.CompilerServices.Extension()> Public Function Take(Of T)(this As QueryAble(Of T), x as Integer) As QueryAble(Of T) Return this End Function End Module Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Class ExtensionAttribute Inherits Attribute End Class End Namespace ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticInfo As SemanticInfoSummary Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("QueryAble(Of QueryAble(Of System.Int32))", s1.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("QueryAble(Of System.Int32)", x1.Type.ToTestDisplayString()) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax).Identifier)) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim node3 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 3) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("QueryAble(Of System.Int32)", x1.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim w1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent), RangeVariableSymbol) Assert.Equal("w", w1.Name) Assert.Equal("System.Int32", w1.Type.ToTestDisplayString()) Assert.Same(w1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent, CollectionRangeVariableSyntax).Identifier)) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax)) Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s2", s2.Name) Assert.Equal("System.Int16", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node6 As ExpressionRangeVariableSyntax = CompilationUtils.FindBindingText(Of ExpressionRangeVariableSyntax)(compilation, "a.vb", 6) Assert.Null(semanticModel.GetDeclaredSymbol(node6)) Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim s3 = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.Equal("s3", s3.Name) Assert.Equal("System.Int16", s3.Type.ToTestDisplayString()) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) s3 = DirectCast(semanticModel.GetDeclaredSymbol(node8), RangeVariableSymbol) Assert.Equal("s3", s3.Name) Assert.Equal("System.Int32", s3.Type.ToTestDisplayString()) Dim node9 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 9) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node9, ExpressionSyntax)) Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) s2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s1", s2.Name) Assert.Equal("System.Byte", s2.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node10 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 10) Dim symbolInfo = semanticModel.GetSymbolInfo(node10) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node11 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 11) symbolInfo = semanticModel.GetSymbolInfo(node11) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node12 As FromClauseSyntax = CompilationUtils.FindBindingText(Of FromClauseSyntax)(compilation, "a.vb", 12) symbolInfo = semanticModel.GetSymbolInfo(node12) Assert.Equal("Function QueryAble(Of QueryAble(Of QueryAble(Of System.Int32))).Select(Of QueryAble(Of QueryAble(Of System.Int32)))(x As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of QueryAble(Of System.Int32)))) As QueryAble(Of QueryAble(Of QueryAble(Of System.Int32)))", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim collectionInfo As CollectionRangeVariableSymbolInfo Dim node13 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 13) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node13) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s As QueryAble(Of QueryAble(Of System.Int32))", semanticModel.GetDeclaredSymbol(node13).ToTestDisplayString()) If True Then Dim node14 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 14) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node14) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of QueryAble(Of QueryAble(Of System.Int32))).SelectMany(Of QueryAble(Of System.Int32), <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)(m As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of QueryAble(Of System.Int32))), x As System.Func(Of QueryAble(Of QueryAble(Of System.Int32)), QueryAble(Of System.Int32), <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s2 As QueryAble(Of System.Int32)", semanticModel.GetDeclaredSymbol(node14).ToTestDisplayString()) Dim node15 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 14) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node14) End If If True Then Dim node15 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 15) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node15) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s5 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s5 As System.Int32", semanticModel.GetDeclaredSymbol(node15).ToTestDisplayString()) End If If True Then Dim node16 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 16) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node16) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s3 As System.Int32", semanticModel.GetDeclaredSymbol(node16).ToTestDisplayString()) End If If True Then Dim node17 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 17) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node17) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) symbolInfo = collectionInfo.AsClauseConversion Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s4 As System.Int64", semanticModel.GetDeclaredSymbol(node17).ToTestDisplayString()) End If If True Then Dim node18 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 18) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node18) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) symbolInfo = collectionInfo.AsClauseConversion Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int64, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int64)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int64, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s6 As System.Int64>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s6 As System.Int64", semanticModel.GetDeclaredSymbol(node18).ToTestDisplayString()) End If If True Then Dim node19 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 19) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node19) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s7 As System.Int32", semanticModel.GetDeclaredSymbol(node19).ToTestDisplayString()) End If If True Then Dim node20 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 20) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node20) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int32)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s8 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s8 As System.Int32", semanticModel.GetDeclaredSymbol(node20).ToTestDisplayString()) End If If True Then Dim node21 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 21) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node21) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble3(Of System.Int32).AsEnumerable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s9 As System.Int32", semanticModel.GetDeclaredSymbol(node21).ToTestDisplayString()) End If If True Then Dim node22 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 22) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node22) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = collectionInfo.AsClauseConversion Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s10 As System.Int64", semanticModel.GetDeclaredSymbol(node22).ToTestDisplayString()) End If If True Then Dim node23 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 23) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node23) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int32)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int32, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s11 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s11 As System.Int32", semanticModel.GetDeclaredSymbol(node23).ToTestDisplayString()) End If If True Then Dim node24 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 24) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node24) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble2(Of System.Int32).AsQueryable() As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = collectionInfo.AsClauseConversion Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int64)(x As System.Func(Of System.Int32, System.Int64)) As QueryAble(Of System.Int64)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of QueryAble2(Of System.Int32)).SelectMany(Of System.Int64, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)(m As System.Func(Of QueryAble2(Of System.Int32), QueryAble(Of System.Int64)), x As System.Func(Of QueryAble2(Of System.Int32), System.Int64, <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)) As QueryAble(Of <anonymous type: Key s As QueryAble2(Of System.Int32), Key s12 As System.Int64>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s12 As System.Int64", semanticModel.GetDeclaredSymbol(node24).ToTestDisplayString()) End If If True Then Dim node25 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 25) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node25) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, System.Int32)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, System.Int32)) As QueryAble(Of System.Int32)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s13 As System.Int32", semanticModel.GetDeclaredSymbol(node25).ToTestDisplayString()) End If If True Then Dim node26 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 26) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node26) Assert.Equal(CandidateReason.None, collectionInfo.ToQueryableCollectionConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) symbolInfo = collectionInfo.SelectMany Assert.Equal("Function QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>).SelectMany(Of System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)(m As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, QueryAble(Of System.Int32)), x As System.Func(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32)>, System.Int32, <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)) As QueryAble(Of <anonymous type: Key s As QueryAble(Of QueryAble(Of System.Int32)), Key s2 As QueryAble(Of System.Int32), Key s14 As System.Int32, Key s15 As System.Int32>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal("s14 As System.Int32", semanticModel.GetDeclaredSymbol(node26).ToTestDisplayString()) End If If True Then Dim node27 As CollectionRangeVariableSyntax = CompilationUtils.FindBindingText(Of CollectionRangeVariableSyntax)(compilation, "a.vb", 27) collectionInfo = semanticModel.GetCollectionRangeVariableSymbolInfo(node27) symbolInfo = collectionInfo.ToQueryableCollectionConversion Assert.Equal("Function QueryAble5.Cast(Of System.Object)() As QueryAble4(Of System.Object)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Assert.Equal(CandidateReason.None, collectionInfo.AsClauseConversion.CandidateReason) Assert.Equal(CandidateReason.None, collectionInfo.SelectMany.CandidateReason) Assert.Equal("s16 As System.Object", semanticModel.GetDeclaredSymbol(node27).ToTestDisplayString()) End If End Sub <Fact()> Public Sub Join1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Program Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s In qi Join x In qb 'BIND1:"x" On s Equals x + 1 'BIND2:"x" Join y In qs 'BIND3:"y" Join x In qu 'BIND4:"x" On y + 1 Equals 'BIND5:"y" x 'BIND6:"x" On y Equals s Join w In ql On w Equals y And w Equals x 'BIND7:"x" End Sub End Module ]]></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 node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("System.Byte", x1.Type.ToTestDisplayString()) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Dim x2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("System.Byte", x2.Type.ToTestDisplayString()) Assert.Same(x1, x2) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("y", y1.Name) Assert.Equal("System.Int16", y1.Type.ToTestDisplayString()) Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol) Assert.Equal("x", x3.Name) Assert.Equal("System.UInt32", x3.Type.ToTestDisplayString()) Assert.NotSame(x1, x3) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax)) Assert.Same(y1, semanticInfo.Symbol) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Assert.Null(semanticInfo.Symbol) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) End Sub <Fact()> Public Sub GroupBy1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function Count(Of S)(x As Func(Of T, S)) As Integer Return 0 End Function Public Function Count() As Integer Return 0 End Function End Class Module Program Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s In qi Join x In qb On s Equals x Join y In qs Join x In qu On y Equals x On y Equals s Join w In ql On w Equals y And w Equals x Group i1 = s+1, 'BIND1:"s" x, 'BIND2:"x" x 'BIND3:"x" By k1 = y+1S, 'BIND4:"y" w, 'BIND5:"w" w 'BIND6:"w" Into Group, 'BIND7:"Group" k1= Count(), 'BIND8:"k1" k1= Count(), 'BIND9:"k1" r2 = Count(i1+ 'BIND10:"i1" x) 'BIND11:"x" Select w, 'BIND12:"w" k1 'BIND13:"k1" Dim q2 As Object = From s In qi Group By s Into Group 'BIND14:"Group By s Into Group" End Sub End Module ]]></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 node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node1, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s.Name) Assert.Equal("System.Int32", s.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim i1 = DirectCast(semanticModel.GetDeclaredSymbol(node1.Parent.Parent), RangeVariableSymbol) Assert.Equal("i1", i1.Name) Assert.Equal("System.Int32", i1.Type.ToTestDisplayString()) Assert.Same(i1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier)) Assert.Same(i1, semanticModel.GetDeclaredSymbol(DirectCast(DirectCast(node1.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier, VisualBasicSyntaxNode))) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Dim x1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("System.Byte", x1.Type.ToTestDisplayString()) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node2.Parent), RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("System.Byte", x2.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node2.Parent, ExpressionRangeVariableSyntax)) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Dim x3 = semanticModel.GetDeclaredSymbol(node3.Parent) Assert.NotSame(x1, x3) Assert.NotSame(x2, x3) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim y = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("y", y.Name) Assert.Equal("System.Int16", y.Type.ToTestDisplayString()) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim k1 = DirectCast(semanticModel.GetDeclaredSymbol(node4.Parent.Parent), RangeVariableSymbol) Assert.Equal("k1", k1.Name) Assert.Equal("System.Int16", k1.Type.ToTestDisplayString()) Assert.Same(k1, semanticModel.GetDeclaredSymbol(DirectCast(node4.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier)) Assert.Same(k1, semanticModel.GetDeclaredSymbol(DirectCast(DirectCast(node4.Parent.Parent, ExpressionRangeVariableSyntax).NameEquals.Identifier, VisualBasicSyntaxNode))) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax)) Dim w1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("w", w1.Name) Assert.Equal("System.Int64", w1.Type.ToTestDisplayString()) Dim w2 = DirectCast(semanticModel.GetDeclaredSymbol(node5.Parent), RangeVariableSymbol) Assert.Equal("w", w2.Name) Assert.Equal("System.Int64", w2.Type.ToTestDisplayString()) Assert.NotSame(w1, w2) symbolInfo = semanticModel.GetSymbolInfo(DirectCast(node5.Parent, ExpressionRangeVariableSyntax)) Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) Dim w3 = semanticModel.GetDeclaredSymbol(node6.Parent) Assert.NotSame(w1, w3) Assert.NotSame(w2, w3) Dim node7 As AggregationRangeVariableSyntax = CompilationUtils.FindBindingText(Of AggregationRangeVariableSyntax)(compilation, "a.vb", 7) Dim gr = DirectCast(semanticModel.GetDeclaredSymbol(node7), RangeVariableSymbol) Assert.Equal("Group", gr.Name) Assert.Equal("QueryAble(Of <anonymous type: Key i1 As System.Int32, Key x As System.Byte, Key $2080 As System.Byte>)", gr.Type.ToTestDisplayString()) Assert.Same(gr, semanticModel.GetDeclaredSymbol(DirectCast(node7, VisualBasicSyntaxNode))) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, node7.Aggregation) Assert.Same(gr.Type, semanticInfo.Type) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Same(gr.Type, semanticInfo.ConvertedType) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Null(semanticInfo.Symbol) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Null(semanticInfo.Alias) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Dim k2 = DirectCast(semanticModel.GetDeclaredSymbol(node8.Parent.Parent), RangeVariableSymbol) Assert.Equal("k1", k2.Name) Assert.Equal("System.Int32", k2.Type.ToTestDisplayString()) Assert.Same(k2, semanticModel.GetDeclaredSymbol(DirectCast(node8.Parent.Parent, AggregationRangeVariableSyntax))) Assert.Same(k2, semanticModel.GetDeclaredSymbol(DirectCast(node8, VisualBasicSyntaxNode))) Assert.Same(k2, semanticModel.GetDeclaredSymbol(node8)) Assert.NotSame(k1, k2) Dim node9 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 9) Dim k3 = semanticModel.GetDeclaredSymbol(node9) Assert.NotNull(k3) Assert.NotSame(k1, k3) Assert.NotSame(k2, k3) Dim node10 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 10) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node10, ExpressionSyntax)) Assert.Same(i1, semanticInfo.Symbol) Dim node11 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 11) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node11, ExpressionSyntax)) Assert.Same(x2, semanticInfo.Symbol) Dim node12 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 12) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node12, ExpressionSyntax)) Assert.Same(w2, semanticInfo.Symbol) Dim node13 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 13) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node13, ExpressionSyntax)) Assert.Same(k1, semanticInfo.Symbol) Dim node14 As GroupByClauseSyntax = CompilationUtils.FindBindingText(Of GroupByClauseSyntax)(compilation, "a.vb", 14) symbolInfo = semanticModel.GetSymbolInfo(node14) Assert.Equal("Function QueryAble(Of System.Int32).GroupBy(Of System.Int32, <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)(key As System.Func(Of System.Int32, System.Int32), into As System.Func(Of System.Int32, QueryAble(Of System.Int32), <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Int32)>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) End Sub <Fact()> <CompilerTrait(CompilerFeature.IOperation)> Public Sub GroupJoin1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Program Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim qu As New QueryAble(Of UInteger)(0) Dim ql As New QueryAble(Of Long)(0) Dim q1 As Object = From s In qi Group Join x In qb 'BIND1:"x" On s Equals x + 1 'BIND2:"x" Into x = Group 'BIND8:"x" Group Join y In qs 'BIND3:"y" Group Join x In qu 'BIND4:"x" On y + 1 Equals 'BIND5:"y" x 'BIND6:"x" Into Group On y Equals s Into y = Group Group Join w In ql On w Equals y And w Equals x 'BIND7:"x" Into Group Dim q2 As Object = From s In qi Group Join x In qb On s Equals x Into Group 'BIND9:"Group Join x In qb On s Equals x Into Group" End Sub End Module ]]></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 node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("System.Byte", x1.Type.ToTestDisplayString()) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node2, ExpressionSyntax)) Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.WideningNumeric, semanticInfo.ImplicitConversion.Kind) Dim x2 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("x", x2.Name) Assert.Equal("System.Byte", x2.Type.ToTestDisplayString()) Assert.Same(x1, x2) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Dim x4 = DirectCast(semanticModel.GetDeclaredSymbol(node8), RangeVariableSymbol) Assert.Equal("x", x4.Name) Assert.Equal("QueryAble(Of System.Byte)", x4.Type.ToTestDisplayString()) Assert.Same(x4, semanticModel.GetDeclaredSymbol(DirectCast(node8, VisualBasicSyntaxNode))) Assert.Same(x4, semanticModel.GetDeclaredSymbol(DirectCast(node8.Parent.Parent, AggregationRangeVariableSyntax))) Assert.Same(x4, semanticModel.GetDeclaredSymbol(node8.Parent.Parent)) Assert.NotSame(x1, x4) Assert.NotSame(x2, x4) Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim y1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("y", y1.Name) Assert.Equal("System.Int16", y1.Type.ToTestDisplayString()) Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node4), RangeVariableSymbol) Assert.Equal("x", x3.Name) Assert.Equal("System.UInt32", x3.Type.ToTestDisplayString()) Assert.NotSame(x1, x3) Assert.NotSame(x2, x3) Assert.NotSame(x4, x3) Dim node5 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 5) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node5, ExpressionSyntax)) Assert.Same(y1, semanticInfo.Symbol) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Assert.Same(x3, semanticInfo.Symbol) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)) Assert.Same(x4, semanticInfo.Symbol) Dim node9 As GroupJoinClauseSyntax = CompilationUtils.FindBindingText(Of GroupJoinClauseSyntax)(compilation, "a.vb", 9) Dim symbolInfo = semanticModel.GetSymbolInfo(node9) Assert.Equal("Function QueryAble(Of System.Int32).GroupJoin(Of System.Byte, System.Int32, <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)(inner As QueryAble(Of System.Byte), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Byte, System.Int32), x As System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key Group As QueryAble(Of System.Byte)>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node = tree.GetRoot().DescendantNodes().OfType(Of QueryExpressionSyntax)().First() compilation.VerifyOperationTree(node, expectedOperationTree:= <![CDATA[ ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'From s In q ... Into Group') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Children(5): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Children(1): IInvocationOperation ( Function QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>).GroupJoin(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32, <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)(inner As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), outerKey As System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, System.Int32), innerKey As System.Func(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32), x As System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)) As QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>), IsImplicit) (Syntax: 'Group Join ... o y = Group') Instance Receiver: IInvocationOperation ( Function QueryAble(Of System.Int32).GroupJoin(Of System.Byte, System.Int32, <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)(inner As QueryAble(Of System.Byte), outerKey As System.Func(Of System.Int32, System.Int32), innerKey As System.Func(Of System.Byte, System.Int32), x As System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)) As QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>), IsImplicit) (Syntax: 'Group Join ... o x = Group') Instance Receiver: ILocalReferenceOperation: qi (OperationKind.LocalReference, Type: QueryAble(Of System.Int32)) (Syntax: 'qi') Arguments(4): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'qb') ILocalReferenceOperation: qb (OperationKind.LocalReference, Type: QueryAble(Of System.Byte)) (Syntax: 'qb') 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: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, System.Int32), IsImplicit) (Syntax: 's') Target: IAnonymousFunctionOperation (Symbol: Function (s As System.Int32) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's') ReturnedValue: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + 1') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Byte, System.Int32), IsImplicit) (Syntax: 'x + 1') Target: IAnonymousFunctionOperation (Symbol: Function (x As System.Byte) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + 1') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Byte) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32, QueryAble(Of System.Byte), <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>), IsImplicit) (Syntax: 'Group Join ... o x = Group') Target: IAnonymousFunctionOperation (Symbol: Function (s As System.Int32, $VB$ItAnonymous As QueryAble(Of System.Byte)) As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... o x = Group') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's In qi') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group') Right: IParameterReferenceOperation: s (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 's') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.Byte), IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'Group Join ... o x = Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o x = Group') Right: IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'Group Join ... o x = Group') 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) Arguments(4): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') IInvocationOperation ( Function QueryAble(Of System.Int16).GroupJoin(Of System.UInt32, System.Int64, <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)(inner As QueryAble(Of System.UInt32), outerKey As System.Func(Of System.Int16, System.Int64), innerKey As System.Func(Of System.UInt32, System.Int64), x As System.Func(Of System.Int16, QueryAble(Of System.UInt32), <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) (OperationKind.Invocation, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: ILocalReferenceOperation: qs (OperationKind.LocalReference, Type: QueryAble(Of System.Int16)) (Syntax: 'qs') Arguments(4): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'qu') ILocalReferenceOperation: qu (OperationKind.LocalReference, Type: QueryAble(Of System.UInt32)) (Syntax: 'qu') 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: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y + 1') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int16, System.Int64), IsImplicit) (Syntax: 'y + 1') Target: IAnonymousFunctionOperation (Symbol: Function (y As System.Int16) As System.Int64) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y + 1') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y + 1') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y + 1') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'y + 1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y + 1') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int16) (Syntax: 'y') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.UInt32, System.Int64), IsImplicit) (Syntax: 'x') Target: IAnonymousFunctionOperation (Symbol: Function (x As System.UInt32) As System.Int64) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.UInt32) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int16, QueryAble(Of System.UInt32), <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... Into Group') Target: IAnonymousFunctionOperation (Symbol: Function (y As System.Int16, $VB$ItAnonymous As QueryAble(Of System.UInt32)) As <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... Into Group') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int16, IsImplicit) (Syntax: 'y In qs') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.y As System.Int16 (OperationKind.PropertyReference, Type: System.Int16, IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int16, IsImplicit) (Syntax: 'y') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... o y = Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.Group As QueryAble(Of System.UInt32) (OperationKind.PropertyReference, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of System.UInt32), IsImplicit) (Syntax: 'Group Join ... Into Group') 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) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'y') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, System.Int32), IsImplicit) (Syntax: 'y') Target: IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y') ReturnedValue: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 's') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'y') 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: innerKey) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 's') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, System.Int32), IsImplicit) (Syntax: 's') Target: IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 's') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 's') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 's') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>.y As System.Int16 (OperationKind.PropertyReference, Type: System.Int16) (Syntax: 'y') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>, IsImplicit) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>), IsImplicit) (Syntax: 'Group Join ... o y = Group') Target: IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, $VB$ItAnonymous As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)) As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Group Join ... o y = Group') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') Right: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... o y = Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsImplicit) (Syntax: 'Group Join ... o y = Group') Right: IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'Group Join ... o y = Group') 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) ILocalReferenceOperation: ql (OperationKind.LocalReference, Type: QueryAble(Of System.Int64)) (Syntax: 'ql') IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'w') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'w') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'w') ReturnedValue: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Children(2): IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsInvalid) (Syntax: 'y') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'w') IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsInvalid) (Syntax: 'x') Instance Receiver: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'w') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'w') IAnonymousFunctionOperation (Symbol: Function (w As System.Int64) As ?) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'y') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'y') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'y') ReturnedValue: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Children(2): IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int64, IsInvalid) (Syntax: 'w') IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int64, IsInvalid) (Syntax: 'w') IAnonymousFunctionOperation (Symbol: Function ($VB$It As <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, $VB$ItAnonymous As ?) As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Initializers(4): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 's In qi') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.s As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 's') Instance Receiver: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x =') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>.x As QueryAble(Of System.Byte) (OperationKind.PropertyReference, Type: QueryAble(Of System.Byte), IsImplicit) (Syntax: 'x') Instance Receiver: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.$VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)> (OperationKind.PropertyReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y =') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>.y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>) (OperationKind.PropertyReference, Type: QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), IsImplicit) (Syntax: 'y') Instance Receiver: IParameterReferenceOperation: $VB$It (OperationKind.ParameterReference, Type: <anonymous type: Key $VB$It As <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte)>, Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>)>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'From s In q ... Into Group') Left: IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>.Group As ? (OperationKind.PropertyReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: Key s As System.Int32, Key x As QueryAble(Of System.Byte), Key y As QueryAble(Of <anonymous type: Key y As System.Int16, Key Group As QueryAble(Of System.UInt32)>), Key Group As ?>, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') Right: IParameterReferenceOperation: $VB$ItAnonymous (OperationKind.ParameterReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Group Join ... Into Group') ]]>.Value) End Sub <Fact()> Public Sub Aggregate1() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count() As Integer End Function End Class Module Program Function Test(Of T)(x as T) As T return x End Function Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim q1 As Object = Aggregate s In qi, 'BIND1:"s" s In 'BIND2:"s" Test(qb) 'BIND6:"qb" Into x = 'BIND3:"x" Where(s > 0), 'BIND4:"s" x = Distinct 'BIND5:"x" Dim q2 As Object = Aggregate s1 In New QueryAble(Of QueryAble(Of Integer))(0), s2 In Test(s1) 'BIND7:"s1" Into x = Distinct q2 = DirectCast(qi.Select(Function(i) i), Object) 'BIND8:"qi.Select(Function(i) i)" q2 = Aggregate i In qi Into [Select](i) 'BIND9:"[Select](i)" Dim qii As New QueryAble(Of QueryAble(Of Integer))(0) q2 = Aggregate ii In qii Into [Select](From i In ii) 'BIND10:"ii" q2 = Aggregate i In qi Into Count(i) 'BIND11:"Count(i)" q2 = Aggregate i In qi Into Count() 'BIND12:"Aggregate i In qi Into Count()" q2 = Aggregate i In qi Into Count(), [Select](i) 'BIND13:"Aggregate i In qi Into Count(), [Select](i)" End Sub End Module ]]></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 node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim s1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode))) Assert.Same(s1, semanticModel.GetDeclaredSymbol(node1.Parent)) Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax))) Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), RangeVariableSymbol) Assert.Equal("s", s2.Name) Assert.Equal("System.Byte", s2.Type.ToTestDisplayString()) Assert.NotSame(s1, s2) Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("?", x1.Type.ToTestDisplayString()) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3, VisualBasicSyntaxNode))) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3.Parent.Parent, AggregationRangeVariableSyntax))) Assert.Same(x1, semanticModel.GetDeclaredSymbol(node3.Parent.Parent)) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s3.Name) Assert.Equal("System.Int32", s3.Type.ToTestDisplayString()) Assert.Same(s1, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("?", x1.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Assert.Equal("qb As QueryAble(Of System.Byte)", semanticInfo.Symbol.ToTestDisplayString()) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)) Assert.Equal("s1 As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) For i As Integer = 8 To 9 Dim node8 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", i) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax)) Assert.Equal("QueryAble(Of System.Int32)", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind) Assert.Equal("QueryAble(Of System.Int32)", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int32)(x As System.Func(Of System.Int32, System.Int32)) As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Null(semanticInfo.Alias) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Next Dim node9 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 9) Dim symbolInfo1 = semanticModel.GetSymbolInfo(node9) Assert.Equal("Function QueryAble(Of System.Int32).Select(Of System.Int32)(x As System.Func(Of System.Int32, System.Int32)) As QueryAble(Of System.Int32)", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Dim symbolInfo2 = semanticModel.GetSymbolInfo(DirectCast(node9, FunctionAggregationSyntax)) Assert.Equal(symbolInfo1.CandidateReason, symbolInfo2.CandidateReason) Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol) Assert.Equal(0, symbolInfo2.CandidateSymbols.Length) Dim commonSymbolInfo = DirectCast(semanticModel, SemanticModel).GetSymbolInfo(DirectCast(node9, SyntaxNode)) Assert.Equal(symbolInfo1.CandidateReason, commonSymbolInfo.CandidateReason) Assert.Same(symbolInfo1.Symbol, commonSymbolInfo.Symbol) Assert.Equal(0, commonSymbolInfo.CandidateSymbols.Length) Dim node10 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 10) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node10, ExpressionSyntax)) Assert.Equal("ii As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Dim node11 As ExpressionSyntax = CompilationUtils.FindBindingText(Of ExpressionSyntax)(compilation, "a.vb", 11) symbolInfo1 = semanticModel.GetSymbolInfo(node11) Assert.Null(symbolInfo1.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo1.CandidateReason) Assert.Equal(1, symbolInfo1.CandidateSymbols.Length) Assert.Equal("Function QueryAble(Of System.Int32).Count() As System.Int32", symbolInfo1.CandidateSymbols(0).ToTestDisplayString()) symbolInfo2 = semanticModel.GetSymbolInfo(DirectCast(node11, FunctionAggregationSyntax)) Assert.Equal(symbolInfo1.CandidateReason, symbolInfo2.CandidateReason) Assert.Same(symbolInfo1.Symbol, symbolInfo2.Symbol) Assert.True(symbolInfo1.CandidateSymbols.SequenceEqual(symbolInfo2.CandidateSymbols)) Dim node12 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 12) symbolInfo1 = semanticModel.GetSymbolInfo(node12) Assert.Null(symbolInfo1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Dim symbolInfo3 As AggregateClauseSymbolInfo = semanticModel.GetAggregateClauseSymbolInfo(node12) Assert.Null(symbolInfo3.Select1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select1.CandidateReason) Assert.Null(symbolInfo3.Select2.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason) Dim node13 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 13) symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node13) Assert.Null(symbolInfo3.Select1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select1.CandidateReason) Assert.Null(symbolInfo3.Select2.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason) End Sub <Fact()> Public Sub Aggregate2() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function Count() As Integer End Function End Class Module Program Function Test(Of T)(x as T) As T return x End Function Sub Main(args As String()) Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim q1 As Object = From y In qs Aggregate s In qi, 'BIND1:"s" s In qb 'BIND2:"s" Into x = 'BIND3:"x" Where(s > 'BIND4:"s" y), 'BIND6:"y" x = Distinct 'BIND5:"x" Select x 'BIND7:"x" Dim q2 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Aggregate s2 In Test(s1) 'BIND8:"s1" Into x = Distinct Dim q3 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Aggregate s2 In s1 Into Count() 'BIND9:"Aggregate s2 In s1 Into Count()" Dim q4 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Where True Aggregate s2 In s1 Into Count() 'BIND10:"Aggregate s2 In s1 Into Count()" Dim q5 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Aggregate s2 In s1 Into Count(), [Select](s2) 'BIND11:"Aggregate s2 In s1 Into Count(), [Select](s2)" Dim q6 As Object = From s1 In New QueryAble(Of QueryAble(Of Integer))(0) Where True Aggregate s2 In s1 Into Count(), [Select](s2) 'BIND12:"Aggregate s2 In s1 Into Count(), [Select](s2)" End Sub End Module ]]></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 node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim s1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), RangeVariableSymbol) Assert.Equal("s", s1.Name) Assert.Equal("System.Int32", s1.Type.ToTestDisplayString()) Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1, VisualBasicSyntaxNode))) Assert.Same(s1, semanticModel.GetDeclaredSymbol(node1.Parent)) Assert.Same(s1, semanticModel.GetDeclaredSymbol(DirectCast(node1.Parent, CollectionRangeVariableSyntax))) Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Dim s2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), RangeVariableSymbol) Assert.Equal("s", s2.Name) Assert.Equal("System.Byte", s2.Type.ToTestDisplayString()) Assert.NotSame(s1, s2) Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node3), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("?", x1.Type.ToTestDisplayString()) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3, VisualBasicSyntaxNode))) Assert.Same(x1, semanticModel.GetDeclaredSymbol(DirectCast(node3.Parent.Parent, AggregationRangeVariableSyntax))) Assert.Same(x1, semanticModel.GetDeclaredSymbol(node3.Parent.Parent)) Dim node4 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 4) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node4, ExpressionSyntax)) Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.Type.TypeKind) Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()) Assert.Equal(TypeKind.Structure, semanticInfo.ConvertedType.TypeKind) Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind) Dim s3 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("s", s3.Name) Assert.Equal("System.Int32", s3.Type.ToTestDisplayString()) Assert.Same(s1, s3) Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason) Assert.Equal(0, semanticInfo.CandidateSymbols.Length) Assert.Equal(0, semanticInfo.MemberGroup.Length) Assert.False(semanticInfo.ConstantValue.HasValue) Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node5), RangeVariableSymbol) Assert.Equal("x", x1.Name) Assert.Equal("?", x1.Type.ToTestDisplayString()) Assert.NotSame(x1, x2) Dim node6 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 6) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node6, ExpressionSyntax)) Dim y1 = DirectCast(semanticInfo.Symbol, RangeVariableSymbol) Assert.Equal("y", y1.Name) Assert.Equal("System.Int16", y1.Type.ToTestDisplayString()) Dim node7 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 7) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node7, ExpressionSyntax)) Assert.Same(x1, semanticInfo.Symbol) Dim node8 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 8) semanticInfo = CompilationUtils.GetSemanticInfoSummary(semanticModel, TryCast(node8, ExpressionSyntax)) Assert.Equal("s1 As QueryAble(Of System.Int32)", semanticInfo.Symbol.ToTestDisplayString()) Dim node9 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 9) Dim symbolInfo1 = semanticModel.GetSymbolInfo(node9) Assert.Null(symbolInfo1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Dim symbolInfo3 As AggregateClauseSymbolInfo symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node9) symbolInfo1 = symbolInfo3.Select1 Assert.Equal("Function QueryAble(Of QueryAble(Of System.Int32)).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)(x As System.Func(Of QueryAble(Of System.Int32), <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32>)", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Assert.Null(symbolInfo3.Select2.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason) Dim node10 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 10) symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node10) symbolInfo1 = symbolInfo3.Select1 Assert.Null(symbolInfo1.Symbol) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Assert.Null(symbolInfo3.Select2.Symbol) Assert.Equal(CandidateReason.None, symbolInfo3.Select2.CandidateReason) Dim node11 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 11) symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node11) symbolInfo1 = symbolInfo3.Select1 Assert.Equal("Function QueryAble(Of QueryAble(Of System.Int32)).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)(x As System.Func(Of QueryAble(Of System.Int32), <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>)", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) symbolInfo1 = symbolInfo3.Select2 Assert.Equal("Function QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>).Select(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)(x As System.Func(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key $VB$Group As QueryAble(Of System.Int32)>, <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)) As QueryAble(Of <anonymous type: Key s1 As QueryAble(Of System.Int32), Key Count As System.Int32, Key Select As QueryAble(Of System.Int32)>)", symbolInfo1.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) Dim node12 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 12) symbolInfo3 = semanticModel.GetAggregateClauseSymbolInfo(node12) symbolInfo1 = symbolInfo3.Select1 Assert.Null(symbolInfo1.Symbol) Assert.Equal(True, symbolInfo1.IsEmpty) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) symbolInfo1 = symbolInfo3.Select2 Assert.Null(symbolInfo1.Symbol) Assert.Equal(True, symbolInfo1.IsEmpty) Assert.Equal(CandidateReason.None, symbolInfo1.CandidateReason) Assert.Equal(0, symbolInfo1.CandidateSymbols.Length) End Sub <Fact()> Public Sub Aggregate3() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Option Strict Off Imports System Class QueryAble(Of T) 'Inherits Base 'Public Shadows [Select] As Byte Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Public Function SelectMany(Of S, R)(m As Func(Of T, QueryAble(Of S)), x As Func(Of T, S, R)) As QueryAble(Of R) System.Console.WriteLine("SelectMany {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function Where(x As Func(Of T, Boolean)) As QueryAble(Of T) System.Console.WriteLine("Where {0}", x) Return New QueryAble(Of T)(v + 1) End Function Public Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T) System.Console.WriteLine("TakeWhile {0}", x) Return New QueryAble(Of T)(v + 1) End Function Public Function SkipWhile(x As Func(Of T, Boolean)) As QueryAble(Of T) System.Console.WriteLine("SkipWhile {0}", x) Return New QueryAble(Of T)(v + 1) End Function Public Function OrderBy(x As Func(Of T, Integer)) As QueryAble(Of T) System.Console.WriteLine("OrderBy {0}", x) Return New QueryAble(Of T)(v + 1) End Function Public Function Distinct() As QueryAble(Of T) System.Console.WriteLine("Distinct") Return New QueryAble(Of T)(v + 1) End Function Public Function Skip(count As Integer) As QueryAble(Of T) System.Console.WriteLine("Skip {0}", count) Return New QueryAble(Of T)(v + 1) End Function Public Function Take(count As Integer) As QueryAble(Of T) System.Console.WriteLine("Take {0}", count) Return New QueryAble(Of T)(v + 1) End Function Public Function Join(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, I, R)) As QueryAble(Of R) System.Console.WriteLine("Join {0}", x) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, I, R)(key As Func(Of T, K), item As Func(Of T, I), into As Func(Of K, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy {0}", item) Return New QueryAble(Of R)(v + 1) End Function Public Function GroupBy(Of K, R)(key As Func(Of T, K), into As Func(Of K, QueryAble(Of T), R)) As QueryAble(Of R) System.Console.WriteLine("GroupBy ") Return New QueryAble(Of R)(v + 1) End Function Public Function GroupJoin(Of I, K, R)(inner As QueryAble(Of I), outerKey As Func(Of T, K), innerKey As Func(Of I, K), x As Func(Of T, QueryAble(Of I), R)) As QueryAble(Of R) System.Console.WriteLine("GroupJoin {0}", x) Return New QueryAble(Of R)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim qb As New QueryAble(Of Byte)(0) Dim qs As New QueryAble(Of Short)(0) Dim q0 As Object q0 = From i In qi, b In qb Aggregate s In qs Into Where(True) 'BIND1:"Aggregate s In qs Into Where(True)" System.Console.WriteLine("------") q0 = From i In qi, b In qb Aggregate s In qs Into Where(True), Distinct() 'BIND2:"Aggregate s In qs Into Where(True), Distinct()" q0 = From i In qi Join b In qb On b Equals i Aggregate s In qs Into Where(True) 'BIND3:"Aggregate s In qs Into Where(True)" System.Console.WriteLine("------") q0 = From i In qi Join b In qb On b Equals i Aggregate s In qs Into Where(True), Distinct() 'BIND4:"Aggregate s In qs Into Where(True), Distinct()" End Sub End Module ]]></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 aggregateInfo As AggregateClauseSymbolInfo For i As Integer = 0 To 1 Dim node1 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 1 + 2 * i) aggregateInfo = semanticModel.GetAggregateClauseSymbolInfo(node1) symbolInfo = aggregateInfo.Select1 Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = aggregateInfo.Select2 Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Dim node2 As AggregateClauseSyntax = CompilationUtils.FindBindingText(Of AggregateClauseSyntax)(compilation, "a.vb", 2 + 2 * i) aggregateInfo = semanticModel.GetAggregateClauseSymbolInfo(node2) symbolInfo = aggregateInfo.Select1 Assert.Null(symbolInfo.Symbol) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) symbolInfo = aggregateInfo.Select2 Assert.Equal("Function QueryAble(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key $VB$Group As QueryAble(Of System.Int16)>).Select(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)(x As System.Func(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key $VB$Group As QueryAble(Of System.Int16)>, <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)) As QueryAble(Of <anonymous type: Key i As System.Int32, Key b As System.Byte, Key Where As QueryAble(Of System.Int16), Key Distinct As QueryAble(Of System.Int16)>)", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason) Assert.Equal(0, symbolInfo.CandidateSymbols.Length) Next End Sub <WorkItem(546132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546132")> <Fact()> Public Sub SymbolInfoForFunctionAgtAregationSyntax() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports Microsoft.VisualBasic Module m1 <System.Runtime.CompilerServices.Extension()> Sub aggr4(Of T)(ByVal this As T) End Sub End Module Class cls1 Function [Select](Of S)(ByVal sel As Func(Of Integer, S)) As cls1 Return Nothing End Function Function GroupBy(Of K, R)(ByVal key As Func(Of Integer, K), ByVal result As Func(Of K, cls1, R)) As cls1 Return Nothing End Function Sub aggr4(Of T)(ByVal this As T) End Sub End Class Module AggrArgsInvalidmod Sub AggrArgsInvalid() Dim colm As New cls1 Dim q4 = From i In colm Group By vbCrLf Into aggr4(4) End Sub End Module ]]></file> </compilation>, references:={TestMetadata.Net40.SystemCore}) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_QueryOperatorNotFound, "aggr4").WithArguments("aggr4")) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel As SemanticModel = compilation.GetSemanticModel(tree) Dim node = DirectCast(tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("aggr4(4)", StringComparison.Ordinal)).Parent, FunctionAggregationSyntax) Dim info = semanticModel.GetSymbolInfo(node) Assert.NotNull(info) Assert.Null(info.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, info.CandidateReason) Assert.Equal(2, info.CandidateSymbols.Length) End Sub <WorkItem(542521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542521")> <Fact()> Public Sub AddressOfOperatorInQuery() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module CodCov004mod Function scen2() As Object Return Nothing End Function Sub CodCov004() Dim q = From a In AddressOf scen2 End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim diagnostics = semanticModel.GetDiagnostics() Assert.NotEmpty(diagnostics) End Sub <WorkItem(542823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542823")> <Fact()> Public Sub DefaultAggregateClauseInfo() Dim aggrClauseSymInfo = New AggregateClauseSymbolInfo() Assert.Null(aggrClauseSymInfo.Select1.Symbol) Assert.Equal(0, aggrClauseSymInfo.Select1.CandidateSymbols.Length) Assert.Null(aggrClauseSymInfo.Select2.Symbol) Assert.Equal(0, aggrClauseSymInfo.Select2.CandidateSymbols.Length) End Sub <WorkItem(543084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543084")> <Fact()> Public Sub MissingIdentifierNameSyntaxInIncompleteLetClause() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim numbers = New Integer() {4, 5} Dim q1 = From num In numbers Let n As End Sub End Module ]]></file> </compilation>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("n As", StringComparison.Ordinal)).Parent.Parent.DescendantNodes().OfType(Of IdentifierNameSyntax)().First() Dim info = semanticModel.GetTypeInfo(node) Assert.NotNull(info) Assert.Equal(TypeInfo.None, info) End Sub <WorkItem(542914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542914")> <Fact()> Public Sub Bug10356() Dim compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim numbers = New Integer() {4, 5} Dim d = From z In New Integer() {1, 2, 3} Let Group By End Sub End Module ]]></file> </compilation>, {SystemCoreRef}) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node = tree.GetCompilationUnitRoot().FindToken(tree.GetCompilationUnitRoot().ToString().IndexOf("By", StringComparison.Ordinal)).Parent.Parent.DescendantNodes().OfType(Of IdentifierNameSyntax)().First() Dim containingSymbol = DirectCast(semanticModel, SemanticModel).GetEnclosingSymbol(node.SpanStart) Assert.Equal("Function (z As System.Int32) As <anonymous type: Key z As System.Int32, Key Group As ?>", DirectCast(containingSymbol, Symbol).ToTestDisplayString()) End Sub <WorkItem(543161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543161")> <Fact()> Public Sub InaccessibleQueryMethodOnCollectionType() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Imports System Class QueryAble(Of T) Public ReadOnly v As Integer Sub New(v As Integer) Me.v = v End Sub Public Function [Select](Of S)(x As Func(Of T, S)) As QueryAble(Of S) System.Console.WriteLine("Select {0}", x) Return New QueryAble(Of S)(v + 1) End Function Private Function TakeWhile(x As Func(Of T, Boolean)) As QueryAble(Of T) System.Console.WriteLine("TakeWhile {0}", x) Return New QueryAble(Of T)(v + 1) End Function Private Function TakeWhile(x As Func(Of T, Integer)) As QueryAble(Of T) System.Console.WriteLine("TakeWhile {0}", x) Return New QueryAble(Of T)(v + 1) End Function End Class Module Module1 Sub Main() Dim qi As New QueryAble(Of Integer)(0) Dim q0 = From s1 In qi Take While False'BIND:"Take While False" End Sub End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of PartitionWhileClauseSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Type) Assert.Null(semanticSummary.ConvertedType) Assert.Equal(ConversionKind.DelegateRelaxationLevelNone, semanticSummary.ImplicitConversion.Kind) Assert.Null(semanticSummary.Symbol) Assert.Equal(CandidateReason.Inaccessible, semanticSummary.CandidateReason) Assert.Equal(1, semanticSummary.CandidateSymbols.Length) Assert.Equal("Function QueryAble(Of System.Int32).TakeWhile(x As System.Func(Of System.Int32, System.Boolean)) As QueryAble(Of System.Int32)", semanticSummary.CandidateSymbols(0).ToTestDisplayString()) Assert.Null(semanticSummary.Alias) Assert.Equal(0, semanticSummary.MemberGroup.Length) Assert.False(semanticSummary.ConstantValue.HasValue) End Sub <WorkItem(546165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546165")> <Fact()> Public Sub QueryInsideEnumMemberDecl() Dim compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ Module Test Enum Enum1 x = (From i In New Integer() {4, 5} Where True Select 1).First 'BIND:"True" End Enum End Module ]]></file> </compilation>) Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of LiteralExpressionSyntax)(compilation, "a.vb") Assert.Null(semanticSummary.Symbol) Assert.True(semanticSummary.ConstantValue.HasValue) End Sub End Class End Namespace
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncIteratorInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Additional information for rewriting an async-iterator. /// </summary> internal sealed class AsyncIteratorInfo { // This `ManualResetValueTaskSourceCore<bool>` struct implements the `IValueTaskSource` logic internal FieldSymbol PromiseOfValueOrEndField { get; } // This `CancellationTokenSource` field helps combine two cancellation tokens internal FieldSymbol CombinedTokensField { get; } // Stores the current/yielded value internal FieldSymbol CurrentField { get; } // Whether the state machine is in dispose mode internal FieldSymbol DisposeModeField { get; } // Method to fulfill the promise with a result: `void ManualResetValueTaskSourceCore<T>.SetResult(T result)` internal MethodSymbol SetResultMethod { get; } // Method to fulfill the promise with an exception: `void ManualResetValueTaskSourceCore<T>.SetException(Exception error)` internal MethodSymbol SetExceptionMethod { get; } public AsyncIteratorInfo(FieldSymbol promiseOfValueOrEndField, FieldSymbol combinedTokensField, FieldSymbol currentField, FieldSymbol disposeModeField, MethodSymbol setResultMethod, MethodSymbol setExceptionMethod) { PromiseOfValueOrEndField = promiseOfValueOrEndField; CombinedTokensField = combinedTokensField; CurrentField = currentField; DisposeModeField = disposeModeField; SetResultMethod = setResultMethod; SetExceptionMethod = setExceptionMethod; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Additional information for rewriting an async-iterator. /// </summary> internal sealed class AsyncIteratorInfo { // This `ManualResetValueTaskSourceCore<bool>` struct implements the `IValueTaskSource` logic internal FieldSymbol PromiseOfValueOrEndField { get; } // This `CancellationTokenSource` field helps combine two cancellation tokens internal FieldSymbol CombinedTokensField { get; } // Stores the current/yielded value internal FieldSymbol CurrentField { get; } // Whether the state machine is in dispose mode internal FieldSymbol DisposeModeField { get; } // Method to fulfill the promise with a result: `void ManualResetValueTaskSourceCore<T>.SetResult(T result)` internal MethodSymbol SetResultMethod { get; } // Method to fulfill the promise with an exception: `void ManualResetValueTaskSourceCore<T>.SetException(Exception error)` internal MethodSymbol SetExceptionMethod { get; } public AsyncIteratorInfo(FieldSymbol promiseOfValueOrEndField, FieldSymbol combinedTokensField, FieldSymbol currentField, FieldSymbol disposeModeField, MethodSymbol setResultMethod, MethodSymbol setExceptionMethod) { PromiseOfValueOrEndField = promiseOfValueOrEndField; CombinedTokensField = combinedTokensField; CurrentField = currentField; DisposeModeField = disposeModeField; SetResultMethod = setResultMethod; SetExceptionMethod = setExceptionMethod; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Tools/BuildBoss/ProjectReferenceEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal struct ProjectReferenceEntry { internal string FileName { get; } internal Guid? Project { get; } internal ProjectKey ProjectKey => new ProjectKey(FileName); internal ProjectReferenceEntry(string fileName, Guid? project) { FileName = fileName; Project = project; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BuildBoss { internal struct ProjectReferenceEntry { internal string FileName { get; } internal Guid? Project { get; } internal ProjectKey ProjectKey => new ProjectKey(FileName); internal ProjectReferenceEntry(string fileName, Guid? project) { FileName = fileName; Project = project; } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/VisualStudio/Core/Impl/CodeModel/ExternalElements/ExternalCodeNamespace.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeNamespace))] public sealed class ExternalCodeNamespace : AbstractExternalCodeElement, EnvDTE.CodeNamespace, EnvDTE.CodeElement { internal static EnvDTE.CodeNamespace Create(CodeModelState state, ProjectId projectId, INamespaceSymbol namespaceSymbol) { var newElement = new ExternalCodeNamespace(state, projectId, namespaceSymbol); return (EnvDTE.CodeNamespace)ComAggregate.CreateAggregatedObject(newElement); } private ExternalCodeNamespace(CodeModelState state, ProjectId projectId, INamespaceSymbol namespaceSymbol) : base(state, projectId, namespaceSymbol) { } private INamespaceSymbol NamespaceSymbol { get { return (INamespaceSymbol)LookupSymbol(); } } protected override string GetDocComment() => string.Empty; public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementNamespace; } } public EnvDTE.CodeElements Members { get { return ExternalNamespaceCollection.Create(State, this, ProjectId, NamespaceSymbol); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeNamespace AddNamespace(string name, object position) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public void Remove(object element) => throw Exceptions.ThrowEFail(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeNamespace))] public sealed class ExternalCodeNamespace : AbstractExternalCodeElement, EnvDTE.CodeNamespace, EnvDTE.CodeElement { internal static EnvDTE.CodeNamespace Create(CodeModelState state, ProjectId projectId, INamespaceSymbol namespaceSymbol) { var newElement = new ExternalCodeNamespace(state, projectId, namespaceSymbol); return (EnvDTE.CodeNamespace)ComAggregate.CreateAggregatedObject(newElement); } private ExternalCodeNamespace(CodeModelState state, ProjectId projectId, INamespaceSymbol namespaceSymbol) : base(state, projectId, namespaceSymbol) { } private INamespaceSymbol NamespaceSymbol { get { return (INamespaceSymbol)LookupSymbol(); } } protected override string GetDocComment() => string.Empty; public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementNamespace; } } public EnvDTE.CodeElements Members { get { return ExternalNamespaceCollection.Create(State, this, ProjectId, NamespaceSymbol); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeNamespace AddNamespace(string name, object position) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public void Remove(object element) => throw Exceptions.ThrowEFail(); } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/Features/CSharp/Portable/InvertConditional/CSharpInvertConditionalCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.InvertConditional; namespace Microsoft.CodeAnalysis.CSharp.InvertConditional { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InvertConditional), Shared] internal class CSharpInvertConditionalCodeRefactoringProvider : AbstractInvertConditionalCodeRefactoringProvider<ConditionalExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpInvertConditionalCodeRefactoringProvider() { } // Don't offer if the conditional is missing the colon and the conditional is too incomplete. protected override bool ShouldOffer(ConditionalExpressionSyntax conditional) => !conditional.ColonToken.IsMissing; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.InvertConditional; namespace Microsoft.CodeAnalysis.CSharp.InvertConditional { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InvertConditional), Shared] internal class CSharpInvertConditionalCodeRefactoringProvider : AbstractInvertConditionalCodeRefactoringProvider<ConditionalExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpInvertConditionalCodeRefactoringProvider() { } // Don't offer if the conditional is missing the colon and the conditional is too incomplete. protected override bool ShouldOffer(ConditionalExpressionSyntax conditional) => !conditional.ColonToken.IsMissing; } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/TestUtilities/Threading/ConditionalWpfFactAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Roslyn.Test.Utilities { public class ConditionalWpfFactAttribute : WpfFactAttribute { public ConditionalWpfFactAttribute(Type skipCondition) { var condition = Activator.CreateInstance(skipCondition) as ExecutionCondition; if (condition.ShouldSkip) { Skip = condition.SkipReason; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Roslyn.Test.Utilities { public class ConditionalWpfFactAttribute : WpfFactAttribute { public ConditionalWpfFactAttribute(Type skipCondition) { var condition = Activator.CreateInstance(skipCondition) as ExecutionCondition; if (condition.ShouldSkip) { Skip = condition.SkipReason; } } } }
-1
dotnet/roslyn
55,696
Have inheritance-margin hold onto data that does *not* point back at Solution instances.
Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
CyrusNajmabadi
2021-08-18T16:22:09Z
2021-08-20T04:50:45Z
16efcb29a0cb8be060ab3bfd9e60c9192c6604bf
6ce4dc34664b63672aeac58683ed9c9e73fa2102
Have inheritance-margin hold onto data that does *not* point back at Solution instances.. Fixes [AB#1371724](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1371724)
./src/EditorFeatures/VisualBasicTest/SignatureHelp/GenericNameSignatureHelpProviderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class GenericNameSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(GenericNameSignatureHelpProvider) End Function #Region "Declaring generic type objects" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith1ParameterUnterminated() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith1ParameterTerminated() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1XmlDoc() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="C"/></typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamS. Also see C", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2XmlDoc() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="C"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamT. Also see C", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(827031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827031")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1XmlDocReferencingTypeParams() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="T"/></typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="S"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamS. Also see T", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(827031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827031")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2XmlDocReferencingTypeParams() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="T"/></typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="S"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamT. Also see S", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Constraints on generic types" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsStructure() As Task Dim markup = <a><![CDATA[ Class G(Of S As Structure, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As Structure, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsClass() As Task Dim markup = <a><![CDATA[ Class G(Of S As Class, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As Class, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsNew() As Task Dim markup = <a><![CDATA[ Class G(Of S As New, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As New, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBase() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Class G(Of S As SomeBaseClass, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of S), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of S), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of Integer), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of Integer), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithGenericNested() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of SomeBaseClass(Of S)), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of SomeBaseClass(Of S)), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() As Task Dim markup = <a><![CDATA[ Class G(Of S As T, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As T, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsMixed1() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New}) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})", "SummaryG", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsMixed2() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New}) End Class Class C Sub Goo() Dim q As [|G(Of Bar, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})", "SummaryG", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Generic member invocation" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith1ParameterUnterminated() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of T)(arg As T) As T End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith1ParameterTerminated() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of T)(arg As T) As T End Function Sub Bar() [|Goo(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn1() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of S, T)(arg As T) As T End Function Sub Bar() [|Goo(Of Integer, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn1XmlDoc() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", "GooSummary", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn2XmlDoc() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of Integer, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", "GooSummary", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(544124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544124")> <WorkItem(544123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544123")> <WorkItem(684631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684631")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCallingGenericExtensionMethod() As Task Dim markup = <a><![CDATA[ Imports System Class D End Class Module ExtnMethods <Runtime.CompilerServices.Extension()> Function Goo(Of S, T)(ByRef dClass As D, objS as S, objT As T) As S End Function End Module Class C Sub Bar() Dim obj As D = Nothing obj.[|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem($"<{VBFeaturesResources.Extension}> D.Goo(Of S, T)(objS As S, objT As T) As S", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Constraints on generic methods" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodTypeWithConstraintsMixed1() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T", "GooSummary", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWithConstraintsMixed2() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T End Function Sub Bar() [|Goo(Of Bas, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T", "GooSummary", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Trigger tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerSpace() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerComma() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer,$$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestTriggerCharacters() Dim expectedTriggerCharacters() As Char = {","c, " "c} Dim unexpectedTriggerCharacters() As Char = {"["c, "<"c, "("c} VerifyTriggerCharacters(expectedTriggerCharacters, unexpectedTriggerCharacters) End Sub #End Region #Region "EditorBrowsable tests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub Goo(Of T)(x As T) End Sub <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(Of T, U)(x As T, y As U) End Sub End Class ]]></Text>.Value Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)() expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)() expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C.Goo(Of T, U)(x As T, y As U)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class GenericNameSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(GenericNameSignatureHelpProvider) End Function #Region "Declaring generic type objects" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith1ParameterUnterminated() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith1ParameterTerminated() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1XmlDoc() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="C"/></typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamS. Also see C", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2XmlDoc() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="C"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamT. Also see C", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(827031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827031")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn1XmlDocReferencingTypeParams() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="T"/></typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="S"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamS. Also see T", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(827031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827031")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWith2ParametersOn2XmlDocReferencingTypeParams() As Task Dim markup = <a><![CDATA[ ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS. Also see <see cref="T"/></typeparam> ''' <typeparam name="T">ParamT. Also see <see cref="S"/></typeparam> Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", "SummaryG", "ParamT. Also see S", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Constraints on generic types" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsStructure() As Task Dim markup = <a><![CDATA[ Class G(Of S As Structure, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As Structure, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsClass() As Task Dim markup = <a><![CDATA[ Class G(Of S As Class, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As Class, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsNew() As Task Dim markup = <a><![CDATA[ Class G(Of S As New, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As New, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBase() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Class G(Of S As SomeBaseClass, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of S), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of S), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of Integer), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of Integer), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsBaseGenericWithGenericNested() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass(Of X) End Class Class G(Of S As SomeBaseClass(Of SomeBaseClass(Of S)), T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As SomeBaseClass(Of SomeBaseClass(Of S)), T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() As Task Dim markup = <a><![CDATA[ Class G(Of S As T, T) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As T, T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsMixed1() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New}) End Class Class C Sub Goo() Dim q As [|G(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})", "SummaryG", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestDeclaringGenericTypeWithConstraintsMixed2() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface ''' <summary> ''' SummaryG ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Class G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New}) End Class Class C Sub Goo() Dim q As [|G(Of Bar, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})", "SummaryG", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Generic member invocation" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith1ParameterUnterminated() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of T)(arg As T) As T End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith1ParameterTerminated() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of T)(arg As T) As T End Function Sub Bar() [|Goo(Of $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn1() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Function Goo(Of S, T)(arg As T) As T End Function Sub Bar() [|Goo(Of Integer, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As T", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn1XmlDoc() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", "GooSummary", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWith2ParametersOn2XmlDoc() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S, T)(arg As T) As S End Function Sub Bar() [|Goo(Of Integer, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S, T)(arg As T) As S", "GooSummary", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(544124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544124")> <WorkItem(544123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544123")> <WorkItem(684631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684631")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCallingGenericExtensionMethod() As Task Dim markup = <a><![CDATA[ Imports System Class D End Class Module ExtnMethods <Runtime.CompilerServices.Extension()> Function Goo(Of S, T)(ByRef dClass As D, objS as S, objT As T) As S End Function End Module Class C Sub Bar() Dim obj As D = Nothing obj.[|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem($"<{VBFeaturesResources.Extension}> D.Goo(Of S, T)(objS As S, objT As T) As S", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Constraints on generic methods" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodTypeWithConstraintsMixed1() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T End Function Sub Bar() [|Goo(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T", "GooSummary", "ParamS", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvokingGenericMethodWithConstraintsMixed2() As Task Dim markup = <a><![CDATA[ Class SomeBaseClass End Class Interface IGoo End Interface Class C ''' <summary> ''' GooSummary ''' </summary> ''' <typeparam name="S">ParamS</typeparam> ''' <typeparam name="T">ParamT</typeparam> Function Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T End Function Sub Bar() [|Goo(Of Bas, $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of S As {SomeBaseClass, New}, T As {Class, S, IGoo, New})(objS As S, objT As T) As T", "GooSummary", "ParamT", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Trigger tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerSpace() As Task Dim markup = <a><![CDATA[ Class G(Of T) End Class Class C Sub Goo() Dim q As [|G(Of $$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerComma() As Task Dim markup = <a><![CDATA[ Class G(Of S, T) End Class Class C Sub Goo() Dim q As [|G(Of Integer,$$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("G(Of S, T)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestTriggerCharacters() Dim expectedTriggerCharacters() As Char = {","c, " "c} Dim unexpectedTriggerCharacters() As Char = {"["c, "<"c, "("c} VerifyTriggerCharacters(expectedTriggerCharacters, unexpectedTriggerCharacters) End Sub #End Region #Region "EditorBrowsable tests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub Goo(Of T)(x As T) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericMethod_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim cc As C cc.Goo(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub Goo(Of T)(x As T) End Sub <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub Goo(Of T, U)(x As T, y As U) End Sub End Class ]]></Text>.Value Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)() expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)() expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C.Goo(Of T)(x As T)", String.Empty, String.Empty, currentParameterIndex:=0)) expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C.Goo(Of T, U)(x As T, y As U)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_GenericType_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub M() Dim c As C(Of $$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Class C(Of T) End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(Of T)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function #End Region End Class End Namespace
-1