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,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/EditorFeatures/TestUtilities/NavigateTo/AbstractNavigateToTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.PatternMatching;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo
{
[UseExportProvider]
public abstract class AbstractNavigateToTests
{
protected static readonly TestComposition DefaultComposition = EditorTestCompositions.EditorFeatures;
protected static readonly TestComposition FirstVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsVisibleDocumentTrackingService.Factory));
protected static readonly TestComposition FirstActiveAndVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsActiveAndVisibleDocumentTrackingService.Factory));
protected INavigateToItemProvider _provider;
protected NavigateToTestAggregator _aggregator;
internal static readonly PatternMatch s_emptyExactPatternMatch = new PatternMatch(PatternMatchKind.Exact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch = new PatternMatch(PatternMatchKind.Prefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch = new PatternMatch(PatternMatchKind.Substring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseExact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch = new PatternMatch(PatternMatchKind.Fuzzy, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Exact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Prefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Substring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseExact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Fuzzy, true, false, ImmutableArray<Span>.Empty);
protected abstract TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider);
protected abstract string Language { get; }
public enum Composition
{
Default,
FirstVisible,
FirstActiveAndVisible,
}
protected async Task TestAsync(TestHost testHost, Composition composition, string content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
protected async Task TestAsync(TestHost testHost, Composition composition, XElement content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
private async Task TestAsync(
string content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
protected async Task TestAsync(
XElement content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
private protected TestWorkspace CreateWorkspace(
XElement workspaceElement,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = TestWorkspace.Create(workspaceElement, exportProvider: exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
private protected TestWorkspace CreateWorkspace(
string content,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = CreateWorkspace(content, exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
internal void InitializeWorkspace(TestWorkspace workspace)
{
_provider = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService<IThreadingContext>());
_aggregator = new NavigateToTestAggregator(_provider);
}
protected static void VerifyNavigateToResultItems(
List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items)
{
expecteditems = expecteditems.OrderBy(i => i.Name).ToList();
items = items.OrderBy(i => i.Name).ToList();
Assert.Equal(expecteditems.Count(), items.Count());
for (var i = 0; i < expecteditems.Count; i++)
{
var expectedItem = expecteditems[i];
var actualItem = items.ElementAt(i);
Assert.Equal(expectedItem.Name, actualItem.Name);
Assert.True(expectedItem.PatternMatch.Kind == actualItem.PatternMatch.Kind, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.Kind, actualItem.PatternMatch.Kind));
Assert.True(expectedItem.PatternMatch.IsCaseSensitive == actualItem.PatternMatch.IsCaseSensitive, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.IsCaseSensitive, actualItem.PatternMatch.IsCaseSensitive));
Assert.Equal(expectedItem.Language, actualItem.Language);
Assert.Equal(expectedItem.Kind, actualItem.Kind);
if (!string.IsNullOrEmpty(expectedItem.SecondarySort))
{
Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal);
}
}
}
internal void VerifyNavigateToResultItem(
NavigateToItem result, string name, string displayMarkup,
PatternMatchKind matchKind, string navigateToItemKind,
Glyph glyph, string additionalInfo = null)
{
// Verify symbol information
Assert.Equal(name, result.Name);
Assert.Equal(matchKind, result.PatternMatch.Kind);
Assert.Equal(this.Language, result.Language);
Assert.Equal(navigateToItemKind, result.Kind);
MarkupTestFile.GetSpans(displayMarkup, out displayMarkup,
out ImmutableArray<TextSpan> expectedDisplayNameSpans);
var itemDisplay = (NavigateToItemDisplay)result.DisplayFactory.CreateItemDisplay(result);
Assert.Equal(itemDisplay.GlyphMoniker, glyph.GetImageMoniker());
Assert.Equal(displayMarkup, itemDisplay.Name);
Assert.Equal<TextSpan>(
expectedDisplayNameSpans,
itemDisplay.GetNameMatchRuns("").Select(s => s.ToTextSpan()).ToImmutableArray());
if (additionalInfo != null)
{
Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation);
}
}
internal static BitmapSource CreateIconBitmapSource()
{
var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16;
return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride);
}
// For ordering of NavigateToItems, see
// http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx
protected static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b)
=> ComparerWithState.CompareTo(a, b, s_comparisonComponents);
private static readonly ImmutableArray<Func<NavigateToItem, IComparable>> s_comparisonComponents =
ImmutableArray.Create<Func<NavigateToItem, IComparable>>(
item => (int)item.PatternMatch.Kind,
item => item.Name,
item => item.Kind,
item => item.SecondarySort);
private class FirstDocIsVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> null;
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
private class FirstDocIsActiveAndVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsActiveAndVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> _workspace.CurrentSolution.Projects.First().DocumentIds.First();
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsActiveAndVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Editor.Wpf;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.PatternMatching;
using Roslyn.Test.EditorUtilities.NavigateTo;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigateTo
{
[UseExportProvider]
public abstract class AbstractNavigateToTests
{
protected static readonly TestComposition DefaultComposition = EditorTestCompositions.EditorFeatures;
protected static readonly TestComposition FirstVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsVisibleDocumentTrackingService.Factory));
protected static readonly TestComposition FirstActiveAndVisibleComposition = EditorTestCompositions.EditorFeatures.AddParts(typeof(FirstDocIsActiveAndVisibleDocumentTrackingService.Factory));
protected INavigateToItemProvider _provider;
protected NavigateToTestAggregator _aggregator;
internal static readonly PatternMatch s_emptyExactPatternMatch = new PatternMatch(PatternMatchKind.Exact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch = new PatternMatch(PatternMatchKind.Prefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch = new PatternMatch(PatternMatchKind.Substring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseExact, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch = new PatternMatch(PatternMatchKind.Fuzzy, true, true, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Exact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Prefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptySubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Substring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseExactPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseExact, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCasePrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCasePrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousPrefixPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousPrefix, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyCamelCaseNonContiguousSubstringPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.CamelCaseNonContiguousSubstring, true, false, ImmutableArray<Span>.Empty);
internal static readonly PatternMatch s_emptyFuzzyPatternMatch_NotCaseSensitive = new PatternMatch(PatternMatchKind.Fuzzy, true, false, ImmutableArray<Span>.Empty);
protected abstract TestWorkspace CreateWorkspace(string content, ExportProvider exportProvider);
protected abstract string Language { get; }
public enum Composition
{
Default,
FirstVisible,
FirstActiveAndVisible,
}
protected async Task TestAsync(TestHost testHost, Composition composition, string content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
protected async Task TestAsync(TestHost testHost, Composition composition, XElement content, Func<TestWorkspace, Task> body)
{
var testComposition = composition switch
{
Composition.Default => DefaultComposition,
Composition.FirstVisible => FirstVisibleComposition,
Composition.FirstActiveAndVisible => FirstActiveAndVisibleComposition,
_ => throw ExceptionUtilities.UnexpectedValue(composition),
};
await TestAsync(content, body, testHost, testComposition);
}
private async Task TestAsync(
string content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
protected async Task TestAsync(
XElement content, Func<TestWorkspace, Task> body, TestHost testHost,
TestComposition composition)
{
using var workspace = CreateWorkspace(content, testHost, composition);
await body(workspace);
}
private protected TestWorkspace CreateWorkspace(
XElement workspaceElement,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = TestWorkspace.Create(workspaceElement, exportProvider: exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
private protected TestWorkspace CreateWorkspace(
string content,
TestHost testHost,
TestComposition composition)
{
var exportProvider = composition.WithTestHostParts(testHost).ExportProviderFactory.CreateExportProvider();
var workspace = CreateWorkspace(content, exportProvider);
InitializeWorkspace(workspace);
return workspace;
}
internal void InitializeWorkspace(TestWorkspace workspace)
{
_provider = new NavigateToItemProvider(workspace, AsynchronousOperationListenerProvider.NullListener, workspace.GetService<IThreadingContext>());
_aggregator = new NavigateToTestAggregator(_provider);
}
protected static void VerifyNavigateToResultItems(
List<NavigateToItem> expecteditems, IEnumerable<NavigateToItem> items)
{
expecteditems = expecteditems.OrderBy(i => i.Name).ToList();
items = items.OrderBy(i => i.Name).ToList();
Assert.Equal(expecteditems.Count(), items.Count());
for (var i = 0; i < expecteditems.Count; i++)
{
var expectedItem = expecteditems[i];
var actualItem = items.ElementAt(i);
Assert.Equal(expectedItem.Name, actualItem.Name);
Assert.True(expectedItem.PatternMatch.Kind == actualItem.PatternMatch.Kind, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.Kind, actualItem.PatternMatch.Kind));
Assert.True(expectedItem.PatternMatch.IsCaseSensitive == actualItem.PatternMatch.IsCaseSensitive, string.Format("pattern: {0} expected: {1} actual: {2}", expectedItem.Name, expectedItem.PatternMatch.IsCaseSensitive, actualItem.PatternMatch.IsCaseSensitive));
Assert.Equal(expectedItem.Language, actualItem.Language);
Assert.Equal(expectedItem.Kind, actualItem.Kind);
if (!string.IsNullOrEmpty(expectedItem.SecondarySort))
{
Assert.Contains(expectedItem.SecondarySort, actualItem.SecondarySort, StringComparison.Ordinal);
}
}
}
internal void VerifyNavigateToResultItem(
NavigateToItem result, string name, string displayMarkup,
PatternMatchKind matchKind, string navigateToItemKind,
Glyph glyph, string additionalInfo = null)
{
// Verify symbol information
Assert.Equal(name, result.Name);
Assert.Equal(matchKind, result.PatternMatch.Kind);
Assert.Equal(this.Language, result.Language);
Assert.Equal(navigateToItemKind, result.Kind);
MarkupTestFile.GetSpans(displayMarkup, out displayMarkup,
out ImmutableArray<TextSpan> expectedDisplayNameSpans);
var itemDisplay = (NavigateToItemDisplay)result.DisplayFactory.CreateItemDisplay(result);
Assert.Equal(itemDisplay.GlyphMoniker, glyph.GetImageMoniker());
Assert.Equal(displayMarkup, itemDisplay.Name);
Assert.Equal<TextSpan>(
expectedDisplayNameSpans,
itemDisplay.GetNameMatchRuns("").Select(s => s.ToTextSpan()).ToImmutableArray());
if (additionalInfo != null)
{
Assert.Equal(additionalInfo, itemDisplay.AdditionalInformation);
}
}
internal static BitmapSource CreateIconBitmapSource()
{
var stride = PixelFormats.Bgr32.BitsPerPixel / 8 * 16;
return BitmapSource.Create(16, 16, 96, 96, PixelFormats.Bgr32, null, new byte[16 * stride], stride);
}
// For ordering of NavigateToItems, see
// http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.language.navigateto.interfaces.navigatetoitem.aspx
protected static int CompareNavigateToItems(NavigateToItem a, NavigateToItem b)
=> ComparerWithState.CompareTo(a, b, s_comparisonComponents);
private static readonly ImmutableArray<Func<NavigateToItem, IComparable>> s_comparisonComponents =
ImmutableArray.Create<Func<NavigateToItem, IComparable>>(
item => (int)item.PatternMatch.Kind,
item => item.Name,
item => item.Kind,
item => item.SecondarySort);
private class FirstDocIsVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> null;
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
private class FirstDocIsActiveAndVisibleDocumentTrackingService : IDocumentTrackingService
{
private readonly Workspace _workspace;
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
private FirstDocIsActiveAndVisibleDocumentTrackingService(Workspace workspace)
=> _workspace = workspace;
public bool SupportsDocumentTracking => true;
public event EventHandler<DocumentId> ActiveDocumentChanged { add { } remove { } }
public event EventHandler<EventArgs> NonRoslynBufferTextChanged { add { } remove { } }
public DocumentId TryGetActiveDocument()
=> _workspace.CurrentSolution.Projects.First().DocumentIds.First();
public ImmutableArray<DocumentId> GetVisibleDocuments()
=> ImmutableArray.Create(_workspace.CurrentSolution.Projects.First().DocumentIds.First());
[ExportWorkspaceServiceFactory(typeof(IDocumentTrackingService), ServiceLayer.Test), Shared, PartNotDiscoverable]
public class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
[Obsolete(MefConstruction.FactoryMethodMessage, error: true)]
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new FirstDocIsActiveAndVisibleDocumentTrackingService(workspaceServices.Workspace);
}
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_DimStatement.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.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitDimStatement(node As BoundDimStatement) As BoundNode
Dim inits As ArrayBuilder(Of BoundStatement) = Nothing
For Each decl In node.LocalDeclarations
Dim init As BoundNode = Me.Visit(decl)
If init IsNot Nothing Then
If inits Is Nothing Then
inits = ArrayBuilder(Of BoundStatement).GetInstance
End If
inits.Add(DirectCast(init, BoundStatement))
End If
Next
If inits IsNot Nothing Then
Return New BoundStatementList(node.Syntax, inits.ToImmutableAndFree)
Else
Return Nothing
End If
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.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitDimStatement(node As BoundDimStatement) As BoundNode
Dim inits As ArrayBuilder(Of BoundStatement) = Nothing
For Each decl In node.LocalDeclarations
Dim init As BoundNode = Me.Visit(decl)
If init IsNot Nothing Then
If inits Is Nothing Then
inits = ArrayBuilder(Of BoundStatement).GetInstance
End If
inits.Add(DirectCast(init, BoundStatement))
End If
Next
If inits IsNot Nothing Then
Return New BoundStatementList(node.Syntax, inits.ToImmutableAndFree)
Else
Return Nothing
End If
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_HostObjectMemberReference.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.Diagnostics
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class LocalRewriter
Public Overrides Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference) As BoundNode
Debug.Assert(_previousSubmissionFields IsNot Nothing)
Debug.Assert(Not _topMethod.IsShared)
Dim syntax = node.Syntax
Dim hostObjectReference = _previousSubmissionFields.GetHostObjectField()
Dim meReference = New BoundMeReference(syntax, _topMethod.ContainingType)
Return New BoundFieldAccess(syntax, receiverOpt:=meReference, FieldSymbol:=hostObjectReference, isLValue:=False, Type:=hostObjectReference.Type)
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.Diagnostics
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class LocalRewriter
Public Overrides Function VisitHostObjectMemberReference(node As BoundHostObjectMemberReference) As BoundNode
Debug.Assert(_previousSubmissionFields IsNot Nothing)
Debug.Assert(Not _topMethod.IsShared)
Dim syntax = node.Syntax
Dim hostObjectReference = _previousSubmissionFields.GetHostObjectField()
Dim meReference = New BoundMeReference(syntax, _topMethod.ContainingType)
Return New BoundFieldAccess(syntax, receiverOpt:=meReference, FieldSymbol:=hostObjectReference, isLValue:=False, Type:=hostObjectReference.Type)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IForEachLoopStatement.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.Operations
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_SimpleForLoopsTest()
Dim source = <![CDATA[
Imports System
Class C
Shared Sub Main()
Dim arr As String() = New String(1) {}
arr(0) = "one"
arr(1) = "two"
For Each s As String In arr'BIND:"For Each s As String In arr"
Console.WriteLine(s)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each s ... Next')
Locals: Local_1: s As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: s As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's As String')
Initializer:
null
Collection:
ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.String()) (Syntax: 'arr')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each s ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's')
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_WithList()
Dim source = <![CDATA[
Class Program
Private Shared Sub Main(args As String())
Dim list As New System.Collections.Generic.List(Of String)()
list.Add("a")
list.Add("b")
list.Add("c")
For Each item As String In list'BIND:"For Each item As String In list"
System.Console.WriteLine(item)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each it ... Next')
Locals: Local_1: item As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: item As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'item As String')
Initializer:
null
Collection:
ILocalReferenceOperation: list (OperationKind.LocalReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'list')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each it ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... eLine(item)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(item)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'item')
ILocalReferenceOperation: item (OperationKind.LocalReference, Type: System.String) (Syntax: 'item')
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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_WithBreak()
Dim source = <![CDATA[
Class C
Public Shared Sub Main()
Dim S As String() = New String() {"ABC", "XYZ"}
For Each x As String In S
For Each y As Char In x'BIND:"For Each y As Char In x"
If y = "B"c Then
Exit For
Else
System.Console.WriteLine(y)
End If
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next')
Locals: Local_1: y As System.Char
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char')
Initializer:
null
Collection:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If y = "B"c ... End If')
Condition:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y = "B"c')
Left:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: B) (Syntax: '"B"c')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If y = "B"c ... End If')
IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'Exit For')
WhenFalse:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: 'Else ... riteLine(y)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_WithContinue()
Dim source = <![CDATA[
Class C
Public Shared Sub Main()
Dim S As String() = New String() {"ABC", "XYZ"}
For Each x As String In S'BIND:"For Each x As String In S"
For Each y As Char In x
If y = "B"c Then
Continue For
End If
System.Console.WriteLine(y)
Next y, x
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next y, x')
Locals: Local_1: x As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As String')
Initializer:
null
Collection:
ILocalReferenceOperation: S (OperationKind.LocalReference, Type: System.String()) (Syntax: 'S')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next y, x')
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next y, x')
Locals: Local_1: y As System.Char
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char')
Initializer:
null
Collection:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next y, x')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If y = "B"c ... End If')
Condition:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y = "B"c')
Left:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: B) (Syntax: '"B"c')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If y = "B"c ... End If')
IBranchOperation (BranchKind.Continue, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'Continue For')
WhenFalse:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (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)
NextVariables(2):
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Nested()
Dim source = <![CDATA[
Class C
Shared Sub Main()
Dim c(3)() As Integer
For Each x As Integer() In c
ReDim x(3)
For i As Integer = 0 To 3
x(i) = i
Next
For Each y As Integer In x'BIND:"For Each y As Integer In x"
System.Console.WriteLine(y)
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next')
Locals: Local_1: y As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Integer')
Initializer:
null
Collection:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'x')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Nested1()
Dim source = <![CDATA[
Class C
Public Shared Sub Main()
Dim S As String() = New String() {"ABC", "XYZ"}
For Each x As String In S'BIND:"For Each x As String In S"
For Each y As Char In x
System.Console.WriteLine(y)
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As String')
Initializer:
null
Collection:
ILocalReferenceOperation: S (OperationKind.LocalReference, Type: System.String()) (Syntax: 'S')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next')
Locals: Local_1: y As System.Char
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char')
Initializer:
null
Collection:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (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)
NextVariables(0)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Interface()
Dim source = <![CDATA[
Option Infer On
Class C
Public Shared Sub Main()
For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()"
System.Console.WriteLine(x)
Next
End Sub
End Class
Class Enumerable
Implements System.Collections.IEnumerable
Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Dim list As New System.Collections.Generic.List(Of Integer)()
list.Add(3)
list.Add(2)
list.Add(1)
Return list.GetEnumerator()
End Function
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.Object
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'New Enumerable()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()')
Arguments(0)
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_String()
Dim source = <![CDATA[
Option Infer On
Class Program
Public Shared Sub Main()
Const s As String = Nothing
For Each y In s'BIND:"For Each y In s"
System.Console.WriteLine(y)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next')
Locals: Local_1: y As System.Char
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y')
Initializer:
null
Collection:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String, Constant: null) (Syntax: 's')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_IterateStruct()
Dim source = <![CDATA[
Option Infer On
Imports System.Collections
Class C
Public Shared Sub Main()
For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()"
System.Console.WriteLine(x)
Next
End Sub
End Class
Structure Enumerable
Implements IEnumerable
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return New Integer() {1, 2, 3}.GetEnumerator()
End Function
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.Object
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'New Enumerable()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()')
Arguments(0)
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_QueryExpression()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Module Program
Sub Main(args As String())
' Obtain a list of customers.
Dim customers As List(Of Customer) = GetCustomers()
' Return customers that are grouped based on country.
Dim countries = From cust In customers
Order By cust.Country, cust.City
Group By CountryName = cust.Country
Into CustomersInCountry = Group, Count()
Order By CountryName
' Output the results.
For Each country In countries'BIND:"For Each country In countries"
Debug.WriteLine(country.CountryName & " count=" & country.Count)
For Each customer In country.CustomersInCountry
Debug.WriteLine(" " & customer.CompanyName & " " & customer.City)
Next
Next
End Sub
Private Function GetCustomers() As List(Of Customer)
Return New List(Of Customer) From
{
New Customer With {.CustomerID = 1, .CompanyName = "C", .City = "H", .Country = "C"},
New Customer With {.CustomerID = 2, .CompanyName = "M", .City = "R", .Country = "U"},
New Customer With {.CustomerID = 3, .CompanyName = "F", .City = "V", .Country = "C"}
}
End Function
End Module
Class Customer
Public Property CustomerID As Integer
Public Property CompanyName As String
Public Property City As String
Public Property Country As String
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each co ... Next')
Locals: Local_1: country As <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: country As <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'country')
Initializer:
null
Collection:
ILocalReferenceOperation: countries (OperationKind.LocalReference, Type: System.Linq.IOrderedEnumerable(Of <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>)) (Syntax: 'countries')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each co ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Debug.Write ... ntry.Count)')
Expression:
IInvocationOperation (Sub System.Diagnostics.Debug.WriteLine(message As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Debug.Write ... ntry.Count)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: 'country.Cou ... untry.Count')
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: 'country.Cou ... untry.Count')
Left:
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: 'country.Cou ... & " count="')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.CountryName As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'country.CountryName')
Instance Receiver:
ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " count=") (Syntax: '" count="')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'country.Count')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.Count As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'country.Count')
Instance Receiver:
ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country')
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)
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each cu ... Next')
Locals: Local_1: customer As Customer
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: customer As Customer) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'customer')
Initializer:
null
Collection:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of Customer)) (Syntax: 'country.Cus ... rsInCountry')
Instance Receiver:
ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each cu ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Debug.Write ... tomer.City)')
Expression:
IInvocationOperation (Sub System.Diagnostics.Debug.WriteLine(message As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Debug.Write ... tomer.City)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: '" " & cus ... stomer.City')
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... stomer.City')
Left:
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... Name & " "')
Left:
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... CompanyName')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "')
Right:
IPropertyReferenceOperation: Property Customer.CompanyName As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'customer.CompanyName')
Instance Receiver:
ILocalReferenceOperation: customer (OperationKind.LocalReference, Type: Customer) (Syntax: 'customer')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "')
Right:
IPropertyReferenceOperation: Property Customer.City As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'customer.City')
Instance Receiver:
ILocalReferenceOperation: customer (OperationKind.LocalReference, Type: Customer) (Syntax: 'customer')
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)
NextVariables(0)
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Multidimensional()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim k(,) = {{1}, {1}}
For Each [Custom] In k'BIND:"For Each [Custom] In k"
Console.Write(VerifyStaticType([Custom], GetType(Integer)))
Console.Write(VerifyStaticType([Custom], GetType(Object)))
Exit For
Next
End Sub
Function VerifyStaticType(Of T)(ByVal x As T, ByVal y As System.Type) As Boolean
Return GetType(T) Is y
End Function
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each [C ... Next')
Locals: Local_1: Custom As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: Custom As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: '[Custom]')
Initializer:
null
Collection:
ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32(,)) (Syntax: 'k')
Body:
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each [C ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... (Integer)))')
Expression:
IInvocationOperation (Sub System.Console.Write(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... (Integer)))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'VerifyStati ... e(Integer))')
IInvocationOperation (Function Program.VerifyStaticType(Of System.Int32)(x As System.Int32, y As System.Type) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'VerifyStati ... e(Integer))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '[Custom]')
ILocalReferenceOperation: Custom (OperationKind.LocalReference, Type: System.Int32) (Syntax: '[Custom]')
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: y) (OperationKind.Argument, Type: null) (Syntax: 'GetType(Integer)')
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Integer)')
TypeOperand: System.Int32
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)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... e(Object)))')
Expression:
IInvocationOperation (Sub System.Console.Write(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... e(Object)))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'VerifyStati ... pe(Object))')
IInvocationOperation (Function Program.VerifyStaticType(Of System.Int32)(x As System.Int32, y As System.Type) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'VerifyStati ... pe(Object))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '[Custom]')
ILocalReferenceOperation: Custom (OperationKind.LocalReference, Type: System.Int32) (Syntax: '[Custom]')
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: y) (OperationKind.Argument, Type: null) (Syntax: 'GetType(Object)')
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Object)')
TypeOperand: System.Object
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)
IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'Exit For')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_LateBinding()
Dim source = <![CDATA[
Option Strict Off
Imports System
Class C
Shared Sub Main()
Dim o As Object = {1, 2, 3}
For Each x In o'BIND:"For Each x In o"
Console.WriteLine(x)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.Object
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'o')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(x)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Pattern()
Dim source = <![CDATA[
Option Infer On
Class C
Public Shared Sub Main()
For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()"
System.Console.WriteLine(x)
Next
End Sub
End Class
Class Enumerable
Public Function GetEnumerator() As Enumerator
Return New Enumerator()
End Function
End Class
Class Enumerator
Private x As Integer = 0
Public ReadOnly Property Current() As Integer
Get
Return x
End Get
End Property
Public Function MoveNext() As Boolean
Return System.Threading.Interlocked.Increment(x) & lt; 4
End Function
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x')
Initializer:
null
Collection:
IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()')
Arguments(0)
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Lambda()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Imports System
Class C1
Private element_lambda_field As Integer
Public Shared Sub Main()
Dim c1 As New C1()
c1.DoStuff()
End Sub
Public Sub DoStuff()
Dim arr As Integer() = New Integer(1) {}
arr(0) = 23
arr(1) = 42
Dim myDelegate As Action = Sub()
Dim element_lambda_local As Integer
For Each element_lambda_local In arr'BIND:"For Each element_lambda_local In arr"
Console.WriteLine(element_lambda_local)
Next element_lambda_local
End Sub
myDelegate.Invoke()
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each el ... ambda_local')
LoopControlVariable:
ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local')
Collection:
ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'arr')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each el ... ambda_local')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... mbda_local)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... mbda_local)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'element_lambda_local')
ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local')
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)
NextVariables(1):
ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local')
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_InvalidConversion()
Dim source = <![CDATA[
Imports System
Class C1
Public Shared Sub Main()
For Each element As Integer In "Hello World."'BIND:"For Each element As Integer In "Hello World.""
Console.WriteLine(element)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For Each el ... Next')
Locals: Local_1: element As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: element As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'element As Integer')
Initializer:
null
Collection:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World.", IsInvalid) (Syntax: '"Hello World."')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For Each el ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... ne(element)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ne(element)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'element')
ILocalReferenceOperation: element (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Throw()
Dim source = <![CDATA[
Imports System
Class C
Shared Sub Main()
Dim arr As String() = New String(1) {}
arr(0) = "one"
arr(1) = "two"
For Each s As String In arr'BIND:"For Each s As String In arr"
If (s = "one") Then
Throw New Exception
End If
Console.WriteLine(s)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each s ... Next')
Locals: Local_1: s As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: s As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's As String')
Initializer:
null
Collection:
ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.String()) (Syntax: 'arr')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each s ... Next')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If (s = "on ... End If')
Condition:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Boolean) (Syntax: '(s = "one")')
Operand:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's = "one"')
Left:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "one") (Syntax: '"one"')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If (s = "on ... End If')
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'Throw New Exception')
IObjectCreationOperation (Constructor: Sub System.Exception..ctor()) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'New Exception')
Arguments(0)
Initializer:
null
WhenFalse:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's')
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_WithReturn()
Dim source = <![CDATA[
Class C
Private F As Object
Shared Function M(c As Object()) As Boolean
For Each o In c'BIND:"For Each o In c"
If o IsNot Nothing Then Return True
Next
Return False
End Function
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each o ... Next')
Locals: Local_1: o As System.Object
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: o As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'o')
Initializer:
null
Collection:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Object()) (Syntax: 'c')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each o ... Next')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If o IsNot ... Return True')
Condition:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'o IsNot Nothing')
Left:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If o IsNot ... Return True')
IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'Return True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
WhenFalse:
null
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_FieldAsIterationVariable()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Private X As Integer = 0
Sub M(args As Integer())
For Each X In args'BIND:"For Each X In args"
Next X
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each X ... Next X')
LoopControlVariable:
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Collection:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each X ... Next X')
NextVariables(1):
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_FieldWithExplicitReceiverAsIterationVariable()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Private X As Integer = 0
Sub M(c As C, args As Integer())
For Each c.X In args'BIND:"For Each c.X In args"
Next c.X
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each c. ... Next c.X')
LoopControlVariable:
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
Collection:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each c. ... Next c.X')
NextVariables(1):
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_CastArrayToIEnumerable()
Dim source = <![CDATA[
Option Infer On
Imports System.Collections
Class Program
Public Shared Sub Main(args As String(), i As String)
For Each arg As String In DirectCast(args, IEnumerable)'BIND:"For Each arg As String In DirectCast(args, IEnumerable)"
i = arg
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each ar ... Next')
Locals: Local_1: arg As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: arg As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'arg As String')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable) (Syntax: 'DirectCast( ... Enumerable)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each ar ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = arg')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'i = arg')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.String) (Syntax: 'i')
Right:
ILocalReferenceOperation: arg (OperationKind.LocalReference, Type: System.String) (Syntax: 'arg')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_CastCollectionToIEnumerable()
Dim source = <![CDATA[
Option Infer On
Imports System.Collections.Generic
Class Program
Public Shared Sub Main(args As List(Of String), i As String)
For Each arg As String In DirectCast(args, IEnumerable(Of String))'BIND:"For Each arg As String In DirectCast(args, IEnumerable(Of String))"
i = arg
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each ar ... Next')
Locals: Local_1: arg As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: arg As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'arg As String')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.String)) (Syntax: 'DirectCast( ... Of String))')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'args')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each ar ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = arg')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'i = arg')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.String) (Syntax: 'i')
Right:
ILocalReferenceOperation: arg (OperationKind.LocalReference, Type: System.String) (Syntax: 'arg')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_InvalidLoopControlVariableDeclaration()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Sub M(args As Integer())
Dim i as Integer = 0
For Each i as Integer In args'BIND:"For Each i as Integer In args"
Next i
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For Each i ... Next i')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i as Integer')
Initializer:
null
Collection:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For Each i ... Next i')
NextVariables(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30616: Variable 'i' hides a variable in an enclosing block.
For Each i as Integer In args'BIND:"For Each i as Integer In args"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_01()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As C(), y as C(), result As C) 'BIND:"Sub M"
For Each z in If(x, y)
result = z
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
CaptureIds: [2]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C()) (Syntax: 'x')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'x')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y')
Value:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C()) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(x, y)')
Value:
IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'If(x, y)')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B6]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(x, y)')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B6]
Entering: {R4}
.locals {R4}
{
Locals: [z As C]
Block[B6] - Block
Predecessors: [B5]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'z')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'z')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(NarrowingReference)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: C) (Syntax: 'z')
Next (Regular) Block[B5]
Leaving: {R4}
}
}
Block[B7] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_02()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As String) 'BIND:"Sub M"
For Each z As String in x
z?.ToString()
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function System.String.GetEnumerator() As System.CharEnumerator) (OperationKind.Invocation, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B4] [B5]
Statements (0)
Jump if False (Regular) to Block[B9]
IInvocationOperation ( Function System.CharEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R6}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.String]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As String')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'z As String')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'z As String')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningString)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.CharEnumerator.Current As System.Char (OperationKind.PropertyReference, Type: System.Char, IsImplicit) (Syntax: 'z As String')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Entering: {R5}
.locals {R5}
{
CaptureIds: [1]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z')
Value:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.String) (Syntax: 'z')
Jump if True (Regular) to Block[B2]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'z')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'z')
Leaving: {R5} {R4}
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'z?.ToString()')
Expression:
IInvocationOperation (virtual Function System.String.ToString() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'z')
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R5} {R4}
}
}
}
.finally {R6}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(WideningReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B9] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_03()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Integer(,), result As Long) 'BIND:"Sub M"
For Each z As Long in x
result = z
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int64]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z As Long')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_04()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Enumerable, result As Long) 'BIND:"Sub M"
For Each z As Long in x
result = z
Next
End Sub
End Class
Public Structure Enumerable
Public Function GetEnumerator() As Enumerator
Return New Enumerator()
End Function
End Structure
Public Structure Enumerator
Public ReadOnly Property Current As Integer
Get
Return 1
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
End Structure
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function Enumerable.GetEnumerator() As Enumerator) (OperationKind.Invocation, Type: Enumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: Enumerable) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation ( Function Enumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int64]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IPropertyReferenceOperation: ReadOnly Property Enumerator.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Long')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_05()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Enumerable, result As Integer) 'BIND:"Sub M"
For Each z As Integer in x
result = z
Next
End Sub
End Class
Public Structure Enumerable
Public Function GetEnumerator() As Enumerator
Return New Enumerator()
End Function
End Structure
Public Structure Enumerator
Implements System.IDisposable
Public ReadOnly Property Current As Integer
Get
Return 1
End Get
End Property
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Public Function MoveNext() As Boolean
Return False
End Function
End Structure
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function Enumerable.GetEnumerator() As Enumerator) (OperationKind.Invocation, Type: Enumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: Enumerable) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B5]
IInvocationOperation ( Function Enumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R5}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.Int32]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Integer')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Integer')
Right:
IPropertyReferenceOperation: ReadOnly Property Enumerator.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Integer')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R4}
}
}
.finally {R5}
{
Block[B4] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningValue)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B5] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_06()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As System.Collections.Generic.IEnumerable(Of Integer), result As Integer) 'BIND:"Sub M"
For Each z in x
result = z
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation (virtual Function System.Collections.Generic.IEnumerable(Of System.Int32).GetEnumerator() As System.Collections.Generic.IEnumerator(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32)) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R5}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.Int32]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Right:
IPropertyReferenceOperation: ReadOnly Property System.Collections.Generic.IEnumerator(Of System.Int32).Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R4}
}
}
.finally {R5}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(WideningReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_11()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Object, result As Object) 'BIND:"Sub M"
For Each z in x
result = z
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation (virtual Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(NarrowingReference)
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R5}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.Object]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Right:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R4}
}
}
.finally {R5}
{
CaptureIds: [1]
Block[B4] - Block
Predecessors (0)
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(NarrowingReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_12()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As C, result As Integer) 'BIND:"Sub M"
For Each z in x
result = z
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32023: Expression is of type 'C', which is not a collection type.
For Each z in x
~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'x')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Children(0)
Next (Regular) Block[B3]
Entering: {R1}
.locals {R1}
{
Locals: [z As System.Object]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Children(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_15()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M() 'BIND:"Sub M"
For Each If(GetC(), Me).F in Me
Next
End Sub
Public F As C
Public ReadOnly Property Current As C
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
Module Ext
<Runtime.CompilerServices.Extension>
Public Function GetEnumerator(this As C) As C
Return this
End Function
End Module
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B6]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC()')
Value:
IInvocationOperation (Function C.GetC() As C) (OperationKind.Invocation, Type: C) (Syntax: 'GetC()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetC()')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC()')
Leaving: {R3}
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC()')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC()')
Next (Regular) Block[B6]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me).F')
Left:
IFieldReferenceOperation: C.F As C (OperationKind.FieldReference, Type: C) (Syntax: 'If(GetC(), Me).F')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me)')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me).F')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_16()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As System.Collections.IEnumerable, result As Object) 'BIND:"Sub M"
For Each z in x
result = z
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation (virtual Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Collections.IEnumerable) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R5}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.Object]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Right:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R4}
}
}
.finally {R5}
{
CaptureIds: [1]
Block[B4] - Block
Predecessors (0)
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(NarrowingReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_17()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Integer(), result As Long) 'BIND:"Sub M"
For Each z As Long in x
result = z
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int64]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z As Long')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_18()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(result as Boolean) 'BIND:"Sub M"
For Each x in Me
If x
Continue For
End If
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Boolean
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B5]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [x As System.Boolean]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Jump if False (Regular) to Block[B4]
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B5] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_19()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(result as Boolean) 'BIND:"Sub M"
For Each x in Me
If x
Exit For
End If
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Boolean
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B4]
Statements (0)
Jump if False (Regular) to Block[B5]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [x As System.Boolean]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Jump if False (Regular) to Block[B4]
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B5]
Leaving: {R2} {R1}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B5] - Exit
Predecessors: [B2] [B3]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_20()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(y as Boolean, result as Boolean) 'BIND:"Sub M"
For Each x in Me
While y
result = y
Continue For
End While
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Boolean
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B4] [B5]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [x As System.Boolean]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = y')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = y')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B2]
Leaving: {R2}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_21()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(y as Boolean, result as Boolean) 'BIND:"Sub M"
For Each x in Me
While y
result = y
Exit For
End While
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Boolean
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [x As System.Boolean]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = y')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = y')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B6]
Leaving: {R2} {R1}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B6] - Exit
Predecessors: [B2] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_22()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M() 'BIND:"Sub M"
For Each z As Long in If(GetC(), GetC())
Next
End Sub
Shared Function GetC() As C
Return Nothing
End Function
Shared Function GetEnumerator() As C
Return Nothing
End Function
Shared Function MoveNext() As Boolean
Return Nothing
End Function
Shared ReadOnly Property Current As Integer
Get
Return 1
End Get
End Property
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
For Each z As Long in If(GetC(), GetC())
~~~~~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
For Each z As Long in If(GetC(), GetC())
~~~~~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
For Each z As Long in If(GetC(), GetC())
~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(GetC(), GetC())')
Value:
IInvocationOperation (Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'If(GetC(), GetC())')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation (Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(GetC(), GetC())')
Instance Receiver:
null
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int64]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Long')
Instance Receiver:
null
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_23()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As C) 'BIND:"Sub M"
For Each z in x
Next
End Sub
Function GetEnumerator(<System.Runtime.CompilerServices.CallerMemberName> Optional member As String = "") As C
Return Nothing
End Function
Function MoveNext(Optional s As String = "ABC") As Boolean
Return Nothing
End Function
ReadOnly Property Current(Optional d As Double = 123.45) As Integer
Get
Return 1
End Get
End Property
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function C.GetEnumerator([member As System.String = ""]) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x')
Arguments(1):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: member) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "M", IsImplicit) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation ( Function C.MoveNext([s As System.String = "ABC"]) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x')
Arguments(1):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "ABC", IsImplicit) (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)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int32]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current([d As System.Double = 123.45]) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x')
Arguments(1):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: d) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 123.45, IsImplicit) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, useLatestFramework:=True)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_24()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(result as Integer) 'BIND:"Sub M"
For Each x As Integer in GetC(x)
result = x
Next
End Sub
Public Function GetC(ByRef x as Integer) As C
Return Me
End Function
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Integer
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [0]
.locals {R2}
{
Locals: [x As System.Int32]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC(x)')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'GetC(x)')
Instance Receiver:
IInvocationOperation ( Function C.GetC(ByRef x As System.Int32) As C) (OperationKind.Invocation, Type: C) (Syntax: 'GetC(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'GetC')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'GetC(x)')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC(x)')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R3}
.locals {R3}
{
Locals: [x As System.Int32]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x As Integer')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC(x)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R3}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_25()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(result as C) 'BIND:"Sub M"
For Each x As C in x
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As C
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
For Each x As C in x
~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [0]
.locals {R2}
{
Locals: [x As C]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'x')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R3}
.locals {R3}
{
Locals: [x As C]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x As C')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'x As C')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'x As C')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R3}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
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.Operations
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_SimpleForLoopsTest()
Dim source = <![CDATA[
Imports System
Class C
Shared Sub Main()
Dim arr As String() = New String(1) {}
arr(0) = "one"
arr(1) = "two"
For Each s As String In arr'BIND:"For Each s As String In arr"
Console.WriteLine(s)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each s ... Next')
Locals: Local_1: s As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: s As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's As String')
Initializer:
null
Collection:
ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.String()) (Syntax: 'arr')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each s ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's')
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_WithList()
Dim source = <![CDATA[
Class Program
Private Shared Sub Main(args As String())
Dim list As New System.Collections.Generic.List(Of String)()
list.Add("a")
list.Add("b")
list.Add("c")
For Each item As String In list'BIND:"For Each item As String In list"
System.Console.WriteLine(item)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each it ... Next')
Locals: Local_1: item As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: item As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'item As String')
Initializer:
null
Collection:
ILocalReferenceOperation: list (OperationKind.LocalReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'list')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each it ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... eLine(item)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(item)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'item')
ILocalReferenceOperation: item (OperationKind.LocalReference, Type: System.String) (Syntax: 'item')
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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_WithBreak()
Dim source = <![CDATA[
Class C
Public Shared Sub Main()
Dim S As String() = New String() {"ABC", "XYZ"}
For Each x As String In S
For Each y As Char In x'BIND:"For Each y As Char In x"
If y = "B"c Then
Exit For
Else
System.Console.WriteLine(y)
End If
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next')
Locals: Local_1: y As System.Char
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char')
Initializer:
null
Collection:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If y = "B"c ... End If')
Condition:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y = "B"c')
Left:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: B) (Syntax: '"B"c')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If y = "B"c ... End If')
IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'Exit For')
WhenFalse:
IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: 'Else ... riteLine(y)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_WithContinue()
Dim source = <![CDATA[
Class C
Public Shared Sub Main()
Dim S As String() = New String() {"ABC", "XYZ"}
For Each x As String In S'BIND:"For Each x As String In S"
For Each y As Char In x
If y = "B"c Then
Continue For
End If
System.Console.WriteLine(y)
Next y, x
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next y, x')
Locals: Local_1: x As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As String')
Initializer:
null
Collection:
ILocalReferenceOperation: S (OperationKind.LocalReference, Type: System.String()) (Syntax: 'S')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next y, x')
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next y, x')
Locals: Local_1: y As System.Char
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char')
Initializer:
null
Collection:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next y, x')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If y = "B"c ... End If')
Condition:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y = "B"c')
Left:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: B) (Syntax: '"B"c')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If y = "B"c ... End If')
IBranchOperation (BranchKind.Continue, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'Continue For')
WhenFalse:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (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)
NextVariables(2):
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (Syntax: 'y')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Nested()
Dim source = <![CDATA[
Class C
Shared Sub Main()
Dim c(3)() As Integer
For Each x As Integer() In c
ReDim x(3)
For i As Integer = 0 To 3
x(i) = i
Next
For Each y As Integer In x'BIND:"For Each y As Integer In x"
System.Console.WriteLine(y)
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next')
Locals: Local_1: y As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Integer')
Initializer:
null
Collection:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'x')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Nested1()
Dim source = <![CDATA[
Class C
Public Shared Sub Main()
Dim S As String() = New String() {"ABC", "XYZ"}
For Each x As String In S'BIND:"For Each x As String In S"
For Each y As Char In x
System.Console.WriteLine(y)
Next
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x As String')
Initializer:
null
Collection:
ILocalReferenceOperation: S (OperationKind.LocalReference, Type: System.String()) (Syntax: 'S')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next')
Locals: Local_1: y As System.Char
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y As Char')
Initializer:
null
Collection:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.String) (Syntax: 'x')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (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)
NextVariables(0)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Interface()
Dim source = <![CDATA[
Option Infer On
Class C
Public Shared Sub Main()
For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()"
System.Console.WriteLine(x)
Next
End Sub
End Class
Class Enumerable
Implements System.Collections.IEnumerable
Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Dim list As New System.Collections.Generic.List(Of Integer)()
list.Add(3)
list.Add(2)
list.Add(1)
Return list.GetEnumerator()
End Function
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.Object
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'New Enumerable()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()')
Arguments(0)
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_String()
Dim source = <![CDATA[
Option Infer On
Class Program
Public Shared Sub Main()
Const s As String = Nothing
For Each y In s'BIND:"For Each y In s"
System.Console.WriteLine(y)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each y ... Next')
Locals: Local_1: y As System.Char
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: y As System.Char) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y')
Initializer:
null
Collection:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String, Constant: null) (Syntax: 's')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each y ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(y)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Char)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(y)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Char) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_IterateStruct()
Dim source = <![CDATA[
Option Infer On
Imports System.Collections
Class C
Public Shared Sub Main()
For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()"
System.Console.WriteLine(x)
Next
End Sub
End Class
Structure Enumerable
Implements IEnumerable
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return New Integer() {1, 2, 3}.GetEnumerator()
End Function
End Structure
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.Object
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'New Enumerable()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()')
Arguments(0)
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_QueryExpression()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Linq
Module Program
Sub Main(args As String())
' Obtain a list of customers.
Dim customers As List(Of Customer) = GetCustomers()
' Return customers that are grouped based on country.
Dim countries = From cust In customers
Order By cust.Country, cust.City
Group By CountryName = cust.Country
Into CustomersInCountry = Group, Count()
Order By CountryName
' Output the results.
For Each country In countries'BIND:"For Each country In countries"
Debug.WriteLine(country.CountryName & " count=" & country.Count)
For Each customer In country.CustomersInCountry
Debug.WriteLine(" " & customer.CompanyName & " " & customer.City)
Next
Next
End Sub
Private Function GetCustomers() As List(Of Customer)
Return New List(Of Customer) From
{
New Customer With {.CustomerID = 1, .CompanyName = "C", .City = "H", .Country = "C"},
New Customer With {.CustomerID = 2, .CompanyName = "M", .City = "R", .Country = "U"},
New Customer With {.CustomerID = 3, .CompanyName = "F", .City = "V", .Country = "C"}
}
End Function
End Module
Class Customer
Public Property CustomerID As Integer
Public Property CompanyName As String
Public Property City As String
Public Property Country As String
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each co ... Next')
Locals: Local_1: country As <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: country As <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'country')
Initializer:
null
Collection:
ILocalReferenceOperation: countries (OperationKind.LocalReference, Type: System.Linq.IOrderedEnumerable(Of <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>)) (Syntax: 'countries')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each co ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Debug.Write ... ntry.Count)')
Expression:
IInvocationOperation (Sub System.Diagnostics.Debug.WriteLine(message As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Debug.Write ... ntry.Count)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: 'country.Cou ... untry.Count')
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: 'country.Cou ... untry.Count')
Left:
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: 'country.Cou ... & " count="')
Left:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.CountryName As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'country.CountryName')
Instance Receiver:
ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " count=") (Syntax: '" count="')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'country.Count')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.Count As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'country.Count')
Instance Receiver:
ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country')
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)
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'For Each cu ... Next')
Locals: Local_1: customer As Customer
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: customer As Customer) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'customer')
Initializer:
null
Collection:
IPropertyReferenceOperation: ReadOnly Property <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>.CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer) (OperationKind.PropertyReference, Type: System.Collections.Generic.IEnumerable(Of Customer)) (Syntax: 'country.Cus ... rsInCountry')
Instance Receiver:
ILocalReferenceOperation: country (OperationKind.LocalReference, Type: <anonymous type: Key CountryName As System.String, Key CustomersInCountry As System.Collections.Generic.IEnumerable(Of Customer), Key Count As System.Int32>) (Syntax: 'country')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each cu ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Debug.Write ... tomer.City)')
Expression:
IInvocationOperation (Sub System.Diagnostics.Debug.WriteLine(message As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Debug.Write ... tomer.City)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: message) (OperationKind.Argument, Type: null) (Syntax: '" " & cus ... stomer.City')
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... stomer.City')
Left:
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... Name & " "')
Left:
IBinaryOperation (BinaryOperatorKind.Concatenate, Checked) (OperationKind.Binary, Type: System.String) (Syntax: '" " & cus ... CompanyName')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "')
Right:
IPropertyReferenceOperation: Property Customer.CompanyName As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'customer.CompanyName')
Instance Receiver:
ILocalReferenceOperation: customer (OperationKind.LocalReference, Type: Customer) (Syntax: 'customer')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: " ") (Syntax: '" "')
Right:
IPropertyReferenceOperation: Property Customer.City As System.String (OperationKind.PropertyReference, Type: System.String) (Syntax: 'customer.City')
Instance Receiver:
ILocalReferenceOperation: customer (OperationKind.LocalReference, Type: Customer) (Syntax: 'customer')
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)
NextVariables(0)
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Multidimensional()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim k(,) = {{1}, {1}}
For Each [Custom] In k'BIND:"For Each [Custom] In k"
Console.Write(VerifyStaticType([Custom], GetType(Integer)))
Console.Write(VerifyStaticType([Custom], GetType(Object)))
Exit For
Next
End Sub
Function VerifyStaticType(Of T)(ByVal x As T, ByVal y As System.Type) As Boolean
Return GetType(T) Is y
End Function
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each [C ... Next')
Locals: Local_1: Custom As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: Custom As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: '[Custom]')
Initializer:
null
Collection:
ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32(,)) (Syntax: 'k')
Body:
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each [C ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... (Integer)))')
Expression:
IInvocationOperation (Sub System.Console.Write(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... (Integer)))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'VerifyStati ... e(Integer))')
IInvocationOperation (Function Program.VerifyStaticType(Of System.Int32)(x As System.Int32, y As System.Type) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'VerifyStati ... e(Integer))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '[Custom]')
ILocalReferenceOperation: Custom (OperationKind.LocalReference, Type: System.Int32) (Syntax: '[Custom]')
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: y) (OperationKind.Argument, Type: null) (Syntax: 'GetType(Integer)')
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Integer)')
TypeOperand: System.Int32
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)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... e(Object)))')
Expression:
IInvocationOperation (Sub System.Console.Write(value As System.Boolean)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... e(Object)))')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'VerifyStati ... pe(Object))')
IInvocationOperation (Function Program.VerifyStaticType(Of System.Int32)(x As System.Int32, y As System.Type) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'VerifyStati ... pe(Object))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '[Custom]')
ILocalReferenceOperation: Custom (OperationKind.LocalReference, Type: System.Int32) (Syntax: '[Custom]')
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: y) (OperationKind.Argument, Type: null) (Syntax: 'GetType(Object)')
ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Object)')
TypeOperand: System.Object
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)
IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'Exit For')
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_LateBinding()
Dim source = <![CDATA[
Option Strict Off
Imports System
Class C
Shared Sub Main()
Dim o As Object = {1, 2, 3}
For Each x In o'BIND:"For Each x In o"
Console.WriteLine(x)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.Object
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'o')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(x)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Pattern()
Dim source = <![CDATA[
Option Infer On
Class C
Public Shared Sub Main()
For Each x In New Enumerable()'BIND:"For Each x In New Enumerable()"
System.Console.WriteLine(x)
Next
End Sub
End Class
Class Enumerable
Public Function GetEnumerator() As Enumerator
Return New Enumerator()
End Function
End Class
Class Enumerator
Private x As Integer = 0
Public ReadOnly Property Current() As Integer
Get
Return x
End Get
End Property
Public Function MoveNext() As Boolean
Return System.Threading.Interlocked.Increment(x) & lt; 4
End Function
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each x ... Next')
Locals: Local_1: x As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: x As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x')
Initializer:
null
Collection:
IObjectCreationOperation (Constructor: Sub Enumerable..ctor()) (OperationKind.ObjectCreation, Type: Enumerable) (Syntax: 'New Enumerable()')
Arguments(0)
Initializer:
null
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each x ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... riteLine(x)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(x)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Lambda()
Dim source = <![CDATA[
Option Strict On
Option Infer On
Imports System
Class C1
Private element_lambda_field As Integer
Public Shared Sub Main()
Dim c1 As New C1()
c1.DoStuff()
End Sub
Public Sub DoStuff()
Dim arr As Integer() = New Integer(1) {}
arr(0) = 23
arr(1) = 42
Dim myDelegate As Action = Sub()
Dim element_lambda_local As Integer
For Each element_lambda_local In arr'BIND:"For Each element_lambda_local In arr"
Console.WriteLine(element_lambda_local)
Next element_lambda_local
End Sub
myDelegate.Invoke()
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each el ... ambda_local')
LoopControlVariable:
ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local')
Collection:
ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'arr')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each el ... ambda_local')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... mbda_local)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... mbda_local)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'element_lambda_local')
ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local')
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)
NextVariables(1):
ILocalReferenceOperation: element_lambda_local (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element_lambda_local')
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_InvalidConversion()
Dim source = <![CDATA[
Imports System
Class C1
Public Shared Sub Main()
For Each element As Integer In "Hello World."'BIND:"For Each element As Integer In "Hello World.""
Console.WriteLine(element)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For Each el ... Next')
Locals: Local_1: element As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: element As System.Int32) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'element As Integer')
Initializer:
null
Collection:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "Hello World.", IsInvalid) (Syntax: '"Hello World."')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For Each el ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.Wri ... ne(element)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.Wri ... ne(element)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'element')
ILocalReferenceOperation: element (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'element')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_Throw()
Dim source = <![CDATA[
Imports System
Class C
Shared Sub Main()
Dim arr As String() = New String(1) {}
arr(0) = "one"
arr(1) = "two"
For Each s As String In arr'BIND:"For Each s As String In arr"
If (s = "one") Then
Throw New Exception
End If
Console.WriteLine(s)
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each s ... Next')
Locals: Local_1: s As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: s As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 's As String')
Initializer:
null
Collection:
ILocalReferenceOperation: arr (OperationKind.LocalReference, Type: System.String()) (Syntax: 'arr')
Body:
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each s ... Next')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If (s = "on ... End If')
Condition:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Boolean) (Syntax: '(s = "one")')
Operand:
IBinaryOperation (BinaryOperatorKind.Equals, Checked) (OperationKind.Binary, Type: System.Boolean) (Syntax: 's = "one"')
Left:
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "one") (Syntax: '"one"')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If (s = "on ... End If')
IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'Throw New Exception')
IObjectCreationOperation (Constructor: Sub System.Exception..ctor()) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'New Exception')
Arguments(0)
Initializer:
null
WhenFalse:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(s)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(s)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 's')
ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (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)
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_WithReturn()
Dim source = <![CDATA[
Class C
Private F As Object
Shared Function M(c As Object()) As Boolean
For Each o In c'BIND:"For Each o In c"
If o IsNot Nothing Then Return True
Next
Return False
End Function
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each o ... Next')
Locals: Local_1: o As System.Object
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: o As System.Object) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'o')
Initializer:
null
Collection:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Object()) (Syntax: 'c')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each o ... Next')
IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'If o IsNot ... Return True')
Condition:
IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'o IsNot Nothing')
Left:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
WhenTrue:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'If o IsNot ... Return True')
IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'Return True')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
WhenFalse:
null
NextVariables(0)
]]>.Value
VerifyOperationTreeForTest(Of ForEachBlockSyntax)(source, expectedOperationTree)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_FieldAsIterationVariable()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Private X As Integer = 0
Sub M(args As Integer())
For Each X In args'BIND:"For Each X In args"
Next X
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each X ... Next X')
LoopControlVariable:
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
Collection:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each X ... Next X')
NextVariables(1):
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'X')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_FieldWithExplicitReceiverAsIterationVariable()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Private X As Integer = 0
Sub M(c As C, args As Integer())
For Each c.X In args'BIND:"For Each c.X In args"
Next c.X
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each c. ... Next c.X')
LoopControlVariable:
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
Collection:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each c. ... Next c.X')
NextVariables(1):
IFieldReferenceOperation: C.X As System.Int32 (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'c.X')
Instance Receiver:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_CastArrayToIEnumerable()
Dim source = <![CDATA[
Option Infer On
Imports System.Collections
Class Program
Public Shared Sub Main(args As String(), i As String)
For Each arg As String In DirectCast(args, IEnumerable)'BIND:"For Each arg As String In DirectCast(args, IEnumerable)"
i = arg
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each ar ... Next')
Locals: Local_1: arg As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: arg As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'arg As String')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable) (Syntax: 'DirectCast( ... Enumerable)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String()) (Syntax: 'args')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each ar ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = arg')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'i = arg')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.String) (Syntax: 'i')
Right:
ILocalReferenceOperation: arg (OperationKind.LocalReference, Type: System.String) (Syntax: 'arg')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_CastCollectionToIEnumerable()
Dim source = <![CDATA[
Option Infer On
Imports System.Collections.Generic
Class Program
Public Shared Sub Main(args As List(Of String), i As String)
For Each arg As String In DirectCast(args, IEnumerable(Of String))'BIND:"For Each arg As String In DirectCast(args, IEnumerable(Of String))"
i = arg
Next
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'For Each ar ... Next')
Locals: Local_1: arg As System.String
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: arg As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'arg As String')
Initializer:
null
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable(Of System.String)) (Syntax: 'DirectCast( ... Of String))')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Collections.Generic.List(Of System.String)) (Syntax: 'args')
Body:
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'For Each ar ... Next')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = arg')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'i = arg')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.String) (Syntax: 'i')
Right:
ILocalReferenceOperation: arg (OperationKind.LocalReference, Type: System.String) (Syntax: 'arg')
NextVariables(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact(), WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")>
Public Sub IForEachLoopStatement_InvalidLoopControlVariableDeclaration()
Dim source = <![CDATA[
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C
Sub M(args As Integer())
Dim i as Integer = 0
For Each i as Integer In args'BIND:"For Each i as Integer In args"
Next i
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'For Each i ... Next i')
Locals: Local_1: i As System.Int32
LoopControlVariable:
IVariableDeclaratorOperation (Symbol: i As System.Int32) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i as Integer')
Initializer:
null
Collection:
IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'args')
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'For Each i ... Next i')
NextVariables(1):
ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30616: Variable 'i' hides a variable in an enclosing block.
For Each i as Integer In args'BIND:"For Each i as Integer In args"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ForEachBlockSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_01()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As C(), y as C(), result As C) 'BIND:"Sub M"
For Each z in If(x, y)
result = z
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
CaptureIds: [2]
.locals {R2}
{
CaptureIds: [1]
.locals {R3}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C()) (Syntax: 'x')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'x')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y')
Value:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C()) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(x, y)')
Value:
IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C(), IsImplicit) (Syntax: 'If(x, y)')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4] [B6]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(x, y)')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B6]
Entering: {R4}
.locals {R4}
{
Locals: [z As C]
Block[B6] - Block
Predecessors: [B5]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'z')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: C, IsImplicit) (Syntax: 'z')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(NarrowingReference)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'If(x, y)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: C) (Syntax: 'z')
Next (Regular) Block[B5]
Leaving: {R4}
}
}
Block[B7] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_02()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As String) 'BIND:"Sub M"
For Each z As String in x
z?.ToString()
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function System.String.GetEnumerator() As System.CharEnumerator) (OperationKind.Invocation, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B4] [B5]
Statements (0)
Jump if False (Regular) to Block[B9]
IInvocationOperation ( Function System.CharEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R6}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.String]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As String')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsImplicit) (Syntax: 'z As String')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsImplicit) (Syntax: 'z As String')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningString)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.CharEnumerator.Current As System.Char (OperationKind.PropertyReference, Type: System.Char, IsImplicit) (Syntax: 'z As String')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B4]
Entering: {R5}
.locals {R5}
{
CaptureIds: [1]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z')
Value:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.String) (Syntax: 'z')
Jump if True (Regular) to Block[B2]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'z')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'z')
Leaving: {R5} {R4}
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'z?.ToString()')
Expression:
IInvocationOperation (virtual Function System.String.ToString() As System.String) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'z')
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R5} {R4}
}
}
}
.finally {R6}
{
Block[B6] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B8]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B7]
Block[B7] - Block
Predecessors: [B6]
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(WideningReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.CharEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B9] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_03()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Integer(,), result As Long) 'BIND:"Sub M"
For Each z As Long in x
result = z
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32(,)) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int64]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z As Long')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_04()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Enumerable, result As Long) 'BIND:"Sub M"
For Each z As Long in x
result = z
Next
End Sub
End Class
Public Structure Enumerable
Public Function GetEnumerator() As Enumerator
Return New Enumerator()
End Function
End Structure
Public Structure Enumerator
Public ReadOnly Property Current As Integer
Get
Return 1
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
End Structure
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function Enumerable.GetEnumerator() As Enumerator) (OperationKind.Invocation, Type: Enumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: Enumerable) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation ( Function Enumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int64]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IPropertyReferenceOperation: ReadOnly Property Enumerator.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Long')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_05()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Enumerable, result As Integer) 'BIND:"Sub M"
For Each z As Integer in x
result = z
Next
End Sub
End Class
Public Structure Enumerable
Public Function GetEnumerator() As Enumerator
Return New Enumerator()
End Function
End Structure
Public Structure Enumerator
Implements System.IDisposable
Public ReadOnly Property Current As Integer
Get
Return 1
End Get
End Property
Public Sub Dispose() Implements IDisposable.Dispose
End Sub
Public Function MoveNext() As Boolean
Return False
End Function
End Structure
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function Enumerable.GetEnumerator() As Enumerator) (OperationKind.Invocation, Type: Enumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: Enumerable) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B5]
IInvocationOperation ( Function Enumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R5}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.Int32]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Integer')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Integer')
Right:
IPropertyReferenceOperation: ReadOnly Property Enumerator.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Integer')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R4}
}
}
.finally {R5}
{
Block[B4] - Block
Predecessors (0)
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningValue)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: Enumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B5] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_06()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As System.Collections.Generic.IEnumerable(Of Integer), result As Integer) 'BIND:"Sub M"
For Each z in x
result = z
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation (virtual Function System.Collections.Generic.IEnumerable(Of System.Int32).GetEnumerator() As System.Collections.Generic.IEnumerator(Of System.Int32)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable(Of System.Int32)) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R5}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.Int32]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Right:
IPropertyReferenceOperation: ReadOnly Property System.Collections.Generic.IEnumerator(Of System.Int32).Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R4}
}
}
.finally {R5}
{
Block[B4] - Block
Predecessors (0)
Statements (0)
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(WideningReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.Generic.IEnumerator(Of System.Int32), IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_11()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Object, result As Object) 'BIND:"Sub M"
For Each z in x
result = z
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation (virtual Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(NarrowingReference)
Operand:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R5}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.Object]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Right:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R4}
}
}
.finally {R5}
{
CaptureIds: [1]
Block[B4] - Block
Predecessors (0)
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(NarrowingReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_12()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As C, result As Integer) 'BIND:"Sub M"
For Each z in x
result = z
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32023: Expression is of type 'C', which is not a collection type.
For Each z in x
~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'x')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvalidOperation (OperationKind.Invalid, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Children(0)
Next (Regular) Block[B3]
Entering: {R1}
.locals {R1}
{
Locals: [z As System.Object]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(DelegateRelaxationLevelNone)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
Children(0)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R1}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_15()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M() 'BIND:"Sub M"
For Each If(GetC(), Me).F in Me
Next
End Sub
Public F As C
Public ReadOnly Property Current As C
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
Module Ext
<Runtime.CompilerServices.Extension>
Public Function GetEnumerator(this As C) As C
Return this
End Function
End Module
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B6]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC()')
Value:
IInvocationOperation (Function C.GetC() As C) (OperationKind.Invocation, Type: C) (Syntax: 'GetC()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B5]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'GetC()')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC()')
Leaving: {R3}
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC()')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC()')
Next (Regular) Block[B6]
Leaving: {R3}
}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me).F')
Left:
IFieldReferenceOperation: C.F As C (OperationKind.FieldReference, Type: C) (Syntax: 'If(GetC(), Me).F')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me)')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'If(GetC(), Me).F')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_16()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As System.Collections.IEnumerable, result As Object) 'BIND:"Sub M"
For Each z in x
result = z
Next
End Sub
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation (virtual Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Collections.IEnumerable) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Entering: {R2} {R3}
.try {R2, R3}
{
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B7]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Finalizing: {R5}
Leaving: {R3} {R2} {R1}
Next (Regular) Block[B3]
Entering: {R4}
.locals {R4}
{
Locals: [z As System.Object]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Right:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R4}
}
}
.finally {R5}
{
CaptureIds: [1]
Block[B4] - Block
Predecessors (0)
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(NarrowingReference)
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Jump if True (Regular) to Block[B6]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IInvocationOperation (virtual Sub System.IDisposable.Dispose()) (OperationKind.Invocation, Type: System.Void, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.IDisposable, IsImplicit) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B4] [B5]
Statements (0)
Next (StructuredExceptionHandling) Block[null]
}
}
Block[B7] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_17()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As Integer(), result As Long) 'BIND:"Sub M"
For Each z As Long in x
result = z
Next
End Sub
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function System.Array.GetEnumerator() As System.Collections.IEnumerator) (OperationKind.Invocation, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32()) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation (virtual Function System.Collections.IEnumerator.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int64]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NarrowingValue)
Operand:
IPropertyReferenceOperation: ReadOnly Property System.Collections.IEnumerator.Current As System.Object (OperationKind.PropertyReference, Type: System.Object, IsImplicit) (Syntax: 'z As Long')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Collections.IEnumerator, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = z')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64, IsImplicit) (Syntax: 'result = z')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
Right:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'z')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_18()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(result as Boolean) 'BIND:"Sub M"
For Each x in Me
If x
Continue For
End If
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Boolean
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3] [B4]
Statements (0)
Jump if False (Regular) to Block[B5]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [x As System.Boolean]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Jump if False (Regular) to Block[B4]
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B5] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_19()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(result as Boolean) 'BIND:"Sub M"
For Each x in Me
If x
Exit For
End If
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Boolean
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B4]
Statements (0)
Jump if False (Regular) to Block[B5]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [x As System.Boolean]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Jump if False (Regular) to Block[B4]
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B5]
Leaving: {R2} {R1}
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B5] - Exit
Predecessors: [B2] [B3]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_20()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(y as Boolean, result as Boolean) 'BIND:"Sub M"
For Each x in Me
While y
result = y
Continue For
End While
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Boolean
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B4] [B5]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [x As System.Boolean]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = y')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = y')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B2]
Leaving: {R2}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B6] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_21()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(y as Boolean, result as Boolean) 'BIND:"Sub M"
For Each x in Me
While y
result = y
Exit For
End While
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Boolean
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'Me')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me')
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B5]
Statements (0)
Jump if False (Regular) to Block[B6]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'Me')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [x As System.Boolean]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Boolean (OperationKind.PropertyReference, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'Me')
Jump if False (Regular) to Block[B5]
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = y')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = y')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y')
Next (Regular) Block[B6]
Leaving: {R2} {R1}
Block[B5] - Block
Predecessors: [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B6] - Exit
Predecessors: [B2] [B4]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_22()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M() 'BIND:"Sub M"
For Each z As Long in If(GetC(), GetC())
Next
End Sub
Shared Function GetC() As C
Return Nothing
End Function
Shared Function GetEnumerator() As C
Return Nothing
End Function
Shared Function MoveNext() As Boolean
Return Nothing
End Function
Shared ReadOnly Property Current As Integer
Get
Return 1
End Get
End Property
End Class]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
For Each z As Long in If(GetC(), GetC())
~~~~~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
For Each z As Long in If(GetC(), GetC())
~~~~~~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
For Each z As Long in If(GetC(), GetC())
~~~~~~~~~~~~~~~~~~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'If(GetC(), GetC())')
Value:
IInvocationOperation (Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'If(GetC(), GetC())')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation (Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'If(GetC(), GetC())')
Instance Receiver:
null
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int64]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z As Long')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'z As Long')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNumeric)
Operand:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z As Long')
Instance Receiver:
null
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_23()
Dim source = <![CDATA[
Imports System
Public Class C
Sub M(x As C) 'BIND:"Sub M"
For Each z in x
Next
End Sub
Function GetEnumerator(<System.Runtime.CompilerServices.CallerMemberName> Optional member As String = "") As C
Return Nothing
End Function
Function MoveNext(Optional s As String = "ABC") As Boolean
Return Nothing
End Function
ReadOnly Property Current(Optional d As Double = 123.45) As Integer
Get
Return 1
End Get
End Property
End Class]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function C.GetEnumerator([member As System.String = ""]) As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x')
Arguments(1):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: member) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "M", IsImplicit) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation ( Function C.MoveNext([s As System.String = "ABC"]) As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x')
Arguments(1):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: s) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "ABC", IsImplicit) (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)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R2}
.locals {R2}
{
Locals: [z As System.Int32]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current([d As System.Double = 123.45]) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'z')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x')
Arguments(1):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: d) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 123.45, IsImplicit) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Next (Regular) Block[B2]
Leaving: {R2}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics, useLatestFramework:=True)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_24()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(result as Integer) 'BIND:"Sub M"
For Each x As Integer in GetC(x)
result = x
Next
End Sub
Public Function GetC(ByRef x as Integer) As C
Return Me
End Function
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As Integer
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = String.Empty
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [0]
.locals {R2}
{
Locals: [x As System.Int32]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'GetC(x)')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'GetC(x)')
Instance Receiver:
IInvocationOperation ( Function C.GetC(ByRef x As System.Int32) As C) (OperationKind.Invocation, Type: C) (Syntax: 'GetC(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'GetC')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'GetC(x)')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC(x)')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R3}
.locals {R3}
{
Locals: [x As System.Int32]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x As Integer')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x As Integer')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'GetC(x)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R3}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub ForEachFlow_25()
Dim source = <![CDATA[
Imports System
Public NotInheritable Class C
Sub M(result as C) 'BIND:"Sub M"
For Each x As C in x
result = x
Next
End Sub
Public Function GetEnumerator() As C
Return Me
End Function
Public ReadOnly Property Current As C
Get
Return Nothing
End Get
End Property
Public Function MoveNext() As Boolean
Return False
End Function
Public Shared Function GetC() As C
Return Nothing
End Function
End Class
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
For Each x As C in x
~
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [0]
.locals {R2}
{
Locals: [x As C]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x')
Value:
IInvocationOperation ( Function C.GetEnumerator() As C) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'x')
Instance Receiver:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x')
Arguments(0)
Next (Regular) Block[B2]
Leaving: {R2}
}
Block[B2] - Block
Predecessors: [B1] [B3]
Statements (0)
Jump if False (Regular) to Block[B4]
IInvocationOperation ( Function C.MoveNext() As System.Boolean) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'x')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x')
Arguments(0)
Leaving: {R1}
Next (Regular) Block[B3]
Entering: {R3}
.locals {R3}
{
Locals: [x As C]
Block[B3] - Block
Predecessors: [B2]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: null, IsImplicit) (Syntax: 'x As C')
Left:
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'x As C')
Right:
IPropertyReferenceOperation: ReadOnly Property C.Current As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'x As C')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'result = x')
Left:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x')
Next (Regular) Block[B2]
Leaving: {R3}
}
}
Block[B4] - Exit
Predecessors: [B2]
Statements (0)
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/Remote/Core/ExternalAccess/Pythia/Api/PythiaPinnedSolutionInfoWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
[DataContract]
internal readonly struct PythiaPinnedSolutionInfoWrapper
{
[DataMember(Order = 0)]
internal readonly PinnedSolutionInfo UnderlyingObject;
public PythiaPinnedSolutionInfoWrapper(PinnedSolutionInfo underlyingObject)
=> UnderlyingObject = underlyingObject;
public static implicit operator PythiaPinnedSolutionInfoWrapper(PinnedSolutionInfo info)
=> new(info);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
[DataContract]
internal readonly struct PythiaPinnedSolutionInfoWrapper
{
[DataMember(Order = 0)]
internal readonly PinnedSolutionInfo UnderlyingObject;
public PythiaPinnedSolutionInfoWrapper(PinnedSolutionInfo underlyingObject)
=> UnderlyingObject = underlyingObject;
public static implicit operator PythiaPinnedSolutionInfoWrapper(PinnedSolutionInfo info)
=> new(info);
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Analyzers/CSharp/Tests/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionFixAllTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertSwitchStatementToExpression
{
using VerifyCS = CSharpCodeFixVerifier<
ConvertSwitchStatementToExpressionDiagnosticAnalyzer,
ConvertSwitchStatementToExpressionCodeFixProvider>;
public class ConvertSwitchStatementToExpressionFixAllTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_01()
{
await VerifyCS.VerifyCodeFixAsync(
@"class Program
{
int M(int i, int j)
{
int r;
[|switch|] (i)
{
case 1:
r = 1;
break;
case 2:
r = 2;
break;
case 3:
r = 3;
break;
default:
r = 4;
break;
}
int x, y;
switch (i)
{
case 1:
x = 1;
y = 1;
break;
case 2:
x = 1;
y = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = 1;
break;
}
[|switch|] (i)
{
default:
throw null;
case 1:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
}
return 0;
case 2:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
case var _:
return 0;
}
case 3:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
case var v:
return 0;
}
}
}
}",
@"class Program
{
int M(int i, int j)
{
var r = i switch
{
1 => 1,
2 => 2,
3 => 3,
_ => 4,
};
int x, y;
switch (i)
{
case 1:
x = 1;
y = 1;
break;
case 2:
x = 1;
y = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = 1;
break;
}
return i switch
{
1 => j switch
{
10 => 10,
20 => 20,
30 => 30,
_ => 0,
},
2 => j switch
{
10 => 10,
20 => 20,
30 => 30,
var _ => 0,
},
3 => j switch
{
10 => 10,
20 => 20,
30 => 30,
var v => 0,
},
_ => throw null,
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_02()
{
var input = @"class Program
{
System.Func<int> M(int i, int j)
{
[|switch|] (i)
{
// 1
default: // 2
return () =>
{
[|switch|] (j)
{
default:
return 3;
}
};
}
}
}";
var expected = @"class Program
{
System.Func<int> M(int i, int j)
{
return i switch
{
// 1
// 2
_ => () =>
{
return j switch
{
_ => 3,
};
}
,
};
}
}";
await new VerifyCS.Test
{
TestCode = input,
FixedCode = expected,
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[WorkItem(37907, "https://github.com/dotnet/roslyn/issues/37907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_03()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
class Program
{
public static void Main() { }
public DayOfWeek StatusValue() => DayOfWeek.Monday;
public short Value => 0;
public bool ValueBoolean()
{
bool value;
[|switch|] (StatusValue())
{
case DayOfWeek.Monday:
[|switch|] (Value)
{
case 0:
value = false;
break;
case 1:
value = true;
break;
default:
throw new Exception();
}
break;
default:
throw new Exception();
}
return value;
}
}",
@"using System;
class Program
{
public static void Main() { }
public DayOfWeek StatusValue() => DayOfWeek.Monday;
public short Value => 0;
public bool ValueBoolean()
{
var value = StatusValue() switch
{
DayOfWeek.Monday => Value switch
{
0 => false,
1 => true,
_ => throw new Exception(),
},
_ => throw new Exception(),
};
return value;
}
}");
}
[WorkItem(44572, "https://github.com/dotnet/roslyn/issues/44572")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestImplicitConversion()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
class C
{
public C(String s) => _s = s;
private readonly String _s;
public static implicit operator String(C value) => value._s;
public static implicit operator C(String value) => new C(value);
public bool method(C c)
{
[|switch|] (c)
{
case ""A"": return true;
default: return false;
}
}
}",
@"using System;
class C
{
public C(String s) => _s = s;
private readonly String _s;
public static implicit operator String(C value) => value._s;
public static implicit operator C(String value) => new C(value);
public bool method(C c)
{
return (string)c switch
{
""A"" => true,
_ => false,
};
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertSwitchStatementToExpression
{
using VerifyCS = CSharpCodeFixVerifier<
ConvertSwitchStatementToExpressionDiagnosticAnalyzer,
ConvertSwitchStatementToExpressionCodeFixProvider>;
public class ConvertSwitchStatementToExpressionFixAllTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_01()
{
await VerifyCS.VerifyCodeFixAsync(
@"class Program
{
int M(int i, int j)
{
int r;
[|switch|] (i)
{
case 1:
r = 1;
break;
case 2:
r = 2;
break;
case 3:
r = 3;
break;
default:
r = 4;
break;
}
int x, y;
switch (i)
{
case 1:
x = 1;
y = 1;
break;
case 2:
x = 1;
y = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = 1;
break;
}
[|switch|] (i)
{
default:
throw null;
case 1:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
}
return 0;
case 2:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
case var _:
return 0;
}
case 3:
[|switch|] (j)
{
case 10:
return 10;
case 20:
return 20;
case 30:
return 30;
case var v:
return 0;
}
}
}
}",
@"class Program
{
int M(int i, int j)
{
var r = i switch
{
1 => 1,
2 => 2,
3 => 3,
_ => 4,
};
int x, y;
switch (i)
{
case 1:
x = 1;
y = 1;
break;
case 2:
x = 1;
y = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = 1;
break;
}
return i switch
{
1 => j switch
{
10 => 10,
20 => 20,
30 => 30,
_ => 0,
},
2 => j switch
{
10 => 10,
20 => 20,
30 => 30,
var _ => 0,
},
3 => j switch
{
10 => 10,
20 => 20,
30 => 30,
var v => 0,
},
_ => throw null,
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_02()
{
var input = @"class Program
{
System.Func<int> M(int i, int j)
{
[|switch|] (i)
{
// 1
default: // 2
return () =>
{
[|switch|] (j)
{
default:
return 3;
}
};
}
}
}";
var expected = @"class Program
{
System.Func<int> M(int i, int j)
{
return i switch
{
// 1
// 2
_ => () =>
{
return j switch
{
_ => 3,
};
}
,
};
}
}";
await new VerifyCS.Test
{
TestCode = input,
FixedCode = expected,
NumberOfFixAllIterations = 2,
}.RunAsync();
}
[WorkItem(37907, "https://github.com/dotnet/roslyn/issues/37907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestNested_03()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
class Program
{
public static void Main() { }
public DayOfWeek StatusValue() => DayOfWeek.Monday;
public short Value => 0;
public bool ValueBoolean()
{
bool value;
[|switch|] (StatusValue())
{
case DayOfWeek.Monday:
[|switch|] (Value)
{
case 0:
value = false;
break;
case 1:
value = true;
break;
default:
throw new Exception();
}
break;
default:
throw new Exception();
}
return value;
}
}",
@"using System;
class Program
{
public static void Main() { }
public DayOfWeek StatusValue() => DayOfWeek.Monday;
public short Value => 0;
public bool ValueBoolean()
{
var value = StatusValue() switch
{
DayOfWeek.Monday => Value switch
{
0 => false,
1 => true,
_ => throw new Exception(),
},
_ => throw new Exception(),
};
return value;
}
}");
}
[WorkItem(44572, "https://github.com/dotnet/roslyn/issues/44572")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertSwitchStatementToExpression)]
public async Task TestImplicitConversion()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
class C
{
public C(String s) => _s = s;
private readonly String _s;
public static implicit operator String(C value) => value._s;
public static implicit operator C(String value) => new C(value);
public bool method(C c)
{
[|switch|] (c)
{
case ""A"": return true;
default: return false;
}
}
}",
@"using System;
class C
{
public C(String s) => _s = s;
private readonly String _s;
public static implicit operator String(C value) => value._s;
public static implicit operator C(String value) => new C(value);
public bool method(C c)
{
return (string)c switch
{
""A"" => true,
_ => false,
};
}
}");
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelObject_CodeGen.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
/// <summary>
/// This is the root class for all code model objects. It contains methods that
/// are common to everything.
/// </summary>
public partial class AbstractCodeModelObject
{
private static CodeGenerationOptions GetCodeGenerationOptions(
EnvDTE.vsCMAccess access, ParseOptions parseOptions, OptionSet options)
{
var generateDefaultAccessibility = (access & EnvDTE.vsCMAccess.vsCMAccessDefault) == 0;
return new CodeGenerationOptions(
generateDefaultAccessibility: generateDefaultAccessibility,
parseOptions: parseOptions,
options: options);
}
protected SyntaxNode CreateConstructorDeclaration(SyntaxNode containerNode, string typeName, EnvDTE.vsCMAccess access)
{
var destination = CodeModelService.GetDestination(containerNode);
var newMethodSymbol = CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination),
modifiers: new DeclarationModifiers(),
typeName: typeName,
parameters: default);
return CodeGenerationService.CreateMethodDeclaration(
newMethodSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
protected SyntaxNode CreateDestructorDeclaration(SyntaxNode containerNode, string typeName)
{
var destination = CodeModelService.GetDestination(containerNode);
var newMethodSymbol = CodeGenerationSymbolFactory.CreateDestructorSymbol(
attributes: default,
typeName: typeName);
return CodeGenerationService.CreateMethodDeclaration(
newMethodSymbol, destination);
}
protected SyntaxNode CreateDelegateTypeDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, INamedTypeSymbol returnType)
{
var destination = CodeModelService.GetDestination(containerNode);
var newTypeSymbol = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination),
modifiers: new DeclarationModifiers(),
returnType: returnType,
refKind: RefKind.None,
name: name);
return CodeGenerationService.CreateNamedTypeDeclaration(
newTypeSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
protected SyntaxNode CreateEventDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type, bool createPropertyStyleEvent)
{
var destination = CodeModelService.GetDestination(containerNode);
IMethodSymbol addMethod = null;
IMethodSymbol removeMethod = null;
if (createPropertyStyleEvent)
{
addMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
returnType: null,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: "add_" + name,
typeParameters: default,
parameters: default);
removeMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
returnType: null,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: "remove_" + name,
typeParameters: default,
parameters: default);
}
var newEventSymbol = CodeGenerationSymbolFactory.CreateEventSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Event, destination),
modifiers: new DeclarationModifiers(),
type: type,
explicitInterfaceImplementations: default,
name: name,
addMethod: addMethod,
removeMethod: removeMethod);
return CodeGenerationService.CreateEventDeclaration(
newEventSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
protected SyntaxNode CreateFieldDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type)
{
var destination = CodeModelService.GetDestination(containerNode);
var newFieldSymbol = CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination),
modifiers: new DeclarationModifiers(isWithEvents: CodeModelService.GetWithEvents(access)),
type: type,
name: name);
return CodeGenerationService.CreateFieldDeclaration(
newFieldSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
protected SyntaxNode CreateMethodDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol returnType)
{
var destination = CodeModelService.GetDestination(containerNode);
var newMethodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination),
modifiers: new DeclarationModifiers(),
returnType: returnType,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: name,
typeParameters: default,
parameters: default);
var codeGenerationOptions = GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null);
if (destination == CodeGenerationDestination.InterfaceType)
{
// Generating method with body is allowed when targeting an interface,
// so we have to explicitly disable it here.
codeGenerationOptions = codeGenerationOptions.With(generateMethodBodies: false);
}
return CodeGenerationService.CreateMethodDeclaration(
newMethodSymbol, destination,
options: codeGenerationOptions);
}
protected SyntaxNode CreatePropertyDeclaration(
SyntaxNode containerNode,
string name,
bool generateGetter,
bool generateSetter,
EnvDTE.vsCMAccess access,
ITypeSymbol type,
OptionSet options)
{
var destination = CodeModelService.GetDestination(containerNode);
IMethodSymbol getMethod = null;
if (generateGetter)
{
getMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
returnType: null,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: "get_" + name,
typeParameters: default,
parameters: default,
statements: ImmutableArray.Create(CodeModelService.CreateReturnDefaultValueStatement(type)));
}
IMethodSymbol setMethod = null;
if (generateSetter)
{
setMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
returnType: null,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: "set_" + name,
typeParameters: default,
parameters: default);
}
var newPropertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination),
modifiers: new DeclarationModifiers(),
type: type,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: name,
parameters: default,
getMethod: getMethod,
setMethod: setMethod);
return CodeGenerationService.CreatePropertyDeclaration(
newPropertySymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options));
}
protected SyntaxNode CreateNamespaceDeclaration(SyntaxNode containerNode, string name)
{
var destination = CodeModelService.GetDestination(containerNode);
var newNamespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name);
var newNamespace = CodeGenerationService.CreateNamespaceDeclaration(
newNamespaceSymbol, destination);
return newNamespace;
}
protected SyntaxNode CreateTypeDeclaration(
SyntaxNode containerNode,
TypeKind typeKind,
string name,
EnvDTE.vsCMAccess access,
INamedTypeSymbol baseType = null,
ImmutableArray<INamedTypeSymbol> implementedInterfaces = default)
{
var destination = CodeModelService.GetDestination(containerNode);
var newTypeSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination),
modifiers: new DeclarationModifiers(),
typeKind: typeKind,
name: name,
typeParameters: default,
baseType: baseType,
interfaces: implementedInterfaces,
specialType: SpecialType.None,
members: default);
return CodeGenerationService.CreateNamedTypeDeclaration(
newTypeSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
/// <summary>
/// This is the root class for all code model objects. It contains methods that
/// are common to everything.
/// </summary>
public partial class AbstractCodeModelObject
{
private static CodeGenerationOptions GetCodeGenerationOptions(
EnvDTE.vsCMAccess access, ParseOptions parseOptions, OptionSet options)
{
var generateDefaultAccessibility = (access & EnvDTE.vsCMAccess.vsCMAccessDefault) == 0;
return new CodeGenerationOptions(
generateDefaultAccessibility: generateDefaultAccessibility,
parseOptions: parseOptions,
options: options);
}
protected SyntaxNode CreateConstructorDeclaration(SyntaxNode containerNode, string typeName, EnvDTE.vsCMAccess access)
{
var destination = CodeModelService.GetDestination(containerNode);
var newMethodSymbol = CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination),
modifiers: new DeclarationModifiers(),
typeName: typeName,
parameters: default);
return CodeGenerationService.CreateMethodDeclaration(
newMethodSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
protected SyntaxNode CreateDestructorDeclaration(SyntaxNode containerNode, string typeName)
{
var destination = CodeModelService.GetDestination(containerNode);
var newMethodSymbol = CodeGenerationSymbolFactory.CreateDestructorSymbol(
attributes: default,
typeName: typeName);
return CodeGenerationService.CreateMethodDeclaration(
newMethodSymbol, destination);
}
protected SyntaxNode CreateDelegateTypeDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, INamedTypeSymbol returnType)
{
var destination = CodeModelService.GetDestination(containerNode);
var newTypeSymbol = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination),
modifiers: new DeclarationModifiers(),
returnType: returnType,
refKind: RefKind.None,
name: name);
return CodeGenerationService.CreateNamedTypeDeclaration(
newTypeSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
protected SyntaxNode CreateEventDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type, bool createPropertyStyleEvent)
{
var destination = CodeModelService.GetDestination(containerNode);
IMethodSymbol addMethod = null;
IMethodSymbol removeMethod = null;
if (createPropertyStyleEvent)
{
addMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
returnType: null,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: "add_" + name,
typeParameters: default,
parameters: default);
removeMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
returnType: null,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: "remove_" + name,
typeParameters: default,
parameters: default);
}
var newEventSymbol = CodeGenerationSymbolFactory.CreateEventSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Event, destination),
modifiers: new DeclarationModifiers(),
type: type,
explicitInterfaceImplementations: default,
name: name,
addMethod: addMethod,
removeMethod: removeMethod);
return CodeGenerationService.CreateEventDeclaration(
newEventSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
protected SyntaxNode CreateFieldDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type)
{
var destination = CodeModelService.GetDestination(containerNode);
var newFieldSymbol = CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination),
modifiers: new DeclarationModifiers(isWithEvents: CodeModelService.GetWithEvents(access)),
type: type,
name: name);
return CodeGenerationService.CreateFieldDeclaration(
newFieldSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
protected SyntaxNode CreateMethodDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol returnType)
{
var destination = CodeModelService.GetDestination(containerNode);
var newMethodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination),
modifiers: new DeclarationModifiers(),
returnType: returnType,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: name,
typeParameters: default,
parameters: default);
var codeGenerationOptions = GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null);
if (destination == CodeGenerationDestination.InterfaceType)
{
// Generating method with body is allowed when targeting an interface,
// so we have to explicitly disable it here.
codeGenerationOptions = codeGenerationOptions.With(generateMethodBodies: false);
}
return CodeGenerationService.CreateMethodDeclaration(
newMethodSymbol, destination,
options: codeGenerationOptions);
}
protected SyntaxNode CreatePropertyDeclaration(
SyntaxNode containerNode,
string name,
bool generateGetter,
bool generateSetter,
EnvDTE.vsCMAccess access,
ITypeSymbol type,
OptionSet options)
{
var destination = CodeModelService.GetDestination(containerNode);
IMethodSymbol getMethod = null;
if (generateGetter)
{
getMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
returnType: null,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: "get_" + name,
typeParameters: default,
parameters: default,
statements: ImmutableArray.Create(CodeModelService.CreateReturnDefaultValueStatement(type)));
}
IMethodSymbol setMethod = null;
if (generateSetter)
{
setMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default,
accessibility: Accessibility.NotApplicable,
modifiers: new DeclarationModifiers(),
returnType: null,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: "set_" + name,
typeParameters: default,
parameters: default);
}
var newPropertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination),
modifiers: new DeclarationModifiers(),
type: type,
refKind: RefKind.None,
explicitInterfaceImplementations: default,
name: name,
parameters: default,
getMethod: getMethod,
setMethod: setMethod);
return CodeGenerationService.CreatePropertyDeclaration(
newPropertySymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options));
}
protected SyntaxNode CreateNamespaceDeclaration(SyntaxNode containerNode, string name)
{
var destination = CodeModelService.GetDestination(containerNode);
var newNamespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name);
var newNamespace = CodeGenerationService.CreateNamespaceDeclaration(
newNamespaceSymbol, destination);
return newNamespace;
}
protected SyntaxNode CreateTypeDeclaration(
SyntaxNode containerNode,
TypeKind typeKind,
string name,
EnvDTE.vsCMAccess access,
INamedTypeSymbol baseType = null,
ImmutableArray<INamedTypeSymbol> implementedInterfaces = default)
{
var destination = CodeModelService.GetDestination(containerNode);
var newTypeSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
attributes: default,
accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination),
modifiers: new DeclarationModifiers(),
typeKind: typeKind,
name: name,
typeParameters: default,
baseType: baseType,
interfaces: implementedInterfaces,
specialType: SpecialType.None,
members: default);
return CodeGenerationService.CreateNamedTypeDeclaration(
newTypeSymbol, destination,
options: GetCodeGenerationOptions(
access, containerNode.SyntaxTree.Options, options: null));
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/VisualStudio/LiveShare/Impl/CustomProtocol/RoslynMethods.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CustomProtocol
{
internal static class RoslynMethods
{
public const string ProjectsName = "roslyn/projects";
public const string ClassificationsName = "roslyn/classifications";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol
{
internal static class RoslynMethods
{
public const string ProjectsName = "roslyn/projects";
public const string ClassificationsName = "roslyn/classifications";
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./THIRD-PARTY-NOTICES.txt | Roslyn uses third-party libraries or other resources that may be
distributed under licenses different than the Roslyn software.
In the event that we accidentally failed to list a required notice, please
bring it to our attention. Post an issue or email us:
[email protected]
The attached notices are provided for information only.
License notice for .NET Core Libraries (CoreFX)
-------------------------------------
https://github.com/dotnet/corefx
Copyright (c) 2018 .NET Foundation and Contributors
This software is licensed subject to the MIT license, available at
https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
License notice for DotNetTools
-------------------------------------
https://github.com/aspnet/DotNetTools
Copyright (c) .NET Foundation and Contributors
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
License notice for DocFX
-------------------------------------
https://github.com/dotnet/docfx
Copyright (c) Microsoft Corporation
This software is licensed subject to the MIT license, available at
https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
License notice for MSBuild Locator
-------------------------------------
https://github.com/Microsoft/MSBuildLocator
Copyright (c) Microsoft Corporation. All rights reserved.
This software is licensed subject to the MIT license, available at
https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| Roslyn uses third-party libraries or other resources that may be
distributed under licenses different than the Roslyn software.
In the event that we accidentally failed to list a required notice, please
bring it to our attention. Post an issue or email us:
[email protected]
The attached notices are provided for information only.
License notice for .NET Core Libraries (CoreFX)
-------------------------------------
https://github.com/dotnet/corefx
Copyright (c) 2018 .NET Foundation and Contributors
This software is licensed subject to the MIT license, available at
https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
License notice for DotNetTools
-------------------------------------
https://github.com/aspnet/DotNetTools
Copyright (c) .NET Foundation and Contributors
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
License notice for DocFX
-------------------------------------
https://github.com/dotnet/docfx
Copyright (c) Microsoft Corporation
This software is licensed subject to the MIT license, available at
https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
License notice for MSBuild Locator
-------------------------------------
https://github.com/Microsoft/MSBuildLocator
Copyright (c) Microsoft Corporation. All rights reserved.
This software is licensed subject to the MIT license, available at
https://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/Test/Core/Mocks/TestStream.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Roslyn.Test.Utilities
{
public class TestStream : Stream
{
private readonly bool? _canRead, _canSeek, _canWrite;
private readonly Func<byte[], int, int, int> _readFunc;
private readonly long? _length;
private readonly Func<long> _getPosition;
private readonly Action<long> _setPosition;
private readonly Stream _backingStream;
private readonly Action _dispose;
public TestStream(
bool? canRead = null,
bool? canSeek = null,
bool? canWrite = null,
Func<byte[], int, int, int> readFunc = null,
long? length = null,
Func<long> getPosition = null,
Action<long> setPosition = null,
Stream backingStream = null,
Action dispose = null)
{
_canRead = canRead;
_canSeek = canSeek;
_canWrite = canWrite;
_readFunc = readFunc;
_length = length;
_getPosition = getPosition;
_setPosition = setPosition;
_backingStream = backingStream;
_dispose = dispose;
}
public override bool CanRead => _canRead ?? _backingStream?.CanRead ?? false;
public override bool CanSeek => _canSeek ?? _backingStream?.CanSeek ?? false;
public override bool CanWrite => _canWrite ?? _backingStream?.CanWrite ?? false;
public override long Length => _length ?? _backingStream?.Length ?? 0;
public override long Position
{
get
{
if (!CanSeek)
throw new NotSupportedException();
if (_getPosition != null)
{
return _getPosition();
}
if (_backingStream != null)
{
return _backingStream.Position;
}
throw new NotImplementedException();
}
set
{
if (!CanSeek)
{
throw new NotSupportedException();
}
if (_setPosition != null)
{
_setPosition(value);
}
else if (_backingStream != null)
{
_backingStream.Position = value;
}
else
{
throw new NotImplementedException();
}
}
}
public override void Flush()
{
if (_backingStream == null)
{
throw new NotSupportedException();
}
_backingStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_readFunc != null)
{
return _readFunc(buffer, offset, count);
}
else if (_backingStream != null)
{
return _backingStream.Read(buffer, offset, count);
}
else
{
throw new NotImplementedException();
}
}
public override long Seek(long offset, SeekOrigin origin)
{
if (!CanSeek)
{
throw new NotSupportedException();
}
return 0;
}
public override void SetLength(long value)
{
if (_backingStream == null)
{
throw new NotSupportedException();
}
_backingStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (!CanWrite)
{
throw new NotSupportedException();
}
}
protected override void Dispose(bool disposing)
{
if (_dispose != null)
{
_dispose();
}
else
{
_backingStream?.Dispose();
}
base.Dispose(disposing);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Roslyn.Test.Utilities
{
public class TestStream : Stream
{
private readonly bool? _canRead, _canSeek, _canWrite;
private readonly Func<byte[], int, int, int> _readFunc;
private readonly long? _length;
private readonly Func<long> _getPosition;
private readonly Action<long> _setPosition;
private readonly Stream _backingStream;
private readonly Action _dispose;
public TestStream(
bool? canRead = null,
bool? canSeek = null,
bool? canWrite = null,
Func<byte[], int, int, int> readFunc = null,
long? length = null,
Func<long> getPosition = null,
Action<long> setPosition = null,
Stream backingStream = null,
Action dispose = null)
{
_canRead = canRead;
_canSeek = canSeek;
_canWrite = canWrite;
_readFunc = readFunc;
_length = length;
_getPosition = getPosition;
_setPosition = setPosition;
_backingStream = backingStream;
_dispose = dispose;
}
public override bool CanRead => _canRead ?? _backingStream?.CanRead ?? false;
public override bool CanSeek => _canSeek ?? _backingStream?.CanSeek ?? false;
public override bool CanWrite => _canWrite ?? _backingStream?.CanWrite ?? false;
public override long Length => _length ?? _backingStream?.Length ?? 0;
public override long Position
{
get
{
if (!CanSeek)
throw new NotSupportedException();
if (_getPosition != null)
{
return _getPosition();
}
if (_backingStream != null)
{
return _backingStream.Position;
}
throw new NotImplementedException();
}
set
{
if (!CanSeek)
{
throw new NotSupportedException();
}
if (_setPosition != null)
{
_setPosition(value);
}
else if (_backingStream != null)
{
_backingStream.Position = value;
}
else
{
throw new NotImplementedException();
}
}
}
public override void Flush()
{
if (_backingStream == null)
{
throw new NotSupportedException();
}
_backingStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_readFunc != null)
{
return _readFunc(buffer, offset, count);
}
else if (_backingStream != null)
{
return _backingStream.Read(buffer, offset, count);
}
else
{
throw new NotImplementedException();
}
}
public override long Seek(long offset, SeekOrigin origin)
{
if (!CanSeek)
{
throw new NotSupportedException();
}
return 0;
}
public override void SetLength(long value)
{
if (_backingStream == null)
{
throw new NotSupportedException();
}
_backingStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
if (!CanWrite)
{
throw new NotSupportedException();
}
}
protected override void Dispose(bool disposing)
{
if (_dispose != null)
{
_dispose();
}
else
{
_backingStream?.Dispose();
}
base.Dispose(disposing);
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/Core/Portable/Workspace/Solution/VersionStamp.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// VersionStamp should be only used to compare versions returned by same API.
/// </summary>
public readonly struct VersionStamp : IEquatable<VersionStamp>, IObjectWritable
{
public static VersionStamp Default => default;
private const int GlobalVersionMarker = -1;
private const int InitialGlobalVersion = 10000;
/// <summary>
/// global counter to avoid collision within same session.
/// it starts with a big initial number just for a clarity in debugging
/// </summary>
private static int s_globalVersion = InitialGlobalVersion;
/// <summary>
/// time stamp
/// </summary>
private readonly DateTime _utcLastModified;
/// <summary>
/// indicate whether there was a collision on same item
/// </summary>
private readonly int _localIncrement;
/// <summary>
/// unique version in same session
/// </summary>
private readonly int _globalIncrement;
private VersionStamp(DateTime utcLastModified)
: this(utcLastModified, 0)
{
}
private VersionStamp(DateTime utcLastModified, int localIncrement)
: this(utcLastModified, localIncrement, GetNextGlobalVersion())
{
}
private VersionStamp(DateTime utcLastModified, int localIncrement, int globalIncrement)
{
if (utcLastModified != default && utcLastModified.Kind != DateTimeKind.Utc)
{
throw new ArgumentException(WorkspacesResources.DateTimeKind_must_be_Utc, nameof(utcLastModified));
}
_utcLastModified = utcLastModified;
_localIncrement = localIncrement;
_globalIncrement = globalIncrement;
}
/// <summary>
/// Creates a new instance of a VersionStamp.
/// </summary>
public static VersionStamp Create()
=> new(DateTime.UtcNow);
/// <summary>
/// Creates a new instance of a version stamp based on the specified DateTime.
/// </summary>
public static VersionStamp Create(DateTime utcTimeLastModified)
=> new(utcTimeLastModified);
/// <summary>
/// compare two different versions and return either one of the versions if there is no collision, otherwise, create a new version
/// that can be used later to compare versions between different items
/// </summary>
public VersionStamp GetNewerVersion(VersionStamp version)
{
// * NOTE *
// in current design/implementation, there are 4 possible ways for a version to be created.
//
// 1. created from a file stamp (most likely by starting a new session). "increment" will have 0 as value
// 2. created by modifying existing item (text changes, project changes etc).
// "increment" will have either 0 or previous increment + 1 if there was a collision.
// 3. created from deserialization (probably by using persistent service).
// 4. created by accumulating versions of multiple items.
//
// and this method is the one that is responsible for #4 case.
if (_utcLastModified > version._utcLastModified)
{
return this;
}
if (_utcLastModified == version._utcLastModified)
{
var thisGlobalVersion = GetGlobalVersion(this);
var thatGlobalVersion = GetGlobalVersion(version);
if (thisGlobalVersion == thatGlobalVersion)
{
// given versions are same one
return this;
}
// mark it as global version
// global version can't be moved to newer version.
return new VersionStamp(_utcLastModified, (thisGlobalVersion > thatGlobalVersion) ? thisGlobalVersion : thatGlobalVersion, GlobalVersionMarker);
}
return version;
}
/// <summary>
/// Gets a new VersionStamp that is guaranteed to be newer than its base one
/// this should only be used for same item to move it to newer version
/// </summary>
public VersionStamp GetNewerVersion()
{
// global version can't be moved to newer version
Debug.Assert(_globalIncrement != GlobalVersionMarker);
var now = DateTime.UtcNow;
var incr = (now == _utcLastModified) ? _localIncrement + 1 : 0;
return new VersionStamp(now, incr);
}
/// <summary>
/// Returns the serialized text form of the VersionStamp.
/// </summary>
public override string ToString()
{
// 'o' is the roundtrip format that captures the most detail.
return _utcLastModified.ToString("o") + "-" + _globalIncrement + "-" + _localIncrement;
}
public override int GetHashCode()
=> Hash.Combine(_utcLastModified.GetHashCode(), _localIncrement);
public override bool Equals(object? obj)
{
if (obj is VersionStamp v)
{
return this.Equals(v);
}
return false;
}
public bool Equals(VersionStamp version)
{
if (_utcLastModified == version._utcLastModified)
{
return GetGlobalVersion(this) == GetGlobalVersion(version);
}
return false;
}
public static bool operator ==(VersionStamp left, VersionStamp right)
=> left.Equals(right);
public static bool operator !=(VersionStamp left, VersionStamp right)
=> !left.Equals(right);
/// <summary>
/// Check whether given persisted version is re-usable. Used by VS for Mac
/// </summary>
internal static bool CanReusePersistedVersion(VersionStamp baseVersion, VersionStamp persistedVersion)
{
if (baseVersion == persistedVersion)
{
return true;
}
// there was a collision, we can't use these
if (baseVersion._localIncrement != 0 || persistedVersion._localIncrement != 0)
{
return false;
}
return baseVersion._utcLastModified == persistedVersion._utcLastModified;
}
bool IObjectWritable.ShouldReuseInSerialization => true;
void IObjectWritable.WriteTo(ObjectWriter writer)
=> WriteTo(writer);
internal void WriteTo(ObjectWriter writer)
{
writer.WriteInt64(_utcLastModified.ToBinary());
writer.WriteInt32(_localIncrement);
writer.WriteInt32(_globalIncrement);
}
internal static VersionStamp ReadFrom(ObjectReader reader)
{
var raw = reader.ReadInt64();
var localIncrement = reader.ReadInt32();
var globalIncrement = reader.ReadInt32();
return new VersionStamp(DateTime.FromBinary(raw), localIncrement, globalIncrement);
}
private static int GetGlobalVersion(VersionStamp version)
{
// global increment < 0 means it is a global version which has its global increment in local increment
return version._globalIncrement >= 0 ? version._globalIncrement : version._localIncrement;
}
private static int GetNextGlobalVersion()
{
// REVIEW: not sure what is best way to wrap it when it overflows. should I just throw or don't care.
// with 50ms (typing) as an interval for a new version, it gives more than 1 year before int32 to overflow.
// with 5ms as an interval, it gives more than 120 days before it overflows.
// since global version is only for per VS session, I think we don't need to worry about overflow.
// or we could use Int64 which will give more than a million years turn around even on 1ms interval.
// this will let versions to be compared safely between multiple items
// without worrying about collision within same session
var globalVersion = Interlocked.Increment(ref VersionStamp.s_globalVersion);
return globalVersion;
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly VersionStamp _versionStamp;
public TestAccessor(in VersionStamp versionStamp)
=> _versionStamp = versionStamp;
/// <summary>
/// True if this VersionStamp is newer than the specified one.
/// </summary>
internal bool IsNewerThan(in VersionStamp version)
{
if (_versionStamp._utcLastModified > version._utcLastModified)
{
return true;
}
if (_versionStamp._utcLastModified == version._utcLastModified)
{
return GetGlobalVersion(_versionStamp) > GetGlobalVersion(version);
}
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.Diagnostics;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// VersionStamp should be only used to compare versions returned by same API.
/// </summary>
public readonly struct VersionStamp : IEquatable<VersionStamp>, IObjectWritable
{
public static VersionStamp Default => default;
private const int GlobalVersionMarker = -1;
private const int InitialGlobalVersion = 10000;
/// <summary>
/// global counter to avoid collision within same session.
/// it starts with a big initial number just for a clarity in debugging
/// </summary>
private static int s_globalVersion = InitialGlobalVersion;
/// <summary>
/// time stamp
/// </summary>
private readonly DateTime _utcLastModified;
/// <summary>
/// indicate whether there was a collision on same item
/// </summary>
private readonly int _localIncrement;
/// <summary>
/// unique version in same session
/// </summary>
private readonly int _globalIncrement;
private VersionStamp(DateTime utcLastModified)
: this(utcLastModified, 0)
{
}
private VersionStamp(DateTime utcLastModified, int localIncrement)
: this(utcLastModified, localIncrement, GetNextGlobalVersion())
{
}
private VersionStamp(DateTime utcLastModified, int localIncrement, int globalIncrement)
{
if (utcLastModified != default && utcLastModified.Kind != DateTimeKind.Utc)
{
throw new ArgumentException(WorkspacesResources.DateTimeKind_must_be_Utc, nameof(utcLastModified));
}
_utcLastModified = utcLastModified;
_localIncrement = localIncrement;
_globalIncrement = globalIncrement;
}
/// <summary>
/// Creates a new instance of a VersionStamp.
/// </summary>
public static VersionStamp Create()
=> new(DateTime.UtcNow);
/// <summary>
/// Creates a new instance of a version stamp based on the specified DateTime.
/// </summary>
public static VersionStamp Create(DateTime utcTimeLastModified)
=> new(utcTimeLastModified);
/// <summary>
/// compare two different versions and return either one of the versions if there is no collision, otherwise, create a new version
/// that can be used later to compare versions between different items
/// </summary>
public VersionStamp GetNewerVersion(VersionStamp version)
{
// * NOTE *
// in current design/implementation, there are 4 possible ways for a version to be created.
//
// 1. created from a file stamp (most likely by starting a new session). "increment" will have 0 as value
// 2. created by modifying existing item (text changes, project changes etc).
// "increment" will have either 0 or previous increment + 1 if there was a collision.
// 3. created from deserialization (probably by using persistent service).
// 4. created by accumulating versions of multiple items.
//
// and this method is the one that is responsible for #4 case.
if (_utcLastModified > version._utcLastModified)
{
return this;
}
if (_utcLastModified == version._utcLastModified)
{
var thisGlobalVersion = GetGlobalVersion(this);
var thatGlobalVersion = GetGlobalVersion(version);
if (thisGlobalVersion == thatGlobalVersion)
{
// given versions are same one
return this;
}
// mark it as global version
// global version can't be moved to newer version.
return new VersionStamp(_utcLastModified, (thisGlobalVersion > thatGlobalVersion) ? thisGlobalVersion : thatGlobalVersion, GlobalVersionMarker);
}
return version;
}
/// <summary>
/// Gets a new VersionStamp that is guaranteed to be newer than its base one
/// this should only be used for same item to move it to newer version
/// </summary>
public VersionStamp GetNewerVersion()
{
// global version can't be moved to newer version
Debug.Assert(_globalIncrement != GlobalVersionMarker);
var now = DateTime.UtcNow;
var incr = (now == _utcLastModified) ? _localIncrement + 1 : 0;
return new VersionStamp(now, incr);
}
/// <summary>
/// Returns the serialized text form of the VersionStamp.
/// </summary>
public override string ToString()
{
// 'o' is the roundtrip format that captures the most detail.
return _utcLastModified.ToString("o") + "-" + _globalIncrement + "-" + _localIncrement;
}
public override int GetHashCode()
=> Hash.Combine(_utcLastModified.GetHashCode(), _localIncrement);
public override bool Equals(object? obj)
{
if (obj is VersionStamp v)
{
return this.Equals(v);
}
return false;
}
public bool Equals(VersionStamp version)
{
if (_utcLastModified == version._utcLastModified)
{
return GetGlobalVersion(this) == GetGlobalVersion(version);
}
return false;
}
public static bool operator ==(VersionStamp left, VersionStamp right)
=> left.Equals(right);
public static bool operator !=(VersionStamp left, VersionStamp right)
=> !left.Equals(right);
/// <summary>
/// Check whether given persisted version is re-usable. Used by VS for Mac
/// </summary>
internal static bool CanReusePersistedVersion(VersionStamp baseVersion, VersionStamp persistedVersion)
{
if (baseVersion == persistedVersion)
{
return true;
}
// there was a collision, we can't use these
if (baseVersion._localIncrement != 0 || persistedVersion._localIncrement != 0)
{
return false;
}
return baseVersion._utcLastModified == persistedVersion._utcLastModified;
}
bool IObjectWritable.ShouldReuseInSerialization => true;
void IObjectWritable.WriteTo(ObjectWriter writer)
=> WriteTo(writer);
internal void WriteTo(ObjectWriter writer)
{
writer.WriteInt64(_utcLastModified.ToBinary());
writer.WriteInt32(_localIncrement);
writer.WriteInt32(_globalIncrement);
}
internal static VersionStamp ReadFrom(ObjectReader reader)
{
var raw = reader.ReadInt64();
var localIncrement = reader.ReadInt32();
var globalIncrement = reader.ReadInt32();
return new VersionStamp(DateTime.FromBinary(raw), localIncrement, globalIncrement);
}
private static int GetGlobalVersion(VersionStamp version)
{
// global increment < 0 means it is a global version which has its global increment in local increment
return version._globalIncrement >= 0 ? version._globalIncrement : version._localIncrement;
}
private static int GetNextGlobalVersion()
{
// REVIEW: not sure what is best way to wrap it when it overflows. should I just throw or don't care.
// with 50ms (typing) as an interval for a new version, it gives more than 1 year before int32 to overflow.
// with 5ms as an interval, it gives more than 120 days before it overflows.
// since global version is only for per VS session, I think we don't need to worry about overflow.
// or we could use Int64 which will give more than a million years turn around even on 1ms interval.
// this will let versions to be compared safely between multiple items
// without worrying about collision within same session
var globalVersion = Interlocked.Increment(ref VersionStamp.s_globalVersion);
return globalVersion;
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly VersionStamp _versionStamp;
public TestAccessor(in VersionStamp versionStamp)
=> _versionStamp = versionStamp;
/// <summary>
/// True if this VersionStamp is newer than the specified one.
/// </summary>
internal bool IsNewerThan(in VersionStamp version)
{
if (_versionStamp._utcLastModified > version._utcLastModified)
{
return true;
}
if (_versionStamp._utcLastModified == version._utcLastModified)
{
return GetGlobalVersion(_versionStamp) > GetGlobalVersion(version);
}
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/Core/Portable/Collections/OrderPreservingMultiDictionary.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Collections
{
/// <summary>
/// A MultiDictionary that allows only adding, and preserves the order of values added to the
/// dictionary. Thread-safe for reading, but not for adding.
/// </summary>
/// <remarks>
/// Always uses the default comparer.
/// </remarks>
internal sealed class OrderPreservingMultiDictionary<K, V> :
IEnumerable<KeyValuePair<K, OrderPreservingMultiDictionary<K, V>.ValueSet>>
where K : notnull
where V : notnull
{
#region Pooling
private readonly ObjectPool<OrderPreservingMultiDictionary<K, V>>? _pool;
private OrderPreservingMultiDictionary(ObjectPool<OrderPreservingMultiDictionary<K, V>> pool)
{
_pool = pool;
}
public void Free()
{
if (_dictionary != null)
{
// Allow our ValueSets to return their underlying ArrayBuilders to the pool.
foreach (var kvp in _dictionary)
{
kvp.Value.Free();
}
_dictionary.Free();
_dictionary = null;
}
_pool?.Free(this);
}
// global pool
private static readonly ObjectPool<OrderPreservingMultiDictionary<K, V>> s_poolInstance = CreatePool();
// if someone needs to create a pool;
public static ObjectPool<OrderPreservingMultiDictionary<K, V>> CreatePool()
{
var pool = new ObjectPool<OrderPreservingMultiDictionary<K, V>>(
pool => new OrderPreservingMultiDictionary<K, V>(pool),
16); // Size is a guess.
return pool;
}
public static OrderPreservingMultiDictionary<K, V> GetInstance()
{
var instance = s_poolInstance.Allocate();
Debug.Assert(instance.IsEmpty);
return instance;
}
#endregion Pooling
// An empty dictionary we keep around to simplify certain operations (like "Keys")
// when we don't have an underlying dictionary of our own.
private static readonly Dictionary<K, ValueSet> s_emptyDictionary = new();
// The underlying dictionary we store our data in. null if we are empty.
private PooledDictionary<K, ValueSet>? _dictionary;
public OrderPreservingMultiDictionary()
{
}
private void EnsureDictionary()
{
_dictionary ??= PooledDictionary<K, ValueSet>.GetInstance();
}
public bool IsEmpty => _dictionary == null;
/// <summary>
/// Add a value to the dictionary.
/// </summary>
public void Add(K k, V v)
{
if (_dictionary is object && _dictionary.TryGetValue(k, out var valueSet))
{
Debug.Assert(valueSet.Count >= 1);
// Have to re-store the ValueSet in case we upgraded the existing ValueSet from
// holding a single item to holding multiple items.
_dictionary[k] = valueSet.WithAddedItem(v);
}
else
{
this.EnsureDictionary();
_dictionary![k] = new ValueSet(v);
}
}
public bool TryGetValue<TArg>(K key, Func<V, TArg, bool> predicate, TArg arg, [MaybeNullWhen(false)] out V value)
{
if (_dictionary is not null && _dictionary.TryGetValue(key, out var valueSet))
{
Debug.Assert(valueSet.Count >= 1);
return valueSet.TryGetValue(predicate, arg, out value);
}
value = default;
return false;
}
public Dictionary<K, ValueSet>.Enumerator GetEnumerator()
{
return _dictionary is null ? s_emptyDictionary.GetEnumerator() : _dictionary.GetEnumerator();
}
IEnumerator<KeyValuePair<K, ValueSet>> IEnumerable<KeyValuePair<K, ValueSet>>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Get all values associated with K, in the order they were added.
/// Returns empty read-only array if no values were present.
/// </summary>
public ImmutableArray<V> this[K k]
{
get
{
if (_dictionary is object && _dictionary.TryGetValue(k, out var valueSet))
{
Debug.Assert(valueSet.Count >= 1);
return valueSet.Items;
}
return ImmutableArray<V>.Empty;
}
}
public bool Contains(K key, V value)
{
return _dictionary is object &&
_dictionary.TryGetValue(key, out var valueSet) &&
valueSet.Contains(value);
}
/// <summary>
/// Get a collection of all the keys.
/// </summary>
public Dictionary<K, ValueSet>.KeyCollection Keys
{
get { return _dictionary is null ? s_emptyDictionary.Keys : _dictionary.Keys; }
}
public struct ValueSet : IEnumerable<V>
{
/// <summary>
/// Each value is either a single V or an <see cref="ArrayBuilder{V}"/>.
/// Never null.
/// </summary>
private readonly object _value;
internal ValueSet(V value)
{
_value = value;
}
internal ValueSet(ArrayBuilder<V> values)
{
_value = values;
}
internal void Free()
{
var arrayBuilder = _value as ArrayBuilder<V>;
arrayBuilder?.Free();
}
internal V this[int index]
{
get
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
if (arrayBuilder == null)
{
if (index == 0)
{
return (V)_value;
}
else
{
throw new IndexOutOfRangeException();
}
}
else
{
return arrayBuilder[index];
}
}
}
public bool TryGetValue<TArg>(Func<V, TArg, bool> predicate, TArg arg, [MaybeNullWhen(false)] out V value)
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
if (arrayBuilder is not null)
{
foreach (var v in arrayBuilder)
{
if (predicate(v, arg))
{
value = v;
return true;
}
}
}
else
{
var singleValue = (V)_value;
if (predicate(singleValue, arg))
{
value = singleValue;
return true;
}
}
value = default;
return false;
}
internal bool Contains(V item)
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
return arrayBuilder == null
? EqualityComparer<V>.Default.Equals(item, (V)_value)
: arrayBuilder.Contains(item);
}
internal ImmutableArray<V> Items
{
get
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
if (arrayBuilder == null)
{
// promote singleton to set
Debug.Assert(_value is V, "Item must be a a V");
return ImmutableArray.Create<V>((V)_value);
}
else
{
return arrayBuilder.ToImmutable();
}
}
}
internal int Count => (_value as ArrayBuilder<V>)?.Count ?? 1;
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<V> IEnumerable<V>.GetEnumerator()
{
return GetEnumerator();
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
internal ValueSet WithAddedItem(V item)
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
if (arrayBuilder == null)
{
// Promote from singleton V to ArrayBuilder<V>.
Debug.Assert(_value is V, "_value must be a V");
// By default we allocate array builders with a size of two. That's to store
// the single item already in _value, and to store the item we're adding.
// In general, we presume that the amount of values per key will be low, so this
// means we have very little overhead when there are multiple keys per value.
arrayBuilder = ArrayBuilder<V>.GetInstance(capacity: 2);
arrayBuilder.Add((V)_value);
arrayBuilder.Add(item);
}
else
{
arrayBuilder.Add(item);
}
return new ValueSet(arrayBuilder);
}
public struct Enumerator : IEnumerator<V>
{
private readonly ValueSet _valueSet;
private readonly int _count;
private int _index;
public Enumerator(ValueSet valueSet)
{
_valueSet = valueSet;
_count = _valueSet.Count;
Debug.Assert(_count >= 1);
_index = -1;
}
public V Current => _valueSet[_index];
object IEnumerator.Current => Current;
public bool MoveNext()
{
_index++;
return _index < _count;
}
public void Reset()
{
_index = -1;
}
public void Dispose()
{
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.Collections
{
/// <summary>
/// A MultiDictionary that allows only adding, and preserves the order of values added to the
/// dictionary. Thread-safe for reading, but not for adding.
/// </summary>
/// <remarks>
/// Always uses the default comparer.
/// </remarks>
internal sealed class OrderPreservingMultiDictionary<K, V> :
IEnumerable<KeyValuePair<K, OrderPreservingMultiDictionary<K, V>.ValueSet>>
where K : notnull
where V : notnull
{
#region Pooling
private readonly ObjectPool<OrderPreservingMultiDictionary<K, V>>? _pool;
private OrderPreservingMultiDictionary(ObjectPool<OrderPreservingMultiDictionary<K, V>> pool)
{
_pool = pool;
}
public void Free()
{
if (_dictionary != null)
{
// Allow our ValueSets to return their underlying ArrayBuilders to the pool.
foreach (var kvp in _dictionary)
{
kvp.Value.Free();
}
_dictionary.Free();
_dictionary = null;
}
_pool?.Free(this);
}
// global pool
private static readonly ObjectPool<OrderPreservingMultiDictionary<K, V>> s_poolInstance = CreatePool();
// if someone needs to create a pool;
public static ObjectPool<OrderPreservingMultiDictionary<K, V>> CreatePool()
{
var pool = new ObjectPool<OrderPreservingMultiDictionary<K, V>>(
pool => new OrderPreservingMultiDictionary<K, V>(pool),
16); // Size is a guess.
return pool;
}
public static OrderPreservingMultiDictionary<K, V> GetInstance()
{
var instance = s_poolInstance.Allocate();
Debug.Assert(instance.IsEmpty);
return instance;
}
#endregion Pooling
// An empty dictionary we keep around to simplify certain operations (like "Keys")
// when we don't have an underlying dictionary of our own.
private static readonly Dictionary<K, ValueSet> s_emptyDictionary = new();
// The underlying dictionary we store our data in. null if we are empty.
private PooledDictionary<K, ValueSet>? _dictionary;
public OrderPreservingMultiDictionary()
{
}
private void EnsureDictionary()
{
_dictionary ??= PooledDictionary<K, ValueSet>.GetInstance();
}
public bool IsEmpty => _dictionary == null;
/// <summary>
/// Add a value to the dictionary.
/// </summary>
public void Add(K k, V v)
{
if (_dictionary is object && _dictionary.TryGetValue(k, out var valueSet))
{
Debug.Assert(valueSet.Count >= 1);
// Have to re-store the ValueSet in case we upgraded the existing ValueSet from
// holding a single item to holding multiple items.
_dictionary[k] = valueSet.WithAddedItem(v);
}
else
{
this.EnsureDictionary();
_dictionary![k] = new ValueSet(v);
}
}
public bool TryGetValue<TArg>(K key, Func<V, TArg, bool> predicate, TArg arg, [MaybeNullWhen(false)] out V value)
{
if (_dictionary is not null && _dictionary.TryGetValue(key, out var valueSet))
{
Debug.Assert(valueSet.Count >= 1);
return valueSet.TryGetValue(predicate, arg, out value);
}
value = default;
return false;
}
public Dictionary<K, ValueSet>.Enumerator GetEnumerator()
{
return _dictionary is null ? s_emptyDictionary.GetEnumerator() : _dictionary.GetEnumerator();
}
IEnumerator<KeyValuePair<K, ValueSet>> IEnumerable<KeyValuePair<K, ValueSet>>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Get all values associated with K, in the order they were added.
/// Returns empty read-only array if no values were present.
/// </summary>
public ImmutableArray<V> this[K k]
{
get
{
if (_dictionary is object && _dictionary.TryGetValue(k, out var valueSet))
{
Debug.Assert(valueSet.Count >= 1);
return valueSet.Items;
}
return ImmutableArray<V>.Empty;
}
}
public bool Contains(K key, V value)
{
return _dictionary is object &&
_dictionary.TryGetValue(key, out var valueSet) &&
valueSet.Contains(value);
}
/// <summary>
/// Get a collection of all the keys.
/// </summary>
public Dictionary<K, ValueSet>.KeyCollection Keys
{
get { return _dictionary is null ? s_emptyDictionary.Keys : _dictionary.Keys; }
}
public struct ValueSet : IEnumerable<V>
{
/// <summary>
/// Each value is either a single V or an <see cref="ArrayBuilder{V}"/>.
/// Never null.
/// </summary>
private readonly object _value;
internal ValueSet(V value)
{
_value = value;
}
internal ValueSet(ArrayBuilder<V> values)
{
_value = values;
}
internal void Free()
{
var arrayBuilder = _value as ArrayBuilder<V>;
arrayBuilder?.Free();
}
internal V this[int index]
{
get
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
if (arrayBuilder == null)
{
if (index == 0)
{
return (V)_value;
}
else
{
throw new IndexOutOfRangeException();
}
}
else
{
return arrayBuilder[index];
}
}
}
public bool TryGetValue<TArg>(Func<V, TArg, bool> predicate, TArg arg, [MaybeNullWhen(false)] out V value)
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
if (arrayBuilder is not null)
{
foreach (var v in arrayBuilder)
{
if (predicate(v, arg))
{
value = v;
return true;
}
}
}
else
{
var singleValue = (V)_value;
if (predicate(singleValue, arg))
{
value = singleValue;
return true;
}
}
value = default;
return false;
}
internal bool Contains(V item)
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
return arrayBuilder == null
? EqualityComparer<V>.Default.Equals(item, (V)_value)
: arrayBuilder.Contains(item);
}
internal ImmutableArray<V> Items
{
get
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
if (arrayBuilder == null)
{
// promote singleton to set
Debug.Assert(_value is V, "Item must be a a V");
return ImmutableArray.Create<V>((V)_value);
}
else
{
return arrayBuilder.ToImmutable();
}
}
}
internal int Count => (_value as ArrayBuilder<V>)?.Count ?? 1;
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<V> IEnumerable<V>.GetEnumerator()
{
return GetEnumerator();
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
internal ValueSet WithAddedItem(V item)
{
Debug.Assert(this.Count >= 1);
var arrayBuilder = _value as ArrayBuilder<V>;
if (arrayBuilder == null)
{
// Promote from singleton V to ArrayBuilder<V>.
Debug.Assert(_value is V, "_value must be a V");
// By default we allocate array builders with a size of two. That's to store
// the single item already in _value, and to store the item we're adding.
// In general, we presume that the amount of values per key will be low, so this
// means we have very little overhead when there are multiple keys per value.
arrayBuilder = ArrayBuilder<V>.GetInstance(capacity: 2);
arrayBuilder.Add((V)_value);
arrayBuilder.Add(item);
}
else
{
arrayBuilder.Add(item);
}
return new ValueSet(arrayBuilder);
}
public struct Enumerator : IEnumerator<V>
{
private readonly ValueSet _valueSet;
private readonly int _count;
private int _index;
public Enumerator(ValueSet valueSet)
{
_valueSet = valueSet;
_count = _valueSet.Count;
Debug.Assert(_count >= 1);
_index = -1;
}
public V Current => _valueSet[_index];
object IEnumerator.Current => Current;
public bool MoveNext()
{
_index++;
return _index < _count;
}
public void Reset()
{
_index = -1;
}
public void Dispose()
{
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Scripting/VisualBasic/Hosting/ObjectFormatter/VisualBasicObjectFormatter.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.Scripting.Hosting
Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting
Public NotInheritable Class VisualBasicObjectFormatter
Inherits ObjectFormatter
Public Shared ReadOnly Property Instance As New VisualBasicObjectFormatter()
Private Shared ReadOnly s_impl As ObjectFormatter = New VisualBasicObjectFormatterImpl()
Private Sub New()
End Sub
Public Overrides Function FormatObject(obj As Object, options As PrintOptions) As String
Return s_impl.FormatObject(obj, options)
End Function
Public Overrides Function FormatException(e As Exception) As String
Return s_impl.FormatException(e)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Scripting.Hosting
Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting
Public NotInheritable Class VisualBasicObjectFormatter
Inherits ObjectFormatter
Public Shared ReadOnly Property Instance As New VisualBasicObjectFormatter()
Private Shared ReadOnly s_impl As ObjectFormatter = New VisualBasicObjectFormatterImpl()
Private Sub New()
End Sub
Public Overrides Function FormatObject(obj As Object, options As PrintOptions) As String
Return s_impl.FormatObject(obj, options)
End Function
Public Overrides Function FormatException(e As Exception) As String
Return s_impl.FormatException(e)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./eng/common/templates/steps/add-build-to-channel.yml | parameters:
ChannelId: 0
steps:
- task: PowerShell@2
displayName: Add Build to Channel
inputs:
filePath: $(Build.SourcesDirectory)/eng/common/post-build/add-build-to-channel.ps1
arguments: -BuildId $(BARBuildId)
-ChannelId ${{ parameters.ChannelId }}
-MaestroApiAccessToken $(MaestroApiAccessToken)
-MaestroApiEndPoint $(MaestroApiEndPoint)
-MaestroApiVersion $(MaestroApiVersion)
| parameters:
ChannelId: 0
steps:
- task: PowerShell@2
displayName: Add Build to Channel
inputs:
filePath: $(Build.SourcesDirectory)/eng/common/post-build/add-build-to-channel.ps1
arguments: -BuildId $(BARBuildId)
-ChannelId ${{ parameters.ChannelId }}
-MaestroApiAccessToken $(MaestroApiAccessToken)
-MaestroApiEndPoint $(MaestroApiEndPoint)
-MaestroApiVersion $(MaestroApiVersion)
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ConcatImmutableArray`1.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
internal readonly struct ConcatImmutableArray<T> : IEnumerable<T>
{
private readonly ImmutableArray<T> _first;
private readonly ImmutableArray<T> _second;
public ConcatImmutableArray(ImmutableArray<T> first, ImmutableArray<T> second)
{
_first = first;
_second = second;
}
public int Length => _first.Length + _second.Length;
public bool Any(Func<T, bool> predicate)
=> _first.Any(predicate) || _second.Any(predicate);
public Enumerator GetEnumerator()
=> new(_first, _second);
public ImmutableArray<T> ToImmutableArray()
=> _first.NullToEmpty().AddRange(_second.NullToEmpty());
IEnumerator<T> IEnumerable<T>.GetEnumerator()
=> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator();
public struct Enumerator : IEnumerator<T>
{
private ImmutableArray<T>.Enumerator _current;
private ImmutableArray<T> _next;
public Enumerator(ImmutableArray<T> first, ImmutableArray<T> second)
{
_current = first.NullToEmpty().GetEnumerator();
_next = second.NullToEmpty();
}
public T Current => _current.Current;
object? IEnumerator.Current => Current;
public bool MoveNext()
{
if (_current.MoveNext())
{
return true;
}
_current = _next.GetEnumerator();
_next = ImmutableArray<T>.Empty;
return _current.MoveNext();
}
void IDisposable.Dispose()
{
}
void IEnumerator.Reset()
=> throw new NotSupportedException();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
internal readonly struct ConcatImmutableArray<T> : IEnumerable<T>
{
private readonly ImmutableArray<T> _first;
private readonly ImmutableArray<T> _second;
public ConcatImmutableArray(ImmutableArray<T> first, ImmutableArray<T> second)
{
_first = first;
_second = second;
}
public int Length => _first.Length + _second.Length;
public bool Any(Func<T, bool> predicate)
=> _first.Any(predicate) || _second.Any(predicate);
public Enumerator GetEnumerator()
=> new(_first, _second);
public ImmutableArray<T> ToImmutableArray()
=> _first.NullToEmpty().AddRange(_second.NullToEmpty());
IEnumerator<T> IEnumerable<T>.GetEnumerator()
=> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator();
public struct Enumerator : IEnumerator<T>
{
private ImmutableArray<T>.Enumerator _current;
private ImmutableArray<T> _next;
public Enumerator(ImmutableArray<T> first, ImmutableArray<T> second)
{
_current = first.NullToEmpty().GetEnumerator();
_next = second.NullToEmpty();
}
public T Current => _current.Current;
object? IEnumerator.Current => Current;
public bool MoveNext()
{
if (_current.MoveNext())
{
return true;
}
_current = _next.GetEnumerator();
_next = ImmutableArray<T>.Empty;
return _current.MoveNext();
}
void IDisposable.Dispose()
{
}
void IEnumerator.Reset()
=> throw new NotSupportedException();
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./eng/common/darc-init.sh | #!/usr/bin/env bash
source="${BASH_SOURCE[0]}"
darcVersion=''
versionEndpoint='https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16'
verbosity='minimal'
while [[ $# > 0 ]]; do
opt="$(echo "$1" | tr "[:upper:]" "[:lower:]")"
case "$opt" in
--darcversion)
darcVersion=$2
shift
;;
--versionendpoint)
versionEndpoint=$2
shift
;;
--verbosity)
verbosity=$2
shift
;;
--toolpath)
toolpath=$2
shift
;;
*)
echo "Invalid argument: $1"
usage
exit 1
;;
esac
shift
done
# resolve $source until the file is no longer a symlink
while [[ -h "$source" ]]; do
scriptroot="$( cd -P "$( dirname "$source" )" && pwd )"
source="$(readlink "$source")"
# if $source was a relative symlink, we need to resolve it relative to the path where the
# symlink file was located
[[ $source != /* ]] && source="$scriptroot/$source"
done
scriptroot="$( cd -P "$( dirname "$source" )" && pwd )"
. "$scriptroot/tools.sh"
if [ -z "$darcVersion" ]; then
darcVersion=$(curl -X GET "$versionEndpoint" -H "accept: text/plain")
fi
function InstallDarcCli {
local darc_cli_package_name="microsoft.dotnet.darc"
InitializeDotNetCli
local dotnet_root=$_InitializeDotNetCli
if [ -z "$toolpath" ]; then
local tool_list=$($dotnet_root/dotnet tool list -g)
if [[ $tool_list = *$darc_cli_package_name* ]]; then
echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name -g)
fi
else
local tool_list=$($dotnet_root/dotnet tool list --tool-path "$toolpath")
if [[ $tool_list = *$darc_cli_package_name* ]]; then
echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name --tool-path "$toolpath")
fi
fi
local arcadeServicesSource="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json"
echo "Installing Darc CLI version $darcVersion..."
echo "You may need to restart your command shell if this is the first dotnet tool you have installed."
if [ -z "$toolpath" ]; then
echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g)
else
echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity --tool-path "$toolpath")
fi
}
InstallDarcCli
| #!/usr/bin/env bash
source="${BASH_SOURCE[0]}"
darcVersion=''
versionEndpoint='https://maestro-prod.westus2.cloudapp.azure.com/api/assets/darc-version?api-version=2019-01-16'
verbosity='minimal'
while [[ $# > 0 ]]; do
opt="$(echo "$1" | tr "[:upper:]" "[:lower:]")"
case "$opt" in
--darcversion)
darcVersion=$2
shift
;;
--versionendpoint)
versionEndpoint=$2
shift
;;
--verbosity)
verbosity=$2
shift
;;
--toolpath)
toolpath=$2
shift
;;
*)
echo "Invalid argument: $1"
usage
exit 1
;;
esac
shift
done
# resolve $source until the file is no longer a symlink
while [[ -h "$source" ]]; do
scriptroot="$( cd -P "$( dirname "$source" )" && pwd )"
source="$(readlink "$source")"
# if $source was a relative symlink, we need to resolve it relative to the path where the
# symlink file was located
[[ $source != /* ]] && source="$scriptroot/$source"
done
scriptroot="$( cd -P "$( dirname "$source" )" && pwd )"
. "$scriptroot/tools.sh"
if [ -z "$darcVersion" ]; then
darcVersion=$(curl -X GET "$versionEndpoint" -H "accept: text/plain")
fi
function InstallDarcCli {
local darc_cli_package_name="microsoft.dotnet.darc"
InitializeDotNetCli
local dotnet_root=$_InitializeDotNetCli
if [ -z "$toolpath" ]; then
local tool_list=$($dotnet_root/dotnet tool list -g)
if [[ $tool_list = *$darc_cli_package_name* ]]; then
echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name -g)
fi
else
local tool_list=$($dotnet_root/dotnet tool list --tool-path "$toolpath")
if [[ $tool_list = *$darc_cli_package_name* ]]; then
echo $($dotnet_root/dotnet tool uninstall $darc_cli_package_name --tool-path "$toolpath")
fi
fi
local arcadeServicesSource="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json"
echo "Installing Darc CLI version $darcVersion..."
echo "You may need to restart your command shell if this is the first dotnet tool you have installed."
if [ -z "$toolpath" ]; then
echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity -g)
else
echo $($dotnet_root/dotnet tool install $darc_cli_package_name --version $darcVersion --add-source "$arcadeServicesSource" -v $verbosity --tool-path "$toolpath")
fi
}
InstallDarcCli
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/VisualBasic/Portable/Syntax/SyntaxNodeExtensions.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Scanner = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Module SyntaxNodeExtensions
<Extension()>
Public Function WithAnnotations(Of TNode As VisualBasicSyntaxNode)(node As TNode, ParamArray annotations As SyntaxAnnotation()) As TNode
Return DirectCast(node.Green.SetAnnotations(annotations).CreateRed(), TNode)
End Function
''' <summary>
''' Find enclosing WithStatement if it exists.
''' </summary>
''' <param name="node"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function ContainingWithStatement(node As VisualBasicSyntaxNode) As WithStatementSyntax
Debug.Assert(node IsNot Nothing)
If node Is Nothing Then
Return Nothing
End If
node = node.Parent
While node IsNot Nothing
Select Case node.Kind
Case SyntaxKind.WithBlock
Return DirectCast(node, WithBlockSyntax).WithStatement
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.EventBlock
' Don't look outside the current method/property/operator/event
Exit While
End Select
node = node.Parent
End While
Return Nothing
End Function
<Extension()> _
Public Sub GetAncestors(Of T As VisualBasicSyntaxNode, C As VisualBasicSyntaxNode)(node As VisualBasicSyntaxNode, result As ArrayBuilder(Of T))
Dim current = node.Parent
Do While current IsNot Nothing AndAlso Not (TypeOf current Is C)
If TypeOf current Is T Then
result.Add(DirectCast(current, T))
End If
current = current.Parent
Loop
result.ReverseContents()
End Sub
<Extension()> _
Public Function GetAncestorOrSelf(Of T As VisualBasicSyntaxNode)(node As VisualBasicSyntaxNode) As T
Do While node IsNot Nothing
Dim result = TryCast(node, T)
If result IsNot Nothing Then
Return result
End If
node = node.Parent
Loop
Return Nothing
End Function
<Extension()>
Public Function IsLambdaExpressionSyntax(this As SyntaxNode) As Boolean
Select Case this.Kind
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return True
End Select
Return False
End Function
''' <summary>
''' Simplified version of ExtractAnonymousTypeMemberName implemented on inner tokens.
''' </summary>
<Extension()>
Friend Function ExtractAnonymousTypeMemberName(input As ExpressionSyntax, <Out()> ByRef failedToInferFromXmlName As XmlNameSyntax) As SyntaxToken
' TODO: revise and remove code duplication
failedToInferFromXmlName = Nothing
TryAgain:
Select Case input.Kind
Case SyntaxKind.IdentifierName
Return DirectCast(input, IdentifierNameSyntax).Identifier
Case SyntaxKind.XmlName
Dim xmlNameInferredFrom = DirectCast(input, XmlNameSyntax)
If Not Scanner.IsIdentifier(xmlNameInferredFrom.LocalName.ToString) Then
failedToInferFromXmlName = xmlNameInferredFrom
Return Nothing
End If
Return xmlNameInferredFrom.LocalName
Case SyntaxKind.XmlBracketedName
' handles something like <a-a>
Dim xmlNameInferredFrom = DirectCast(input, XmlBracketedNameSyntax)
input = xmlNameInferredFrom.Name
GoTo TryAgain
Case SyntaxKind.SimpleMemberAccessExpression,
SyntaxKind.DictionaryAccessExpression
Dim memberAccess = DirectCast(input, MemberAccessExpressionSyntax)
If input.Kind = SyntaxKind.SimpleMemberAccessExpression Then
' See if this is an identifier qualified with XmlElementAccessExpression or XmlDescendantAccessExpression
Dim receiver As ExpressionSyntax = If(memberAccess.Expression, GetCorrespondingConditionalAccessReceiver(memberAccess))
If receiver IsNot Nothing Then
Select Case receiver.Kind
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlDescendantAccessExpression
input = receiver
GoTo TryAgain
End Select
End If
End If
input = memberAccess.Name
GoTo TryAgain
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlAttributeAccessExpression,
SyntaxKind.XmlDescendantAccessExpression
Dim xmlAccess = DirectCast(input, XmlMemberAccessExpressionSyntax)
input = xmlAccess.Name
GoTo TryAgain
Case SyntaxKind.InvocationExpression
Dim invocation = DirectCast(input, InvocationExpressionSyntax)
Dim target As ExpressionSyntax = If(invocation.Expression, GetCorrespondingConditionalAccessReceiver(invocation))
If target Is Nothing Then
Exit Select
End If
If invocation.ArgumentList Is Nothing OrElse invocation.ArgumentList.Arguments.Count = 0 Then
input = target
GoTo TryAgain
End If
Debug.Assert(invocation.ArgumentList IsNot Nothing)
If invocation.ArgumentList.Arguments.Count = 1 Then
' See if this is an indexed XmlElementAccessExpression or XmlDescendantAccessExpression
Select Case target.Kind
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlDescendantAccessExpression
input = target
GoTo TryAgain
End Select
End If
Case SyntaxKind.ConditionalAccessExpression
input = DirectCast(input, ConditionalAccessExpressionSyntax).WhenNotNull
GoTo TryAgain
End Select
Return Nothing
End Function
Private Function GetCorrespondingConditionalAccessReceiver(node As ExpressionSyntax) As ExpressionSyntax
Dim access As ConditionalAccessExpressionSyntax = GetCorrespondingConditionalAccessExpression(node)
If access IsNot Nothing Then
Return access.Expression
End If
Return Nothing
End Function
<Extension>
Friend Function GetCorrespondingConditionalAccessExpression(node As ExpressionSyntax) As ConditionalAccessExpressionSyntax
Dim access As VisualBasicSyntaxNode = node
Dim parent As VisualBasicSyntaxNode = access.Parent
While parent IsNot Nothing
Select Case parent.Kind
Case SyntaxKind.DictionaryAccessExpression,
SyntaxKind.SimpleMemberAccessExpression
If DirectCast(parent, MemberAccessExpressionSyntax).Expression IsNot access Then
Return Nothing
End If
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlDescendantAccessExpression,
SyntaxKind.XmlAttributeAccessExpression
If DirectCast(parent, XmlMemberAccessExpressionSyntax).Base IsNot access Then
Return Nothing
End If
Case SyntaxKind.InvocationExpression
If DirectCast(parent, InvocationExpressionSyntax).Expression IsNot access Then
Return Nothing
End If
Case SyntaxKind.ConditionalAccessExpression
Dim conditional = DirectCast(parent, ConditionalAccessExpressionSyntax)
If conditional.WhenNotNull Is access Then
Return conditional
ElseIf conditional.Expression IsNot access Then
Return Nothing
End If
Case Else
Return Nothing
End Select
access = parent
parent = access.Parent
End While
Return Nothing
End Function
<Extension>
Friend Function GetLeafAccess(conditionalAccess As ConditionalAccessExpressionSyntax) As ExpressionSyntax
Dim access As ExpressionSyntax = conditionalAccess.WhenNotNull
Do
Select Case access.Kind
Case SyntaxKind.DictionaryAccessExpression,
SyntaxKind.SimpleMemberAccessExpression
Dim memberAccess = DirectCast(access, MemberAccessExpressionSyntax)
If memberAccess.Expression Is Nothing Then
Return memberAccess
Else
access = memberAccess.Expression
End If
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlDescendantAccessExpression,
SyntaxKind.XmlAttributeAccessExpression
Dim memberAccess = DirectCast(access, XmlMemberAccessExpressionSyntax)
If memberAccess.Base Is Nothing Then
Return memberAccess
Else
access = memberAccess.Base
End If
Case SyntaxKind.InvocationExpression
Dim invocation = DirectCast(access, InvocationExpressionSyntax)
If invocation.Expression Is Nothing Then
Return invocation
Else
access = invocation.Expression
End If
Case SyntaxKind.ConditionalAccessExpression
access = DirectCast(access, ConditionalAccessExpressionSyntax).Expression
If access Is Nothing Then
' Must be a syntax error
Return Nothing
End If
Case Else
Return Nothing
End Select
Loop
End Function
''' <summary>
''' Returns true if all arguments are of the specified kind and they are also missing.
''' </summary>
<Extension()>
Public Function AllAreMissing(arguments As IEnumerable(Of VisualBasicSyntaxNode), kind As SyntaxKind) As Boolean
Return Not arguments.Any(Function(arg) Not (arg.Kind = kind AndAlso DirectCast(arg, IdentifierNameSyntax).IsMissing))
End Function
''' <summary>
''' Returns true if all arguments are missing.
''' </summary>
''' <param name="arguments"></param>
<Extension()>
Public Function AllAreMissingIdentifierName(arguments As IEnumerable(Of VisualBasicSyntaxNode)) As Boolean
Return arguments.AllAreMissing(SyntaxKind.IdentifierName)
End Function
''' <summary>
''' Given a syntax node of query clause returns its leading keyword
''' </summary>
<Extension()>
Public Function QueryClauseKeywordOrRangeVariableIdentifier(syntax As SyntaxNode) As SyntaxToken
Select Case syntax.Kind
Case SyntaxKind.CollectionRangeVariable
Return DirectCast(syntax, CollectionRangeVariableSyntax).Identifier.Identifier
Case SyntaxKind.ExpressionRangeVariable
Return DirectCast(syntax, ExpressionRangeVariableSyntax).NameEquals.Identifier.Identifier
Case SyntaxKind.FromClause
Return DirectCast(syntax, FromClauseSyntax).FromKeyword
Case SyntaxKind.FromClause
Return DirectCast(syntax, FromClauseSyntax).FromKeyword
Case SyntaxKind.LetClause
Return DirectCast(syntax, LetClauseSyntax).LetKeyword
Case SyntaxKind.AggregateClause
Return DirectCast(syntax, AggregateClauseSyntax).AggregateKeyword
Case SyntaxKind.DistinctClause
Return DirectCast(syntax, DistinctClauseSyntax).DistinctKeyword
Case SyntaxKind.WhereClause
Return DirectCast(syntax, WhereClauseSyntax).WhereKeyword
Case SyntaxKind.SkipWhileClause, SyntaxKind.TakeWhileClause
Return DirectCast(syntax, PartitionWhileClauseSyntax).SkipOrTakeKeyword
Case SyntaxKind.SkipClause, SyntaxKind.TakeClause
Return DirectCast(syntax, PartitionClauseSyntax).SkipOrTakeKeyword
Case SyntaxKind.GroupByClause
Return DirectCast(syntax, GroupByClauseSyntax).GroupKeyword
Case SyntaxKind.GroupJoinClause
Return DirectCast(syntax, GroupJoinClauseSyntax).GroupKeyword
Case SyntaxKind.SimpleJoinClause
Return DirectCast(syntax, SimpleJoinClauseSyntax).JoinKeyword
Case SyntaxKind.OrderByClause
Return DirectCast(syntax, OrderByClauseSyntax).OrderKeyword
Case SyntaxKind.SelectClause
Return DirectCast(syntax, SelectClauseSyntax).SelectKeyword
Case Else
Throw ExceptionUtilities.UnexpectedValue(syntax.Kind)
End Select
End Function
<Extension>
Friend Function EnclosingStructuredTrivia(node As VisualBasicSyntaxNode) As StructuredTriviaSyntax
While node IsNot Nothing
If node.IsStructuredTrivia Then
Return DirectCast(node, StructuredTriviaSyntax)
Else
node = node.Parent
End If
End While
Return Nothing
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Scanner = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.Scanner
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Module SyntaxNodeExtensions
<Extension()>
Public Function WithAnnotations(Of TNode As VisualBasicSyntaxNode)(node As TNode, ParamArray annotations As SyntaxAnnotation()) As TNode
Return DirectCast(node.Green.SetAnnotations(annotations).CreateRed(), TNode)
End Function
''' <summary>
''' Find enclosing WithStatement if it exists.
''' </summary>
''' <param name="node"></param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()> _
Public Function ContainingWithStatement(node As VisualBasicSyntaxNode) As WithStatementSyntax
Debug.Assert(node IsNot Nothing)
If node Is Nothing Then
Return Nothing
End If
node = node.Parent
While node IsNot Nothing
Select Case node.Kind
Case SyntaxKind.WithBlock
Return DirectCast(node, WithBlockSyntax).WithStatement
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.PropertyBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.EventBlock
' Don't look outside the current method/property/operator/event
Exit While
End Select
node = node.Parent
End While
Return Nothing
End Function
<Extension()> _
Public Sub GetAncestors(Of T As VisualBasicSyntaxNode, C As VisualBasicSyntaxNode)(node As VisualBasicSyntaxNode, result As ArrayBuilder(Of T))
Dim current = node.Parent
Do While current IsNot Nothing AndAlso Not (TypeOf current Is C)
If TypeOf current Is T Then
result.Add(DirectCast(current, T))
End If
current = current.Parent
Loop
result.ReverseContents()
End Sub
<Extension()> _
Public Function GetAncestorOrSelf(Of T As VisualBasicSyntaxNode)(node As VisualBasicSyntaxNode) As T
Do While node IsNot Nothing
Dim result = TryCast(node, T)
If result IsNot Nothing Then
Return result
End If
node = node.Parent
Loop
Return Nothing
End Function
<Extension()>
Public Function IsLambdaExpressionSyntax(this As SyntaxNode) As Boolean
Select Case this.Kind
Case SyntaxKind.SingleLineFunctionLambdaExpression,
SyntaxKind.SingleLineSubLambdaExpression,
SyntaxKind.MultiLineFunctionLambdaExpression,
SyntaxKind.MultiLineSubLambdaExpression
Return True
End Select
Return False
End Function
''' <summary>
''' Simplified version of ExtractAnonymousTypeMemberName implemented on inner tokens.
''' </summary>
<Extension()>
Friend Function ExtractAnonymousTypeMemberName(input As ExpressionSyntax, <Out()> ByRef failedToInferFromXmlName As XmlNameSyntax) As SyntaxToken
' TODO: revise and remove code duplication
failedToInferFromXmlName = Nothing
TryAgain:
Select Case input.Kind
Case SyntaxKind.IdentifierName
Return DirectCast(input, IdentifierNameSyntax).Identifier
Case SyntaxKind.XmlName
Dim xmlNameInferredFrom = DirectCast(input, XmlNameSyntax)
If Not Scanner.IsIdentifier(xmlNameInferredFrom.LocalName.ToString) Then
failedToInferFromXmlName = xmlNameInferredFrom
Return Nothing
End If
Return xmlNameInferredFrom.LocalName
Case SyntaxKind.XmlBracketedName
' handles something like <a-a>
Dim xmlNameInferredFrom = DirectCast(input, XmlBracketedNameSyntax)
input = xmlNameInferredFrom.Name
GoTo TryAgain
Case SyntaxKind.SimpleMemberAccessExpression,
SyntaxKind.DictionaryAccessExpression
Dim memberAccess = DirectCast(input, MemberAccessExpressionSyntax)
If input.Kind = SyntaxKind.SimpleMemberAccessExpression Then
' See if this is an identifier qualified with XmlElementAccessExpression or XmlDescendantAccessExpression
Dim receiver As ExpressionSyntax = If(memberAccess.Expression, GetCorrespondingConditionalAccessReceiver(memberAccess))
If receiver IsNot Nothing Then
Select Case receiver.Kind
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlDescendantAccessExpression
input = receiver
GoTo TryAgain
End Select
End If
End If
input = memberAccess.Name
GoTo TryAgain
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlAttributeAccessExpression,
SyntaxKind.XmlDescendantAccessExpression
Dim xmlAccess = DirectCast(input, XmlMemberAccessExpressionSyntax)
input = xmlAccess.Name
GoTo TryAgain
Case SyntaxKind.InvocationExpression
Dim invocation = DirectCast(input, InvocationExpressionSyntax)
Dim target As ExpressionSyntax = If(invocation.Expression, GetCorrespondingConditionalAccessReceiver(invocation))
If target Is Nothing Then
Exit Select
End If
If invocation.ArgumentList Is Nothing OrElse invocation.ArgumentList.Arguments.Count = 0 Then
input = target
GoTo TryAgain
End If
Debug.Assert(invocation.ArgumentList IsNot Nothing)
If invocation.ArgumentList.Arguments.Count = 1 Then
' See if this is an indexed XmlElementAccessExpression or XmlDescendantAccessExpression
Select Case target.Kind
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlDescendantAccessExpression
input = target
GoTo TryAgain
End Select
End If
Case SyntaxKind.ConditionalAccessExpression
input = DirectCast(input, ConditionalAccessExpressionSyntax).WhenNotNull
GoTo TryAgain
End Select
Return Nothing
End Function
Private Function GetCorrespondingConditionalAccessReceiver(node As ExpressionSyntax) As ExpressionSyntax
Dim access As ConditionalAccessExpressionSyntax = GetCorrespondingConditionalAccessExpression(node)
If access IsNot Nothing Then
Return access.Expression
End If
Return Nothing
End Function
<Extension>
Friend Function GetCorrespondingConditionalAccessExpression(node As ExpressionSyntax) As ConditionalAccessExpressionSyntax
Dim access As VisualBasicSyntaxNode = node
Dim parent As VisualBasicSyntaxNode = access.Parent
While parent IsNot Nothing
Select Case parent.Kind
Case SyntaxKind.DictionaryAccessExpression,
SyntaxKind.SimpleMemberAccessExpression
If DirectCast(parent, MemberAccessExpressionSyntax).Expression IsNot access Then
Return Nothing
End If
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlDescendantAccessExpression,
SyntaxKind.XmlAttributeAccessExpression
If DirectCast(parent, XmlMemberAccessExpressionSyntax).Base IsNot access Then
Return Nothing
End If
Case SyntaxKind.InvocationExpression
If DirectCast(parent, InvocationExpressionSyntax).Expression IsNot access Then
Return Nothing
End If
Case SyntaxKind.ConditionalAccessExpression
Dim conditional = DirectCast(parent, ConditionalAccessExpressionSyntax)
If conditional.WhenNotNull Is access Then
Return conditional
ElseIf conditional.Expression IsNot access Then
Return Nothing
End If
Case Else
Return Nothing
End Select
access = parent
parent = access.Parent
End While
Return Nothing
End Function
<Extension>
Friend Function GetLeafAccess(conditionalAccess As ConditionalAccessExpressionSyntax) As ExpressionSyntax
Dim access As ExpressionSyntax = conditionalAccess.WhenNotNull
Do
Select Case access.Kind
Case SyntaxKind.DictionaryAccessExpression,
SyntaxKind.SimpleMemberAccessExpression
Dim memberAccess = DirectCast(access, MemberAccessExpressionSyntax)
If memberAccess.Expression Is Nothing Then
Return memberAccess
Else
access = memberAccess.Expression
End If
Case SyntaxKind.XmlElementAccessExpression,
SyntaxKind.XmlDescendantAccessExpression,
SyntaxKind.XmlAttributeAccessExpression
Dim memberAccess = DirectCast(access, XmlMemberAccessExpressionSyntax)
If memberAccess.Base Is Nothing Then
Return memberAccess
Else
access = memberAccess.Base
End If
Case SyntaxKind.InvocationExpression
Dim invocation = DirectCast(access, InvocationExpressionSyntax)
If invocation.Expression Is Nothing Then
Return invocation
Else
access = invocation.Expression
End If
Case SyntaxKind.ConditionalAccessExpression
access = DirectCast(access, ConditionalAccessExpressionSyntax).Expression
If access Is Nothing Then
' Must be a syntax error
Return Nothing
End If
Case Else
Return Nothing
End Select
Loop
End Function
''' <summary>
''' Returns true if all arguments are of the specified kind and they are also missing.
''' </summary>
<Extension()>
Public Function AllAreMissing(arguments As IEnumerable(Of VisualBasicSyntaxNode), kind As SyntaxKind) As Boolean
Return Not arguments.Any(Function(arg) Not (arg.Kind = kind AndAlso DirectCast(arg, IdentifierNameSyntax).IsMissing))
End Function
''' <summary>
''' Returns true if all arguments are missing.
''' </summary>
''' <param name="arguments"></param>
<Extension()>
Public Function AllAreMissingIdentifierName(arguments As IEnumerable(Of VisualBasicSyntaxNode)) As Boolean
Return arguments.AllAreMissing(SyntaxKind.IdentifierName)
End Function
''' <summary>
''' Given a syntax node of query clause returns its leading keyword
''' </summary>
<Extension()>
Public Function QueryClauseKeywordOrRangeVariableIdentifier(syntax As SyntaxNode) As SyntaxToken
Select Case syntax.Kind
Case SyntaxKind.CollectionRangeVariable
Return DirectCast(syntax, CollectionRangeVariableSyntax).Identifier.Identifier
Case SyntaxKind.ExpressionRangeVariable
Return DirectCast(syntax, ExpressionRangeVariableSyntax).NameEquals.Identifier.Identifier
Case SyntaxKind.FromClause
Return DirectCast(syntax, FromClauseSyntax).FromKeyword
Case SyntaxKind.FromClause
Return DirectCast(syntax, FromClauseSyntax).FromKeyword
Case SyntaxKind.LetClause
Return DirectCast(syntax, LetClauseSyntax).LetKeyword
Case SyntaxKind.AggregateClause
Return DirectCast(syntax, AggregateClauseSyntax).AggregateKeyword
Case SyntaxKind.DistinctClause
Return DirectCast(syntax, DistinctClauseSyntax).DistinctKeyword
Case SyntaxKind.WhereClause
Return DirectCast(syntax, WhereClauseSyntax).WhereKeyword
Case SyntaxKind.SkipWhileClause, SyntaxKind.TakeWhileClause
Return DirectCast(syntax, PartitionWhileClauseSyntax).SkipOrTakeKeyword
Case SyntaxKind.SkipClause, SyntaxKind.TakeClause
Return DirectCast(syntax, PartitionClauseSyntax).SkipOrTakeKeyword
Case SyntaxKind.GroupByClause
Return DirectCast(syntax, GroupByClauseSyntax).GroupKeyword
Case SyntaxKind.GroupJoinClause
Return DirectCast(syntax, GroupJoinClauseSyntax).GroupKeyword
Case SyntaxKind.SimpleJoinClause
Return DirectCast(syntax, SimpleJoinClauseSyntax).JoinKeyword
Case SyntaxKind.OrderByClause
Return DirectCast(syntax, OrderByClauseSyntax).OrderKeyword
Case SyntaxKind.SelectClause
Return DirectCast(syntax, SelectClauseSyntax).SelectKeyword
Case Else
Throw ExceptionUtilities.UnexpectedValue(syntax.Kind)
End Select
End Function
<Extension>
Friend Function EnclosingStructuredTrivia(node As VisualBasicSyntaxNode) As StructuredTriviaSyntax
While node IsNot Nothing
If node.IsStructuredTrivia Then
Return DirectCast(node, StructuredTriviaSyntax)
Else
node = node.Parent
End If
End While
Return Nothing
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpExpressionCompiler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpExpressionCompiler : ExpressionCompiler
{
private static readonly DkmCompilerId s_compilerId = new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.CSharp);
public CSharpExpressionCompiler() : base(new CSharpFrameDecoder(), new CSharpLanguageInstructionDecoder())
{
}
internal override DiagnosticFormatter DiagnosticFormatter
{
get { return DebuggerDiagnosticFormatter.Instance; }
}
internal override DkmCompilerId CompilerId
{
get { return s_compilerId; }
}
internal delegate MetadataContext<CSharpMetadataContext> GetMetadataContextDelegate<TAppDomain>(TAppDomain appDomain);
internal delegate void SetMetadataContextDelegate<TAppDomain>(TAppDomain appDomain, MetadataContext<CSharpMetadataContext> metadataContext, bool report);
internal override EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly)
{
return CreateTypeContext(
appDomain,
ad => ad.GetMetadataContext<CSharpMetadataContext>(),
metadataBlocks,
moduleVersionId,
typeToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
internal static EvaluationContext CreateTypeContext<TAppDomain>(
TAppDomain appDomain,
GetMetadataContextDelegate<TAppDomain> getMetadataContext,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
MakeAssemblyReferencesKind kind)
{
CSharpCompilation? compilation;
if (kind == MakeAssemblyReferencesKind.DirectReferencesOnly)
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
return EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken);
}
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var previous = getMetadataContext(appDomain);
CSharpMetadataContext previousMetadataContext = default;
if (previous.Matches(metadataBlocks))
{
previous.AssemblyContexts.TryGetValue(contextId, out previousMetadataContext);
}
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
if (compilation == null)
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
}
var context = EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken);
// New type context is not attached to the AppDomain since it is less
// re-usable than the previous attached method context. (We could hold
// on to it if we don't have a previous method context but it's unlikely
// that we evaluated a type-level expression before a method-level.)
Debug.Assert(context != previousMetadataContext.EvaluationContext);
return context;
}
internal override EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> unusedLazyAssemblyReaders,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly)
{
return CreateMethodContext(
appDomain,
ad => ad.GetMetadataContext<CSharpMetadataContext>(),
(ad, mc, report) => ad.SetMetadataContext<CSharpMetadataContext>(mc, report),
metadataBlocks,
symReader,
moduleVersionId,
methodToken,
methodVersion,
ilOffset,
localSignatureToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
internal static EvaluationContext CreateMethodContext<TAppDomain>(
TAppDomain appDomain,
GetMetadataContextDelegate<TAppDomain> getMetadataContext,
SetMetadataContextDelegate<TAppDomain> setMetadataContext,
ImmutableArray<MetadataBlock> metadataBlocks,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
MakeAssemblyReferencesKind kind)
{
CSharpCompilation compilation;
int offset = EvaluationContextBase.NormalizeILOffset(ilOffset);
if (kind == MakeAssemblyReferencesKind.DirectReferencesOnly)
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
return EvaluationContext.CreateMethodContext(
compilation,
symReader,
moduleVersionId,
methodToken,
methodVersion,
offset,
localSignatureToken);
}
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var previous = getMetadataContext(appDomain);
var assemblyContexts = previous.Matches(metadataBlocks) ? previous.AssemblyContexts : ImmutableDictionary<MetadataContextId, CSharpMetadataContext>.Empty;
CSharpMetadataContext previousMetadataContext;
assemblyContexts.TryGetValue(contextId, out previousMetadataContext);
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
if (compilation != null)
{
// Re-use entire context if method scope has not changed.
var previousContext = previousMetadataContext.EvaluationContext;
if (previousContext != null &&
previousContext.MethodContextReuseConstraints.HasValue &&
previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset))
{
return previousContext;
}
}
else
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
}
var context = EvaluationContext.CreateMethodContext(
compilation,
symReader,
moduleVersionId,
methodToken,
methodVersion,
offset,
localSignatureToken);
if (context != previousMetadataContext.EvaluationContext)
{
setMetadataContext(
appDomain,
new MetadataContext<CSharpMetadataContext>(
metadataBlocks,
assemblyContexts.SetItem(contextId, new CSharpMetadataContext(context.Compilation, context))),
report: kind == MakeAssemblyReferencesKind.AllReferences);
}
return context;
}
internal override void RemoveDataItem(DkmClrAppDomain appDomain)
{
appDomain.RemoveMetadataContext<CSharpMetadataContext>();
}
internal override ImmutableArray<MetadataBlock> GetMetadataBlocks(DkmClrAppDomain appDomain, DkmClrRuntimeInstance runtimeInstance)
{
var previous = appDomain.GetMetadataContext<CSharpMetadataContext>();
return runtimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
[DkmReportNonFatalWatsonException(ExcludeExceptionType = typeof(NotImplementedException)), DkmContinueCorruptingException]
internal sealed class CSharpExpressionCompiler : ExpressionCompiler
{
private static readonly DkmCompilerId s_compilerId = new DkmCompilerId(DkmVendorId.Microsoft, DkmLanguageId.CSharp);
public CSharpExpressionCompiler() : base(new CSharpFrameDecoder(), new CSharpLanguageInstructionDecoder())
{
}
internal override DiagnosticFormatter DiagnosticFormatter
{
get { return DebuggerDiagnosticFormatter.Instance; }
}
internal override DkmCompilerId CompilerId
{
get { return s_compilerId; }
}
internal delegate MetadataContext<CSharpMetadataContext> GetMetadataContextDelegate<TAppDomain>(TAppDomain appDomain);
internal delegate void SetMetadataContextDelegate<TAppDomain>(TAppDomain appDomain, MetadataContext<CSharpMetadataContext> metadataContext, bool report);
internal override EvaluationContextBase CreateTypeContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
bool useReferencedModulesOnly)
{
return CreateTypeContext(
appDomain,
ad => ad.GetMetadataContext<CSharpMetadataContext>(),
metadataBlocks,
moduleVersionId,
typeToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
internal static EvaluationContext CreateTypeContext<TAppDomain>(
TAppDomain appDomain,
GetMetadataContextDelegate<TAppDomain> getMetadataContext,
ImmutableArray<MetadataBlock> metadataBlocks,
Guid moduleVersionId,
int typeToken,
MakeAssemblyReferencesKind kind)
{
CSharpCompilation? compilation;
if (kind == MakeAssemblyReferencesKind.DirectReferencesOnly)
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
return EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken);
}
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var previous = getMetadataContext(appDomain);
CSharpMetadataContext previousMetadataContext = default;
if (previous.Matches(metadataBlocks))
{
previous.AssemblyContexts.TryGetValue(contextId, out previousMetadataContext);
}
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
if (compilation == null)
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
}
var context = EvaluationContext.CreateTypeContext(
compilation,
moduleVersionId,
typeToken);
// New type context is not attached to the AppDomain since it is less
// re-usable than the previous attached method context. (We could hold
// on to it if we don't have a previous method context but it's unlikely
// that we evaluated a type-level expression before a method-level.)
Debug.Assert(context != previousMetadataContext.EvaluationContext);
return context;
}
internal override EvaluationContextBase CreateMethodContext(
DkmClrAppDomain appDomain,
ImmutableArray<MetadataBlock> metadataBlocks,
Lazy<ImmutableArray<AssemblyReaders>> unusedLazyAssemblyReaders,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
bool useReferencedModulesOnly)
{
return CreateMethodContext(
appDomain,
ad => ad.GetMetadataContext<CSharpMetadataContext>(),
(ad, mc, report) => ad.SetMetadataContext<CSharpMetadataContext>(mc, report),
metadataBlocks,
symReader,
moduleVersionId,
methodToken,
methodVersion,
ilOffset,
localSignatureToken,
GetMakeAssemblyReferencesKind(useReferencedModulesOnly));
}
internal static EvaluationContext CreateMethodContext<TAppDomain>(
TAppDomain appDomain,
GetMetadataContextDelegate<TAppDomain> getMetadataContext,
SetMetadataContextDelegate<TAppDomain> setMetadataContext,
ImmutableArray<MetadataBlock> metadataBlocks,
object? symReader,
Guid moduleVersionId,
int methodToken,
int methodVersion,
uint ilOffset,
int localSignatureToken,
MakeAssemblyReferencesKind kind)
{
CSharpCompilation compilation;
int offset = EvaluationContextBase.NormalizeILOffset(ilOffset);
if (kind == MakeAssemblyReferencesKind.DirectReferencesOnly)
{
// Avoid using the cache for referenced assemblies only
// since this should be the exceptional case.
compilation = metadataBlocks.ToCompilationReferencedModulesOnly(moduleVersionId);
return EvaluationContext.CreateMethodContext(
compilation,
symReader,
moduleVersionId,
methodToken,
methodVersion,
offset,
localSignatureToken);
}
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var previous = getMetadataContext(appDomain);
var assemblyContexts = previous.Matches(metadataBlocks) ? previous.AssemblyContexts : ImmutableDictionary<MetadataContextId, CSharpMetadataContext>.Empty;
CSharpMetadataContext previousMetadataContext;
assemblyContexts.TryGetValue(contextId, out previousMetadataContext);
// Re-use the previous compilation if possible.
compilation = previousMetadataContext.Compilation;
if (compilation != null)
{
// Re-use entire context if method scope has not changed.
var previousContext = previousMetadataContext.EvaluationContext;
if (previousContext != null &&
previousContext.MethodContextReuseConstraints.HasValue &&
previousContext.MethodContextReuseConstraints.GetValueOrDefault().AreSatisfied(moduleVersionId, methodToken, methodVersion, offset))
{
return previousContext;
}
}
else
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
}
var context = EvaluationContext.CreateMethodContext(
compilation,
symReader,
moduleVersionId,
methodToken,
methodVersion,
offset,
localSignatureToken);
if (context != previousMetadataContext.EvaluationContext)
{
setMetadataContext(
appDomain,
new MetadataContext<CSharpMetadataContext>(
metadataBlocks,
assemblyContexts.SetItem(contextId, new CSharpMetadataContext(context.Compilation, context))),
report: kind == MakeAssemblyReferencesKind.AllReferences);
}
return context;
}
internal override void RemoveDataItem(DkmClrAppDomain appDomain)
{
appDomain.RemoveMetadataContext<CSharpMetadataContext>();
}
internal override ImmutableArray<MetadataBlock> GetMetadataBlocks(DkmClrAppDomain appDomain, DkmClrRuntimeInstance runtimeInstance)
{
var previous = appDomain.GetMetadataContext<CSharpMetadataContext>();
return runtimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks);
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/PrintResultTestSource.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Globalization
Module PrintHelper
Function GetCultureInvariantString(val As Object) As String
If val Is Nothing Then
Return Nothing
End If
Dim vType = val.GetType()
Dim valStr = val.ToString()
If vType Is GetType(DateTime) Then
valStr = DirectCast(val, DateTime).ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Single) Then
valStr = DirectCast(val, Single).ToString(CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Double) Then
valStr = DirectCast(val, Double).ToString(CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Decimal) Then
valStr = DirectCast(val, Decimal).ToString(CultureInfo.InvariantCulture)
End If
Return valStr
End Function
Sub PrintResult(val As Boolean)
Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResult(val As SByte)
Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResult(val As Byte)
Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResult(val As Short)
Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResult(val As UShort)
Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResult(val As Integer)
Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResult(val As UInteger)
Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResult(val As Long)
Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResult(val As ULong)
Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResult(val As Decimal)
Console.WriteLine("Decimal: {0}", GetCultureInvariantString(val))
End Sub
Sub PrintResult(val As Single)
Console.WriteLine("Single: {0}", GetCultureInvariantString(val))
End Sub
Sub PrintResult(val As Double)
Console.WriteLine("Double: {0}", GetCultureInvariantString(val))
End Sub
Sub PrintResult(val As Date)
Console.WriteLine("Date: {0}", GetCultureInvariantString(val))
End Sub
Sub PrintResult(val As Char)
Console.WriteLine("Char: [{0}]", val)
End Sub
Sub PrintResult(val As Char())
Console.WriteLine("Char(): {0}", New String(val))
End Sub
Sub PrintResult(val As String)
Console.WriteLine("String: [{0}]", val)
End Sub
Sub PrintResult(val As Object)
Console.WriteLine("Object: [{0}]", val)
End Sub
Sub PrintResult(val As Guid)
Console.WriteLine("Guid: {0}", val)
End Sub
Sub PrintResult(val As ValueType)
Dim pval = GetCultureInvariantString(val)
Console.WriteLine("ValueType: [{0}]", pval)
End Sub
Sub PrintResult(val As IComparable)
Console.WriteLine("IComparable: [{0}]", val)
End Sub
' =================================================================
Sub PrintResult(expr As String, val As Boolean)
System.Console.WriteLine("[{1}] Boolean: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As SByte)
System.Console.WriteLine("[{1}] SByte: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Byte)
System.Console.WriteLine("[{1}] Byte: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Short)
System.Console.WriteLine("[{1}] Short: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As UShort)
System.Console.WriteLine("[{1}] UShort: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Integer)
System.Console.WriteLine("[{1}] Integer: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As UInteger)
System.Console.WriteLine("[{1}] UInteger: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Long)
System.Console.WriteLine("[{1}] Long: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As ULong)
System.Console.WriteLine("[{1}] ULong: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Decimal)
System.Console.WriteLine("[{1}] Decimal: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As Single)
System.Console.WriteLine("[{1}] Single: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As Double)
System.Console.WriteLine("[{1}] Double: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As Date)
System.Console.WriteLine("[{1}] Date: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As Char)
System.Console.WriteLine("[{1}] Char: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As String)
System.Console.WriteLine("[{0}] String: [{1}]", expr, val)
End Sub
Sub PrintResult(expr As String, val As Object)
System.Console.WriteLine("[{1}] Object: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As System.TypeCode)
System.Console.WriteLine("[{1}] TypeCode: {0}", val, expr)
End Sub
End Module
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Globalization
Module PrintHelper
Function GetCultureInvariantString(val As Object) As String
If val Is Nothing Then
Return Nothing
End If
Dim vType = val.GetType()
Dim valStr = val.ToString()
If vType Is GetType(DateTime) Then
valStr = DirectCast(val, DateTime).ToString("M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Single) Then
valStr = DirectCast(val, Single).ToString(CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Double) Then
valStr = DirectCast(val, Double).ToString(CultureInfo.InvariantCulture)
ElseIf vType Is GetType(Decimal) Then
valStr = DirectCast(val, Decimal).ToString(CultureInfo.InvariantCulture)
End If
Return valStr
End Function
Sub PrintResult(val As Boolean)
Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResult(val As SByte)
Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResult(val As Byte)
Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResult(val As Short)
Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResult(val As UShort)
Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResult(val As Integer)
Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResult(val As UInteger)
Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResult(val As Long)
Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResult(val As ULong)
Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResult(val As Decimal)
Console.WriteLine("Decimal: {0}", GetCultureInvariantString(val))
End Sub
Sub PrintResult(val As Single)
Console.WriteLine("Single: {0}", GetCultureInvariantString(val))
End Sub
Sub PrintResult(val As Double)
Console.WriteLine("Double: {0}", GetCultureInvariantString(val))
End Sub
Sub PrintResult(val As Date)
Console.WriteLine("Date: {0}", GetCultureInvariantString(val))
End Sub
Sub PrintResult(val As Char)
Console.WriteLine("Char: [{0}]", val)
End Sub
Sub PrintResult(val As Char())
Console.WriteLine("Char(): {0}", New String(val))
End Sub
Sub PrintResult(val As String)
Console.WriteLine("String: [{0}]", val)
End Sub
Sub PrintResult(val As Object)
Console.WriteLine("Object: [{0}]", val)
End Sub
Sub PrintResult(val As Guid)
Console.WriteLine("Guid: {0}", val)
End Sub
Sub PrintResult(val As ValueType)
Dim pval = GetCultureInvariantString(val)
Console.WriteLine("ValueType: [{0}]", pval)
End Sub
Sub PrintResult(val As IComparable)
Console.WriteLine("IComparable: [{0}]", val)
End Sub
' =================================================================
Sub PrintResult(expr As String, val As Boolean)
System.Console.WriteLine("[{1}] Boolean: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As SByte)
System.Console.WriteLine("[{1}] SByte: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Byte)
System.Console.WriteLine("[{1}] Byte: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Short)
System.Console.WriteLine("[{1}] Short: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As UShort)
System.Console.WriteLine("[{1}] UShort: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Integer)
System.Console.WriteLine("[{1}] Integer: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As UInteger)
System.Console.WriteLine("[{1}] UInteger: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Long)
System.Console.WriteLine("[{1}] Long: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As ULong)
System.Console.WriteLine("[{1}] ULong: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As Decimal)
System.Console.WriteLine("[{1}] Decimal: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As Single)
System.Console.WriteLine("[{1}] Single: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As Double)
System.Console.WriteLine("[{1}] Double: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As Date)
System.Console.WriteLine("[{1}] Date: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As Char)
System.Console.WriteLine("[{1}] Char: {0}", val, expr)
End Sub
Sub PrintResult(expr As String, val As String)
System.Console.WriteLine("[{0}] String: [{1}]", expr, val)
End Sub
Sub PrintResult(expr As String, val As Object)
System.Console.WriteLine("[{1}] Object: {0}", GetCultureInvariantString(val), expr)
End Sub
Sub PrintResult(expr As String, val As System.TypeCode)
System.Console.WriteLine("[{1}] TypeCode: {0}", val, expr)
End Sub
End Module
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ISyntaxFacts.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal interface ISyntaxFacts
{
bool IsCaseSensitive { get; }
StringComparer StringComparer { get; }
SyntaxTrivia ElasticMarker { get; }
SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
ISyntaxKinds SyntaxKinds { get; }
bool SupportsIndexingInitializer(ParseOptions options);
bool SupportsLocalFunctionDeclaration(ParseOptions options);
bool SupportsNotPattern(ParseOptions options);
bool SupportsRecord(ParseOptions options);
bool SupportsRecordStruct(ParseOptions options);
bool SupportsThrowExpression(ParseOptions options);
SyntaxToken ParseToken(string text);
SyntaxTriviaList ParseLeadingTrivia(string text);
string EscapeIdentifier(string identifier);
bool IsVerbatimIdentifier(SyntaxToken token);
bool IsOperator(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token, PredefinedType type);
bool IsPredefinedOperator(SyntaxToken token);
bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op);
/// <summary>
/// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a
/// identifier that is always treated as being a special keyword, regardless of where it is
/// found in the token stream. Examples of this are tokens like <see langword="class"/> and
/// <see langword="Class"/> in C# and VB respectively.
///
/// Importantly, this does *not* include contextual keywords. If contextual keywords are
/// important for your scenario, use <see cref="IsContextualKeyword"/> or <see
/// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using
/// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know
/// if this is effectively any identifier in the language, regardless of whether the language
/// is treating it as a keyword or not.
/// </summary>
bool IsReservedKeyword(SyntaxToken token);
/// <summary>
/// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A
/// 'contextual' keyword is a identifier that is only treated as being a special keyword in
/// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a
/// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see
/// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not*
/// 'contextual' keywords. This is because they are not treated as keywords depending on
/// the syntactic context around them. Instead, the language always treats them identifiers
/// that have special *semantic* meaning if they end up not binding to an existing symbol.
///
/// Importantly, if <paramref name="token"/> is not in the syntactic construct where the
/// language thinks an identifier should be contextually treated as a keyword, then this
/// will return <see langword="false"/>.
///
/// Or, in other words, the parser must be able to identify these cases in order to be a
/// contextual keyword. If identification happens afterwards, it's not contextual.
/// </summary>
bool IsContextualKeyword(SyntaxToken token);
/// <summary>
/// The set of identifiers that have special meaning directly after the `#` token in a
/// preprocessor directive. For example `if` or `pragma`.
/// </summary>
bool IsPreprocessorKeyword(SyntaxToken token);
bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
bool IsLiteral(SyntaxToken token);
bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token);
bool IsNumericLiteral(SyntaxToken token);
bool IsVerbatimStringLiteral(SyntaxToken token);
bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent);
bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent);
bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node);
bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaration(SyntaxNode node);
bool IsTypeDeclaration(SyntaxNode node);
bool IsRegularComment(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxTrivia trivia);
bool IsElastic(SyntaxTrivia trivia);
bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes);
bool IsDocumentationComment(SyntaxNode node);
bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
string GetText(int kind);
bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken);
bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type);
bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op);
bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info);
bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetObjectCreationInitializer(SyntaxNode node);
SyntaxNode GetObjectCreationType(SyntaxNode node);
bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right);
void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse);
bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression);
bool IsExpressionOfInvocationExpression(SyntaxNode? node);
void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList);
SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node);
bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node);
bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode;
void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken);
bool IsVerbatimInterpolatedStringExpression(SyntaxNode node);
SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node);
SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node);
// Left side of = assignment.
bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement);
void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
// Left side of any assignment (for example = or ??= or *= or += )
bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node);
// Left side of compound assignment (for example ??= or *= or += )
bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node);
bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightSideOfDot(SyntaxNode? node);
/// <summary>
/// Get the node on the left side of the dot if given a dotted expression.
/// </summary>
/// <param name="allowImplicitTarget">
/// In VB, we have a member access expression with a null expression, this may be one of the
/// following forms:
/// 1) new With { .a = 1, .b = .a .a refers to the anonymous type
/// 2) With obj : .m .m refers to the obj type
/// 3) new T() With { .a = 1, .b = .a 'a refers to the T type
/// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null.
/// This parameter has no affect on C# node.
/// </param>
SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false);
bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
[return: NotNullIfNotNull("node")]
SyntaxNode? GetStandaloneExpression(SyntaxNode? node);
/// <summary>
/// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works
/// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in
/// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of
/// a conditional access, and commonly represents the full standalone expression that can be operated on
/// atomically.
/// </summary>
SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node);
bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node);
/// <summary>
/// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/>
/// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/>
/// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed
/// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this
/// may return the expression in the surrounding With-statement.
/// </summary>
SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget = false);
void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name);
SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node);
SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node);
bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetDefaultOfParameter(SyntaxNode? node);
SyntaxNode? GetParameterList(SyntaxNode node);
bool IsParameterList([NotNullWhen(true)] SyntaxNode? node);
bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia);
void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList);
SyntaxNode? GetExpressionOfArgument(SyntaxNode? node);
SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node);
SyntaxNode GetNameOfAttribute(SyntaxNode node);
void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull);
bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node);
SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node);
SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node);
SyntaxToken GetIdentifierOfParameter(SyntaxNode node);
SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node);
SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node);
SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node);
SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node);
/// <summary>
/// True if this is an argument with just an expression and nothing else (i.e. no ref/out,
/// no named params, no omitted args).
/// </summary>
bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsArgument([NotNullWhen(true)] SyntaxNode? node);
RefKind GetRefKindOfArgument(SyntaxNode? node);
void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity);
bool LooksGeneric(SyntaxNode simpleName);
SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? node);
SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node);
SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node);
bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node);
bool IsAttributeName(SyntaxNode node);
SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node);
bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance);
bool IsDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Returns true for nodes that represent the body of a method.
///
/// For VB this will be
/// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator
/// bodies as well as accessor bodies. It will not be true for things like sub() function()
/// lambdas.
///
/// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a
/// method/constructor/deconstructor/operator/accessor. It will not be included for local
/// functions.
/// </summary>
bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node);
bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement);
SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node);
SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node);
SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node);
bool IsThisConstructorInitializer(SyntaxToken token);
bool IsBaseConstructorInitializer(SyntaxToken token);
bool IsQueryKeyword(SyntaxToken token);
bool IsThrowExpression(SyntaxNode node);
bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node);
bool IsIdentifierStartCharacter(char c);
bool IsIdentifierPartCharacter(char c);
bool IsIdentifierEscapeCharacter(char c);
bool IsStartOfUnicodeEscapeSequence(char c);
bool IsValidIdentifier(string identifier);
bool IsVerbatimIdentifier(string identifier);
/// <summary>
/// Returns true if the given character is a character which may be included in an
/// identifier to specify the type of a variable.
/// </summary>
bool IsTypeCharacter(char c);
bool IsBindableToken(SyntaxToken token);
bool IsInStaticContext(SyntaxNode node);
bool IsUnsafeContext(SyntaxNode node);
bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node);
bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n);
bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstructor(SyntaxNode node);
bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node);
bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node);
bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax.
/// </summary>
bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax.
/// In VB, this includes all block statements such as a MultiLineIfBlockSyntax.
/// </summary>
bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node);
IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node);
SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes);
/// <summary>
/// A node that can host a list of statements or a single statement. In addition to
/// every "executable block", this also includes C# embedded statement owners.
/// </summary>
bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node);
IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node);
bool AreEquivalent(SyntaxToken token1, SyntaxToken token2);
bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2);
string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null);
SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position);
SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true);
SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node);
SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false);
SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false);
void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen);
[return: NotNullIfNotNull("node")]
SyntaxNode? WalkDownParentheses(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false);
bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node);
bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node);
List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root);
List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root);
SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration);
SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration);
SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit);
SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration);
SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit);
bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span);
TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body
/// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be
/// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns
/// an empty <see cref="TextSpan"/> at position 0.
/// </summary>
TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node);
/// <summary>
/// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find
/// All References. For example, if the token is part of the type of an object creation, the parenting object
/// creation expression is returned so that binding will return constructor symbols.
/// </summary>
SyntaxNode? TryGetBindableParent(SyntaxToken token);
IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken);
bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of
/// that arguments name.
/// </summary>
string GetNameForArgument(SyntaxNode? argument);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of
/// that arguments name.
/// </summary>
string GetNameForAttributeArgument(SyntaxNode? argument);
bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node);
bool IsPropertyPatternClause(SyntaxNode node);
bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node);
void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen);
void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation);
void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation);
void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern);
SyntaxNode GetTypeOfTypePattern(SyntaxNode node);
/// <summary>
/// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see
/// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/>
/// then the span through the base-list will be considered.
/// </summary>
bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration);
bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter);
bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method);
bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction);
bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration);
bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement);
bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement);
bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement);
bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
SyntaxNode? GetNextExecutableStatement(SyntaxNode statement);
ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node);
TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode;
ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root);
ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken);
bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken);
bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken);
string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken);
SyntaxTokenList GetModifiers(SyntaxNode? node);
SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers);
Location GetDeconstructionReferenceLocation(SyntaxNode node);
SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token);
bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes);
bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node);
SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
bool CanHaveAccessibility(SyntaxNode declaration);
/// <summary>
/// Gets the accessibility of the declaration.
/// </summary>
Accessibility GetAccessibility(SyntaxNode declaration);
void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault);
SyntaxTokenList GetModifierTokens(SyntaxNode? declaration);
/// <summary>
/// Gets the <see cref="DeclarationKind"/> for the declaration.
/// </summary>
DeclarationKind GetDeclarationKind(SyntaxNode declaration);
bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression);
bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node);
}
[Flags]
internal enum DisplayNameOptions
{
None = 0,
IncludeMemberKeyword = 1,
IncludeNamespaces = 1 << 1,
IncludeParameters = 1 << 2,
IncludeType = 1 << 3,
IncludeTypeParameters = 1 << 4
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.Text;
#if CODE_STYLE
using Microsoft.CodeAnalysis.Internal.Editing;
#else
using Microsoft.CodeAnalysis.Editing;
#endif
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal interface ISyntaxFacts
{
bool IsCaseSensitive { get; }
StringComparer StringComparer { get; }
SyntaxTrivia ElasticMarker { get; }
SyntaxTrivia ElasticCarriageReturnLineFeed { get; }
ISyntaxKinds SyntaxKinds { get; }
bool SupportsIndexingInitializer(ParseOptions options);
bool SupportsLocalFunctionDeclaration(ParseOptions options);
bool SupportsNotPattern(ParseOptions options);
bool SupportsRecord(ParseOptions options);
bool SupportsRecordStruct(ParseOptions options);
bool SupportsThrowExpression(ParseOptions options);
SyntaxToken ParseToken(string text);
SyntaxTriviaList ParseLeadingTrivia(string text);
string EscapeIdentifier(string identifier);
bool IsVerbatimIdentifier(SyntaxToken token);
bool IsOperator(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token);
bool IsPredefinedType(SyntaxToken token, PredefinedType type);
bool IsPredefinedOperator(SyntaxToken token);
bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op);
/// <summary>
/// Returns 'true' if this a 'reserved' keyword for the language. A 'reserved' keyword is a
/// identifier that is always treated as being a special keyword, regardless of where it is
/// found in the token stream. Examples of this are tokens like <see langword="class"/> and
/// <see langword="Class"/> in C# and VB respectively.
///
/// Importantly, this does *not* include contextual keywords. If contextual keywords are
/// important for your scenario, use <see cref="IsContextualKeyword"/> or <see
/// cref="ISyntaxFactsExtensions.IsReservedOrContextualKeyword"/>. Also, consider using
/// <see cref="ISyntaxFactsExtensions.IsWord"/> if all you need is the ability to know
/// if this is effectively any identifier in the language, regardless of whether the language
/// is treating it as a keyword or not.
/// </summary>
bool IsReservedKeyword(SyntaxToken token);
/// <summary>
/// Returns <see langword="true"/> if this a 'contextual' keyword for the language. A
/// 'contextual' keyword is a identifier that is only treated as being a special keyword in
/// certain *syntactic* contexts. Examples of this is 'yield' in C#. This is only a
/// keyword if used as 'yield return' or 'yield break'. Importantly, identifiers like <see
/// langword="var"/>, <see langword="dynamic"/> and <see langword="nameof"/> are *not*
/// 'contextual' keywords. This is because they are not treated as keywords depending on
/// the syntactic context around them. Instead, the language always treats them identifiers
/// that have special *semantic* meaning if they end up not binding to an existing symbol.
///
/// Importantly, if <paramref name="token"/> is not in the syntactic construct where the
/// language thinks an identifier should be contextually treated as a keyword, then this
/// will return <see langword="false"/>.
///
/// Or, in other words, the parser must be able to identify these cases in order to be a
/// contextual keyword. If identification happens afterwards, it's not contextual.
/// </summary>
bool IsContextualKeyword(SyntaxToken token);
/// <summary>
/// The set of identifiers that have special meaning directly after the `#` token in a
/// preprocessor directive. For example `if` or `pragma`.
/// </summary>
bool IsPreprocessorKeyword(SyntaxToken token);
bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken);
bool IsLiteral(SyntaxToken token);
bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token);
bool IsNumericLiteral(SyntaxToken token);
bool IsVerbatimStringLiteral(SyntaxToken token);
bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent);
bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent);
bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node);
bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaration(SyntaxNode node);
bool IsTypeDeclaration(SyntaxNode node);
bool IsRegularComment(SyntaxTrivia trivia);
bool IsDocumentationComment(SyntaxTrivia trivia);
bool IsElastic(SyntaxTrivia trivia);
bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes);
bool IsDocumentationComment(SyntaxNode node);
bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node);
string GetText(int kind);
bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken);
bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type);
bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op);
bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? directive, out ExternalSourceInfo info);
bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetObjectCreationInitializer(SyntaxNode node);
SyntaxNode GetObjectCreationType(SyntaxNode node);
bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right);
void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse);
bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression);
bool IsExpressionOfInvocationExpression(SyntaxNode? node);
void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList);
SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node);
bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node);
bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node);
void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node,
out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode;
void GetPartsOfInterpolationExpression(SyntaxNode node,
out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken);
bool IsVerbatimInterpolatedStringExpression(SyntaxNode node);
SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node);
SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node);
// Left side of = assignment.
bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement);
void GetPartsOfAssignmentStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfAssignmentExpressionOrStatement(SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
// Left side of any assignment (for example = or ??= or *= or += )
bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node);
// Left side of compound assignment (for example ??= or *= or += )
bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node);
bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetRightSideOfDot(SyntaxNode? node);
/// <summary>
/// Get the node on the left side of the dot if given a dotted expression.
/// </summary>
/// <param name="allowImplicitTarget">
/// In VB, we have a member access expression with a null expression, this may be one of the
/// following forms:
/// 1) new With { .a = 1, .b = .a .a refers to the anonymous type
/// 2) With obj : .m .m refers to the obj type
/// 3) new T() With { .a = 1, .b = .a 'a refers to the T type
/// If `allowImplicitTarget` is set to true, the returned node will be set to approperiate node, otherwise, it will return null.
/// This parameter has no affect on C# node.
/// </param>
SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget = false);
bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node);
bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
[return: NotNullIfNotNull("node")]
SyntaxNode? GetStandaloneExpression(SyntaxNode? node);
/// <summary>
/// Call on the `.y` part of a `x?.y` to get the entire `x?.y` conditional access expression. This also works
/// when there are multiple chained conditional accesses. For example, calling this on '.y' or '.z' in
/// `x?.y?.z` will both return the full `x?.y?.z` node. This can be used to effectively get 'out' of the RHS of
/// a conditional access, and commonly represents the full standalone expression that can be operated on
/// atomically.
/// </summary>
SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node);
bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode node);
/// <summary>
/// Returns the expression node the member is being accessed off of. If <paramref name="allowImplicitTarget"/>
/// is <see langword="false"/>, this will be the node directly to the left of the dot-token. If <paramref name="allowImplicitTarget"/>
/// is <see langword="true"/>, then this can return another node in the tree that the member will be accessed
/// off of. For example, in VB, if you have a member-access-expression of the form ".Length" then this
/// may return the expression in the surrounding With-statement.
/// </summary>
SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget = false);
void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name);
SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node);
SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node);
bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node);
SyntaxToken? GetNameOfParameter([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetDefaultOfParameter(SyntaxNode? node);
SyntaxNode? GetParameterList(SyntaxNode node);
bool IsParameterList([NotNullWhen(true)] SyntaxNode? node);
bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia);
void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList);
SyntaxNode? GetExpressionOfArgument(SyntaxNode? node);
SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node);
SyntaxNode GetNameOfAttribute(SyntaxNode node);
void GetPartsOfConditionalAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull);
bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node);
SyntaxToken GetIdentifierOfGenericName(SyntaxNode? node);
SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node);
SyntaxToken GetIdentifierOfParameter(SyntaxNode node);
SyntaxToken GetIdentifierOfTypeDeclaration(SyntaxNode node);
SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node);
SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node);
SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node);
/// <summary>
/// True if this is an argument with just an expression and nothing else (i.e. no ref/out,
/// no named params, no omitted args).
/// </summary>
bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node);
bool IsArgument([NotNullWhen(true)] SyntaxNode? node);
RefKind GetRefKindOfArgument(SyntaxNode? node);
void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity);
bool LooksGeneric(SyntaxNode simpleName);
SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? node);
SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? node);
SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode node);
SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode node);
bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node);
bool IsAttributeName(SyntaxNode node);
SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node);
bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node);
bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance);
bool IsDirective([NotNullWhen(true)] SyntaxNode? node);
bool IsStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node);
bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// Returns true for nodes that represent the body of a method.
///
/// For VB this will be
/// MethodBlockBaseSyntax. This will be true for things like constructor, method, operator
/// bodies as well as accessor bodies. It will not be true for things like sub() function()
/// lambdas.
///
/// For C# this will be the BlockSyntax or ArrowExpressionSyntax for a
/// method/constructor/deconstructor/operator/accessor. It will not be included for local
/// functions.
/// </summary>
bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node);
bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement);
SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node);
SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node);
SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node);
bool IsThisConstructorInitializer(SyntaxToken token);
bool IsBaseConstructorInitializer(SyntaxToken token);
bool IsQueryKeyword(SyntaxToken token);
bool IsThrowExpression(SyntaxNode node);
bool IsElementAccessExpression([NotNullWhen(true)] SyntaxNode? node);
bool IsIndexerMemberCRef([NotNullWhen(true)] SyntaxNode? node);
bool IsIdentifierStartCharacter(char c);
bool IsIdentifierPartCharacter(char c);
bool IsIdentifierEscapeCharacter(char c);
bool IsStartOfUnicodeEscapeSequence(char c);
bool IsValidIdentifier(string identifier);
bool IsVerbatimIdentifier(string identifier);
/// <summary>
/// Returns true if the given character is a character which may be included in an
/// identifier to specify the type of a variable.
/// </summary>
bool IsTypeCharacter(char c);
bool IsBindableToken(SyntaxToken token);
bool IsInStaticContext(SyntaxNode node);
bool IsUnsafeContext(SyntaxNode node);
bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node);
bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node);
bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? n);
bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node);
bool IsInConstructor(SyntaxNode node);
bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node);
bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node);
bool HasIncompleteParentMember([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A block that has no semantics other than introducing a new scope. That is only C# BlockSyntax.
/// </summary>
bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node);
/// <summary>
/// A node that contains a list of statements. In C#, this is BlockSyntax and SwitchSectionSyntax.
/// In VB, this includes all block statements such as a MultiLineIfBlockSyntax.
/// </summary>
bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node);
IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node);
SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes);
/// <summary>
/// A node that can host a list of statements or a single statement. In addition to
/// every "executable block", this also includes C# embedded statement owners.
/// </summary>
bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node);
IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node);
bool AreEquivalent(SyntaxToken token1, SyntaxToken token2);
bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2);
string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null);
SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position);
SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true);
SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node);
SyntaxToken FindTokenOnLeftOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false);
SyntaxToken FindTokenOnRightOfPosition(SyntaxNode node, int position, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false);
void GetPartsOfParenthesizedExpression(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen);
[return: NotNullIfNotNull("node")]
SyntaxNode? WalkDownParentheses(SyntaxNode? node);
[return: NotNullIfNotNull("node")]
SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false);
bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node);
bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node);
List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root);
List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root);
SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration);
SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration);
SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit);
SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration);
SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit);
bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span);
TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree tree, int position, CancellationToken cancellationToken);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, return the <see cref="TextSpan"/> representing the span of the member body
/// it is contained within. This <see cref="TextSpan"/> is used to determine whether speculative binding should be
/// used in performance-critical typing scenarios. Note: if this method fails to find a relevant span, it returns
/// an empty <see cref="TextSpan"/> at position 0.
/// </summary>
TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node);
/// <summary>
/// Returns the parent node that binds to the symbols that the IDE prefers for features like Quick Info and Find
/// All References. For example, if the token is part of the type of an object creation, the parenting object
/// creation expression is returned so that binding will return constructor symbols.
/// </summary>
SyntaxNode? TryGetBindableParent(SyntaxToken token);
IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken);
bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents and argument return the string representation of
/// that arguments name.
/// </summary>
string GetNameForArgument(SyntaxNode? argument);
/// <summary>
/// Given a <see cref="SyntaxNode"/>, that represents an attribute argument return the string representation of
/// that arguments name.
/// </summary>
string GetNameForAttributeArgument(SyntaxNode? argument);
bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node);
bool IsPropertyPatternClause(SyntaxNode node);
bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node);
bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node);
bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node);
void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen);
void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right);
void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation);
void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation);
void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern);
SyntaxNode GetTypeOfTypePattern(SyntaxNode node);
/// <summary>
/// <paramref name="fullHeader"/> controls how much of the type header should be considered. If <see
/// langword="false"/> only the span up through the type name will be considered. If <see langword="true"/>
/// then the span through the base-list will be considered.
/// </summary>
bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration);
bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter);
bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method);
bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction);
bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration);
bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement);
bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement);
bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement);
bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration);
SyntaxNode? GetNextExecutableStatement(SyntaxNode statement);
ImmutableArray<SyntaxTrivia> GetLeadingBlankLines(SyntaxNode node);
TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(TSyntaxNode node) where TSyntaxNode : SyntaxNode;
ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxNode root);
ImmutableArray<SyntaxTrivia> GetFileBanner(SyntaxToken firstToken);
bool ContainsInterleavedDirective(SyntaxNode node, CancellationToken cancellationToken);
bool ContainsInterleavedDirective(ImmutableArray<SyntaxNode> nodes, CancellationToken cancellationToken);
string GetBannerText(SyntaxNode? documentationCommentTriviaSyntax, int maxBannerLength, CancellationToken cancellationToken);
SyntaxTokenList GetModifiers(SyntaxNode? node);
SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers);
Location GetDeconstructionReferenceLocation(SyntaxNode node);
SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token);
bool SpansPreprocessorDirective(IEnumerable<SyntaxNode> nodes);
bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node);
SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia);
bool CanHaveAccessibility(SyntaxNode declaration);
/// <summary>
/// Gets the accessibility of the declaration.
/// </summary>
Accessibility GetAccessibility(SyntaxNode declaration);
void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault);
SyntaxTokenList GetModifierTokens(SyntaxNode? declaration);
/// <summary>
/// Gets the <see cref="DeclarationKind"/> for the declaration.
/// </summary>
DeclarationKind GetDeclarationKind(SyntaxNode declaration);
bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node);
SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression);
bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node);
bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node);
}
[Flags]
internal enum DisplayNameOptions
{
None = 0,
IncludeMemberKeyword = 1,
IncludeNamespaces = 1 << 1,
IncludeParameters = 1 << 2,
IncludeType = 1 << 3,
IncludeTypeParameters = 1 << 4
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/CSharp/Portable/Binder/AliasAndExternAliasDirective.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal struct AliasAndExternAliasDirective
{
public readonly AliasSymbol Alias;
public readonly SyntaxReference? ExternAliasDirectiveReference;
public readonly bool SkipInLookup;
public AliasAndExternAliasDirective(AliasSymbol alias, ExternAliasDirectiveSyntax? externAliasDirective, bool skipInLookup)
{
this.Alias = alias;
this.ExternAliasDirectiveReference = externAliasDirective?.GetReference();
this.SkipInLookup = skipInLookup;
}
public ExternAliasDirectiveSyntax? ExternAliasDirective => (ExternAliasDirectiveSyntax?)ExternAliasDirectiveReference?.GetSyntax();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal struct AliasAndExternAliasDirective
{
public readonly AliasSymbol Alias;
public readonly SyntaxReference? ExternAliasDirectiveReference;
public readonly bool SkipInLookup;
public AliasAndExternAliasDirective(AliasSymbol alias, ExternAliasDirectiveSyntax? externAliasDirective, bool skipInLookup)
{
this.Alias = alias;
this.ExternAliasDirectiveReference = externAliasDirective?.GetReference();
this.SkipInLookup = skipInLookup;
}
public ExternAliasDirectiveSyntax? ExternAliasDirective => (ExternAliasDirectiveSyntax?)ExternAliasDirectiveReference?.GetSyntax();
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/Core/Portable/Workspace/Solution/AnalyzerConfigDocument.cs | // Licensed to the .NET Foundation under one or more 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
{
public sealed class AnalyzerConfigDocument : TextDocument
{
internal AnalyzerConfigDocument(Project project, AnalyzerConfigDocumentState state)
: base(project, state, TextDocumentKind.AnalyzerConfigDocument)
{
}
}
}
| // Licensed to the .NET Foundation under one or more 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
{
public sealed class AnalyzerConfigDocument : TextDocument
{
internal AnalyzerConfigDocument(Project project, AnalyzerConfigDocumentState state)
: base(project, state, TextDocumentKind.AnalyzerConfigDocument)
{
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/EditorFeatures/Core/Shared/Options/FeatureOnOffOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
internal static class FeatureOnOffOptions
{
public static readonly PerLanguageOption2<bool> EndConstruct = new(nameof(FeatureOnOffOptions), nameof(EndConstruct), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoEndInsert"));
// This value is only used by Visual Basic, and so is using the old serialization name that was used by VB.
public static readonly PerLanguageOption2<bool> AutomaticInsertionOfAbstractOrInterfaceMembers = new(nameof(FeatureOnOffOptions), nameof(AutomaticInsertionOfAbstractOrInterfaceMembers), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoRequiredMemberInsert"));
public static readonly PerLanguageOption2<bool> LineSeparator = new(nameof(FeatureOnOffOptions), nameof(LineSeparator), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.DisplayLineSeparators" : "TextEditor.%LANGUAGE%.Specific.Line Separator"));
public static readonly PerLanguageOption2<bool> Outlining = new(nameof(FeatureOnOffOptions), nameof(Outlining), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Outlining"));
public static readonly PerLanguageOption2<bool> KeywordHighlighting = new(nameof(FeatureOnOffOptions), nameof(KeywordHighlighting), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightRelatedKeywords" : "TextEditor.%LANGUAGE%.Specific.Keyword Highlighting"));
public static readonly PerLanguageOption2<bool> ReferenceHighlighting = new(nameof(FeatureOnOffOptions), nameof(ReferenceHighlighting), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightReferences" : "TextEditor.%LANGUAGE%.Specific.Reference Highlighting"));
public static readonly PerLanguageOption2<bool> AutoInsertBlockCommentStartString = new(nameof(FeatureOnOffOptions), nameof(AutoInsertBlockCommentStartString), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Insert Block Comment Start String"));
public static readonly PerLanguageOption2<bool> PrettyListing = new(nameof(FeatureOnOffOptions), nameof(PrettyListing), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PrettyListing"));
public static readonly PerLanguageOption2<bool> RenameTrackingPreview = new(nameof(FeatureOnOffOptions), nameof(RenameTrackingPreview), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.RenameTrackingPreview" : "TextEditor.%LANGUAGE%.Specific.Rename Tracking Preview"));
/// <summary>
/// This option is currently used by Roslyn, but we might want to implement it in the
/// future. Keeping the option while it's unimplemented allows all upgrade paths to
/// maintain any customized value for this setting, even through versions that have not
/// implemented this feature yet.
/// </summary>
public static readonly PerLanguageOption2<bool> RenameTracking = new(nameof(FeatureOnOffOptions), nameof(RenameTracking), defaultValue: true);
/// <summary>
/// This option is currently used by Roslyn, but we might want to implement it in the
/// future. Keeping the option while it's unimplemented allows all upgrade paths to
/// maintain any customized value for this setting, even through versions that have not
/// implemented this feature yet.
/// </summary>
public static readonly PerLanguageOption2<bool> RefactoringVerification = new(
nameof(FeatureOnOffOptions), nameof(RefactoringVerification), defaultValue: false);
public static readonly PerLanguageOption2<bool> StreamingGoToImplementation = new(
nameof(FeatureOnOffOptions), nameof(StreamingGoToImplementation), defaultValue: true);
public static readonly Option2<bool> NavigateToDecompiledSources = new(
nameof(FeatureOnOffOptions), nameof(NavigateToDecompiledSources), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(NavigateToDecompiledSources)}"));
public static readonly Option2<int> UseEnhancedColors = new(
nameof(FeatureOnOffOptions), nameof(UseEnhancedColors), defaultValue: 1,
storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages"));
public static readonly PerLanguageOption2<bool?> AddImportsOnPaste = new(
nameof(FeatureOnOffOptions), nameof(AddImportsOnPaste), defaultValue: null,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(AddImportsOnPaste)}"));
public static readonly Option2<bool?> OfferRemoveUnusedReferences = new(
nameof(FeatureOnOffOptions), nameof(OfferRemoveUnusedReferences), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(OfferRemoveUnusedReferences)}"));
public static readonly PerLanguageOption2<bool?> ShowInheritanceMargin =
new(nameof(FeatureOnOffOptions),
nameof(ShowInheritanceMargin),
defaultValue: true,
new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowInheritanceMargin"));
public static readonly Option2<bool> AutomaticallyCompleteStatementOnSemicolon = new(
nameof(FeatureOnOffOptions), nameof(AutomaticallyCompleteStatementOnSemicolon), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(AutomaticallyCompleteStatementOnSemicolon)}"));
public static readonly Option2<bool> SkipAnalyzersForImplicitlyTriggeredBuilds = new(
nameof(FeatureOnOffOptions), nameof(SkipAnalyzersForImplicitlyTriggeredBuilds), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(SkipAnalyzersForImplicitlyTriggeredBuilds)}"));
}
[ExportOptionProvider, Shared]
internal class FeatureOnOffOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FeatureOnOffOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
FeatureOnOffOptions.EndConstruct,
FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers,
FeatureOnOffOptions.LineSeparator,
FeatureOnOffOptions.Outlining,
FeatureOnOffOptions.KeywordHighlighting,
FeatureOnOffOptions.ReferenceHighlighting,
FeatureOnOffOptions.AutoInsertBlockCommentStartString,
FeatureOnOffOptions.PrettyListing,
FeatureOnOffOptions.RenameTrackingPreview,
FeatureOnOffOptions.RenameTracking,
FeatureOnOffOptions.RefactoringVerification,
FeatureOnOffOptions.StreamingGoToImplementation,
FeatureOnOffOptions.NavigateToDecompiledSources,
FeatureOnOffOptions.UseEnhancedColors,
FeatureOnOffOptions.AddImportsOnPaste,
FeatureOnOffOptions.OfferRemoveUnusedReferences,
FeatureOnOffOptions.ShowInheritanceMargin,
FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon,
FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.InheritanceMargin;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.Editor.Shared.Options
{
internal static class FeatureOnOffOptions
{
public static readonly PerLanguageOption2<bool> EndConstruct = new(nameof(FeatureOnOffOptions), nameof(EndConstruct), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoEndInsert"));
// This value is only used by Visual Basic, and so is using the old serialization name that was used by VB.
public static readonly PerLanguageOption2<bool> AutomaticInsertionOfAbstractOrInterfaceMembers = new(nameof(FeatureOnOffOptions), nameof(AutomaticInsertionOfAbstractOrInterfaceMembers), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.AutoRequiredMemberInsert"));
public static readonly PerLanguageOption2<bool> LineSeparator = new(nameof(FeatureOnOffOptions), nameof(LineSeparator), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.DisplayLineSeparators" : "TextEditor.%LANGUAGE%.Specific.Line Separator"));
public static readonly PerLanguageOption2<bool> Outlining = new(nameof(FeatureOnOffOptions), nameof(Outlining), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Outlining"));
public static readonly PerLanguageOption2<bool> KeywordHighlighting = new(nameof(FeatureOnOffOptions), nameof(KeywordHighlighting), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightRelatedKeywords" : "TextEditor.%LANGUAGE%.Specific.Keyword Highlighting"));
public static readonly PerLanguageOption2<bool> ReferenceHighlighting = new(nameof(FeatureOnOffOptions), nameof(ReferenceHighlighting), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.EnableHighlightReferences" : "TextEditor.%LANGUAGE%.Specific.Reference Highlighting"));
public static readonly PerLanguageOption2<bool> AutoInsertBlockCommentStartString = new(nameof(FeatureOnOffOptions), nameof(AutoInsertBlockCommentStartString), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.Auto Insert Block Comment Start String"));
public static readonly PerLanguageOption2<bool> PrettyListing = new(nameof(FeatureOnOffOptions), nameof(PrettyListing), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PrettyListing"));
public static readonly PerLanguageOption2<bool> RenameTrackingPreview = new(nameof(FeatureOnOffOptions), nameof(RenameTrackingPreview), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation(language => language == LanguageNames.VisualBasic ? "TextEditor.%LANGUAGE%.Specific.RenameTrackingPreview" : "TextEditor.%LANGUAGE%.Specific.Rename Tracking Preview"));
/// <summary>
/// This option is currently used by Roslyn, but we might want to implement it in the
/// future. Keeping the option while it's unimplemented allows all upgrade paths to
/// maintain any customized value for this setting, even through versions that have not
/// implemented this feature yet.
/// </summary>
public static readonly PerLanguageOption2<bool> RenameTracking = new(nameof(FeatureOnOffOptions), nameof(RenameTracking), defaultValue: true);
/// <summary>
/// This option is currently used by Roslyn, but we might want to implement it in the
/// future. Keeping the option while it's unimplemented allows all upgrade paths to
/// maintain any customized value for this setting, even through versions that have not
/// implemented this feature yet.
/// </summary>
public static readonly PerLanguageOption2<bool> RefactoringVerification = new(
nameof(FeatureOnOffOptions), nameof(RefactoringVerification), defaultValue: false);
public static readonly PerLanguageOption2<bool> StreamingGoToImplementation = new(
nameof(FeatureOnOffOptions), nameof(StreamingGoToImplementation), defaultValue: true);
public static readonly Option2<bool> NavigateToDecompiledSources = new(
nameof(FeatureOnOffOptions), nameof(NavigateToDecompiledSources), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(NavigateToDecompiledSources)}"));
public static readonly Option2<int> UseEnhancedColors = new(
nameof(FeatureOnOffOptions), nameof(UseEnhancedColors), defaultValue: 1,
storageLocations: new RoamingProfileStorageLocation("WindowManagement.Options.UseEnhancedColorsForManagedLanguages"));
public static readonly PerLanguageOption2<bool?> AddImportsOnPaste = new(
nameof(FeatureOnOffOptions), nameof(AddImportsOnPaste), defaultValue: null,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(AddImportsOnPaste)}"));
public static readonly Option2<bool?> OfferRemoveUnusedReferences = new(
nameof(FeatureOnOffOptions), nameof(OfferRemoveUnusedReferences), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(OfferRemoveUnusedReferences)}"));
public static readonly PerLanguageOption2<bool?> ShowInheritanceMargin =
new(nameof(FeatureOnOffOptions),
nameof(ShowInheritanceMargin),
defaultValue: true,
new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.ShowInheritanceMargin"));
public static readonly Option2<bool> AutomaticallyCompleteStatementOnSemicolon = new(
nameof(FeatureOnOffOptions), nameof(AutomaticallyCompleteStatementOnSemicolon), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(AutomaticallyCompleteStatementOnSemicolon)}"));
public static readonly Option2<bool> SkipAnalyzersForImplicitlyTriggeredBuilds = new(
nameof(FeatureOnOffOptions), nameof(SkipAnalyzersForImplicitlyTriggeredBuilds), defaultValue: true,
storageLocations: new RoamingProfileStorageLocation($"TextEditor.{nameof(SkipAnalyzersForImplicitlyTriggeredBuilds)}"));
}
[ExportOptionProvider, Shared]
internal class FeatureOnOffOptionsProvider : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FeatureOnOffOptionsProvider()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
FeatureOnOffOptions.EndConstruct,
FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers,
FeatureOnOffOptions.LineSeparator,
FeatureOnOffOptions.Outlining,
FeatureOnOffOptions.KeywordHighlighting,
FeatureOnOffOptions.ReferenceHighlighting,
FeatureOnOffOptions.AutoInsertBlockCommentStartString,
FeatureOnOffOptions.PrettyListing,
FeatureOnOffOptions.RenameTrackingPreview,
FeatureOnOffOptions.RenameTracking,
FeatureOnOffOptions.RefactoringVerification,
FeatureOnOffOptions.StreamingGoToImplementation,
FeatureOnOffOptions.NavigateToDecompiledSources,
FeatureOnOffOptions.UseEnhancedColors,
FeatureOnOffOptions.AddImportsOnPaste,
FeatureOnOffOptions.OfferRemoveUnusedReferences,
FeatureOnOffOptions.ShowInheritanceMargin,
FeatureOnOffOptions.AutomaticallyCompleteStatementOnSemicolon,
FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds);
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/CSharp/Portable/Lowering/DiagnosticsPass_Warnings.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This pass detects and reports diagnostics that do not affect lambda convertibility.
/// This part of the partial class focuses on expression and operator warnings.
/// </summary>
internal sealed partial class DiagnosticsPass : BoundTreeWalkerWithStackGuard
{
private void CheckArguments(ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<BoundExpression> arguments, Symbol method)
{
if (!argumentRefKindsOpt.IsDefault)
{
Debug.Assert(arguments.Length == argumentRefKindsOpt.Length);
for (int i = 0; i < arguments.Length; i++)
{
if (argumentRefKindsOpt[i] != RefKind.None)
{
var argument = arguments[i];
switch (argument.Kind)
{
case BoundKind.FieldAccess:
CheckFieldAddress((BoundFieldAccess)argument, method);
break;
case BoundKind.Local:
var local = (BoundLocal)argument;
if (local.Syntax.Kind() == SyntaxKind.DeclarationExpression)
{
CheckOutDeclaration(local);
}
break;
case BoundKind.DiscardExpression:
CheckDiscard((BoundDiscardExpression)argument);
break;
}
}
}
}
}
/// <remarks>
/// This is for when we are taking the address of a field.
/// Distinguish from <see cref="CheckFieldAsReceiver"/>.
/// </remarks>
private void CheckFieldAddress(BoundFieldAccess fieldAccess, Symbol consumerOpt)
{
FieldSymbol fieldSymbol = fieldAccess.FieldSymbol;
// We can safely suppress this warning when calling an Interlocked API
if (fieldSymbol.IsVolatile && ((object)consumerOpt == null || !IsInterlockedAPI(consumerOpt)))
{
Error(ErrorCode.WRN_VolatileByRef, fieldAccess, fieldSymbol);
}
if (IsNonAgileFieldAccess(fieldAccess, _compilation))
{
Error(ErrorCode.WRN_ByRefNonAgileField, fieldAccess, fieldSymbol);
}
}
/// <remarks>
/// This is for when we are dotting into a field.
/// Distinguish from <see cref="CheckFieldAddress"/>.
///
/// NOTE: dev11 also calls this on string initializers in fixed statements,
/// but never accomplishes anything since string is a reference type. This
/// is probably a bug, but fixing it would be a breaking change.
/// </remarks>
private void CheckFieldAsReceiver(BoundFieldAccess fieldAccess)
{
// From ExpressionBinder.cpp:
// Taking the address of a field is suspect if the type is marshalbyref.
// REVIEW ShonK: Is this really the best way to handle this? It'd be so much more
// bullet proof for ilgen to error when it spits out the ldflda....
FieldSymbol fieldSymbol = fieldAccess.FieldSymbol;
if (IsNonAgileFieldAccess(fieldAccess, _compilation) && !fieldSymbol.Type.IsReferenceType)
{
Error(ErrorCode.WRN_CallOnNonAgileField, fieldAccess, fieldSymbol);
}
}
private void CheckReceiverIfField(BoundExpression receiverOpt)
{
if (receiverOpt != null && receiverOpt.Kind == BoundKind.FieldAccess)
{
CheckFieldAsReceiver((BoundFieldAccess)receiverOpt);
}
}
/// <remarks>
/// Based on OutputContext::IsNonAgileField.
/// </remarks>
internal static bool IsNonAgileFieldAccess(BoundFieldAccess fieldAccess, CSharpCompilation compilation)
{
// Warn if taking the address of a non-static field with a receiver other than this (possibly cast)
// and a type that descends from System.MarshalByRefObject.
if (IsInstanceFieldAccessWithNonThisReceiver(fieldAccess))
{
// NOTE: We're only trying to produce a warning, so there's no point in producing an
// error if the well-known type we need for the check is missing.
NamedTypeSymbol marshalByRefType = compilation.GetWellKnownType(WellKnownType.System_MarshalByRefObject);
TypeSymbol baseType = fieldAccess.FieldSymbol.ContainingType;
while ((object)baseType != null)
{
if (TypeSymbol.Equals(baseType, marshalByRefType, TypeCompareKind.ConsiderEverything))
{
return true;
}
// NOTE: We're only trying to produce a warning, so there's no point in producing a
// use site diagnostic if we can't walk up the base type hierarchy.
baseType = baseType.BaseTypeNoUseSiteDiagnostics;
}
}
return false;
}
private static bool IsInstanceFieldAccessWithNonThisReceiver(BoundFieldAccess fieldAccess)
{
BoundExpression receiver = fieldAccess.ReceiverOpt;
if (receiver == null || fieldAccess.FieldSymbol.IsStatic)
{
return false;
}
while (receiver.Kind == BoundKind.Conversion)
{
BoundConversion conversion = (BoundConversion)receiver;
if (conversion.ExplicitCastInCode) break;
receiver = conversion.Operand;
}
return receiver.Kind != BoundKind.ThisReference && receiver.Kind != BoundKind.BaseReference;
}
private bool IsInterlockedAPI(Symbol method)
{
var interlocked = _compilation.GetWellKnownType(WellKnownType.System_Threading_Interlocked);
if ((object)interlocked != null && TypeSymbol.Equals(interlocked, method.ContainingType, TypeCompareKind.ConsiderEverything2))
return true;
return false;
}
private static BoundExpression StripImplicitCasts(BoundExpression expr)
{
BoundExpression current = expr;
while (true)
{
// CONSIDER: Dev11 doesn't strip conversions to float or double.
BoundConversion conversion = current as BoundConversion;
if (conversion == null || !conversion.ConversionKind.IsImplicitConversion())
{
return current;
}
current = conversion.Operand;
}
}
private static bool IsSameLocalOrField(BoundExpression expr1, BoundExpression expr2)
{
if (expr1 == null && expr2 == null)
{
return true;
}
if (expr1 == null || expr2 == null)
{
return false;
}
if (expr1.HasAnyErrors || expr2.HasAnyErrors)
{
return false;
}
expr1 = StripImplicitCasts(expr1);
expr2 = StripImplicitCasts(expr2);
if (expr1.Kind != expr2.Kind)
{
return false;
}
switch (expr1.Kind)
{
case BoundKind.Local:
var local1 = (BoundLocal)expr1;
var local2 = (BoundLocal)expr2;
return local1.LocalSymbol == local2.LocalSymbol;
case BoundKind.FieldAccess:
var field1 = (BoundFieldAccess)expr1;
var field2 = (BoundFieldAccess)expr2;
return field1.FieldSymbol == field2.FieldSymbol &&
(field1.FieldSymbol.IsStatic || IsSameLocalOrField(field1.ReceiverOpt, field2.ReceiverOpt));
case BoundKind.EventAccess:
var event1 = (BoundEventAccess)expr1;
var event2 = (BoundEventAccess)expr2;
return event1.EventSymbol == event2.EventSymbol &&
(event1.EventSymbol.IsStatic || IsSameLocalOrField(event1.ReceiverOpt, event2.ReceiverOpt));
case BoundKind.Parameter:
var param1 = (BoundParameter)expr1;
var param2 = (BoundParameter)expr2;
return param1.ParameterSymbol == param2.ParameterSymbol;
case BoundKind.RangeVariable:
var rangeVar1 = (BoundRangeVariable)expr1;
var rangeVar2 = (BoundRangeVariable)expr2;
return rangeVar1.RangeVariableSymbol == rangeVar2.RangeVariableSymbol;
case BoundKind.ThisReference:
case BoundKind.PreviousSubmissionReference:
case BoundKind.HostObjectMemberReference:
Debug.Assert(TypeSymbol.Equals(expr1.Type, expr2.Type, TypeCompareKind.ConsiderEverything2));
return true;
default:
return false;
}
}
private static bool IsComCallWithRefOmitted(MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt)
{
if (method.ParameterCount != arguments.Length ||
(object)method.ContainingType == null ||
!method.ContainingType.IsComImport)
return false;
for (int i = 0; i < arguments.Length; i++)
{
if (method.Parameters[i].RefKind != RefKind.None && (argumentRefKindsOpt.IsDefault || argumentRefKindsOpt[i] == RefKind.None)) return true;
}
return false;
}
private void CheckBinaryOperator(BoundBinaryOperator node)
{
if (node.Method is MethodSymbol method)
{
if (_inExpressionLambda && method.IsAbstract && method.IsStatic)
{
Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node);
}
}
else
{
CheckUnsafeType(node.Left);
CheckUnsafeType(node.Right);
}
CheckForBitwiseOrSignExtend(node, node.OperatorKind, node.Left, node.Right);
CheckNullableNullBinOp(node);
CheckLiftedBinOp(node);
CheckRelationals(node);
CheckDynamic(node);
}
private void CheckCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
BoundExpression left = node.Left;
if (!node.Operator.Kind.IsDynamic() && !node.LeftConversion.IsIdentity && node.LeftConversion.Exists)
{
// Need to represent the implicit conversion as a node in order to be able to produce correct diagnostics.
left = new BoundConversion(left.Syntax, left, node.LeftConversion, node.Operator.Kind.IsChecked(),
explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: node.Operator.LeftType);
}
CheckForBitwiseOrSignExtend(node, node.Operator.Kind, left, node.Right);
CheckLiftedCompoundAssignment(node);
if (_inExpressionLambda)
{
Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node);
}
}
private void CheckRelationals(BoundBinaryOperator node)
{
Debug.Assert(node != null);
if (!node.OperatorKind.IsComparison())
{
return;
}
// Don't bother to check vacuous comparisons where both sides are constant, eg, where someone
// is doing something like "if (0xFFFFFFFFU == 0)" -- these are likely to be machine-
// generated code.
if (node.Left.ConstantValue != null && node.Right.ConstantValue == null && node.Right.Kind == BoundKind.Conversion)
{
CheckVacuousComparisons(node, node.Left.ConstantValue, node.Right);
}
if (node.Right.ConstantValue != null && node.Left.ConstantValue == null && node.Left.Kind == BoundKind.Conversion)
{
CheckVacuousComparisons(node, node.Right.ConstantValue, node.Left);
}
if (node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual)
{
TypeSymbol t;
if (node.Left.Type.SpecialType == SpecialType.System_Object && !IsExplicitCast(node.Left) && !(node.Left.ConstantValue != null && node.Left.ConstantValue.IsNull) && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
{
// Possible unintended reference comparison; to get a value comparison, cast the left hand side to type '{0}'
_diagnostics.Add(ErrorCode.WRN_BadRefCompareLeft, node.Syntax.Location, t);
}
else if (node.Right.Type.SpecialType == SpecialType.System_Object && !IsExplicitCast(node.Right) && !(node.Right.ConstantValue != null && node.Right.ConstantValue.IsNull) && ConvertedHasEqual(node.OperatorKind, node.Left, out t))
{
// Possible unintended reference comparison; to get a value comparison, cast the right hand side to type '{0}'
_diagnostics.Add(ErrorCode.WRN_BadRefCompareRight, node.Syntax.Location, t);
}
}
CheckSelfComparisons(node);
}
private static bool IsExplicitCast(BoundExpression node)
{
return node.Kind == BoundKind.Conversion && ((BoundConversion)node).ExplicitCastInCode;
}
private static bool ConvertedHasEqual(BinaryOperatorKind oldOperatorKind, BoundNode node, out TypeSymbol type)
{
type = null;
if (node.Kind != BoundKind.Conversion) return false;
var conv = (BoundConversion)node;
if (conv.ExplicitCastInCode) return false;
NamedTypeSymbol nt = conv.Operand.Type as NamedTypeSymbol;
if ((object)nt == null || !nt.IsReferenceType || nt.IsInterface)
{
return false;
}
string opName = (oldOperatorKind == BinaryOperatorKind.ObjectEqual) ? WellKnownMemberNames.EqualityOperatorName : WellKnownMemberNames.InequalityOperatorName;
for (var t = nt; (object)t != null; t = t.BaseTypeNoUseSiteDiagnostics)
{
foreach (var sym in t.GetMembers(opName))
{
MethodSymbol op = sym as MethodSymbol;
if ((object)op == null || op.MethodKind != MethodKind.UserDefinedOperator) continue;
var parameters = op.GetParameters();
if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, t, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(parameters[1].Type, t, TypeCompareKind.ConsiderEverything2))
{
type = t;
return true;
}
}
}
return false;
}
private void CheckSelfComparisons(BoundBinaryOperator node)
{
Debug.Assert(node != null);
Debug.Assert(node.OperatorKind.IsComparison());
if (!node.HasAnyErrors && IsSameLocalOrField(node.Left, node.Right))
{
Error(ErrorCode.WRN_ComparisonToSelf, node);
}
}
private void CheckVacuousComparisons(BoundBinaryOperator tree, ConstantValue constantValue, BoundNode operand)
{
Debug.Assert(tree != null);
Debug.Assert(constantValue != null);
Debug.Assert(operand != null);
// We wish to detect comparisons between integers and constants which are likely to be wrong
// because we know at compile time whether they will be true or false. For example:
//
// const short s = 1000;
// byte b = whatever;
// if (b < s)
//
// We know that this will always be true because when b and s are both converted to int for
// the comparison, the left side will always be less than the right side.
//
// We only give the warning if there is no explicit conversion involved on the operand.
// For example, if we had:
//
// const uint s = 1000;
// sbyte b = whatever;
// if ((byte)b < s)
//
// Then we do not give a warning.
//
// Note that the native compiler has what looks to be some dead code. It checks to see
// if the conversion on the operand is from an enum type. But this is unnecessary if
// we are rejecting cases with explicit conversions. The only possible cases are:
//
// enum == enumConstant -- enum types must be the same, so it must be in range.
// enum == integralConstant -- not legal unless the constant is zero, which is in range.
// enum == (ENUM)anyConstant -- if the constant is out of range then this is not legal in the first place
// unless we're in an unchecked context, in which case, the user probably does
// not want the warning.
// integral == enumConstant -- never legal in the first place
//
// Since it seems pointless to try to check enums, we simply look for vacuous comparisons of
// integral types here.
for (BoundConversion conversion = operand as BoundConversion;
conversion != null;
conversion = conversion.Operand as BoundConversion)
{
if (conversion.ConversionKind != ConversionKind.ImplicitNumeric &&
conversion.ConversionKind != ConversionKind.ImplicitConstant)
{
return;
}
// As in dev11, we don't dig through explicit casts (see ExpressionBinder::WarnAboutBadRelationals).
if (conversion.ExplicitCastInCode)
{
return;
}
if (!conversion.Operand.Type.SpecialType.IsIntegralType() || !conversion.Type.SpecialType.IsIntegralType())
{
return;
}
if (!Binder.CheckConstantBounds(conversion.Operand.Type.SpecialType, constantValue, out _))
{
Error(ErrorCode.WRN_VacuousIntegralComp, tree, conversion.Operand.Type);
return;
}
}
}
private void CheckForBitwiseOrSignExtend(BoundExpression node, BinaryOperatorKind operatorKind, BoundExpression leftOperand, BoundExpression rightOperand)
{
// We wish to give a warning for situations where an unexpected sign extension wipes
// out some bits. For example:
//
// int x = 0x0ABC0000;
// short y = -2; // 0xFFFE
// int z = x | y;
//
// The user might naively expect the result to be 0x0ABCFFFE. But the short is sign-extended
// when it is converted to int before the bitwise or, so this is in fact the same as:
//
// int x = 0x0ABC0000;
// short y = -2; // 0xFFFE
// int ytemp = y; // 0xFFFFFFFE
// int z = x | ytemp;
//
// Which gives 0xFFFFFFFE, not 0x0ABCFFFE.
//
// However, we wish to suppress the warning if:
//
// * The sign extension is "expected" -- for instance, because there was an explicit cast
// from short to int: "int z = x | (int)y;" should not produce the warning.
// Note that "uint z = (uint)x | (uint)y;" should still produce the warning because
// the user might not realize that converting y to uint does a sign extension.
//
// * There is the same amount of sign extension on both sides. For example, when
// doing "short | sbyte", both sides are sign extended. The left creates two FF bytes
// and the right creates three, so we are potentially wiping out information from the
// left side. But "short | short" adds two FF bytes on both sides, so no information is lost.
//
// The native compiler also suppresses this warning in a bizarre and inconsistent way. If
// the side whose bits are going to be wiped out by sign extension is a *constant*, then the
// warning is suppressed *if the constant, when converted to a signed long, fits into the
// range of the type that is being sign-extended.*
//
// Consider the effects of this rule:
//
// (uint)0xFFFF0000 | y -- gives the warning because 0xFFFF0000 as a long is not in the range of a short,
// *even though the result will not be affected by the sign extension*.
// (ulong)0xFFFFFFFFFFFFFFFF | y -- suppresses the warning, because 0xFFFFFFFFFFFFFFFF as a signed long fits into a short.
// (int)0x0000ABCD | y -- suppresses the warning, even though the 0000 is going to be wiped out by the sign extension.
//
// It seems clear that the intention of the heuristic is to *suppress the warning when the bits being hammered
// on are either all zero, or all one.* Therefore that is the heuristic we will *actually* implement here.
//
switch (operatorKind)
{
case BinaryOperatorKind.LiftedUIntOr:
case BinaryOperatorKind.LiftedIntOr:
case BinaryOperatorKind.LiftedULongOr:
case BinaryOperatorKind.LiftedLongOr:
case BinaryOperatorKind.UIntOr:
case BinaryOperatorKind.IntOr:
case BinaryOperatorKind.ULongOr:
case BinaryOperatorKind.LongOr:
break;
default:
return;
}
// The native compiler skips this warning if both sides of the operator are constants.
//
// CONSIDER: Is that sensible? It seems reasonable that if we would warn on int | short
// when they are non-constants, or when one is a constant, that we would similarly warn
// when both are constants.
if (node.ConstantValue != null)
{
return;
}
// Start by determining *which bits on each side are going to be unexpectedly turned on*.
ulong left = FindSurprisingSignExtensionBits(leftOperand);
ulong right = FindSurprisingSignExtensionBits(rightOperand);
// If they are all the same then there's no warning to give.
if (left == right)
{
return;
}
// Suppress the warning if one side is a constant, and either all the unexpected
// bits are already off, or all the unexpected bits are already on.
ConstantValue constVal = GetConstantValueForBitwiseOrCheck(leftOperand);
if (constVal != null)
{
ulong val = constVal.UInt64Value;
if ((val & right) == right || (~val & right) == right)
{
return;
}
}
constVal = GetConstantValueForBitwiseOrCheck(rightOperand);
if (constVal != null)
{
ulong val = constVal.UInt64Value;
if ((val & left) == left || (~val & left) == left)
{
return;
}
}
// CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first
Error(ErrorCode.WRN_BitwiseOrSignExtend, node);
}
private static ConstantValue GetConstantValueForBitwiseOrCheck(BoundExpression operand)
{
// We might have a nullable conversion on top of an integer constant. But only dig out
// one level.
if (operand.Kind == BoundKind.Conversion)
{
BoundConversion conv = (BoundConversion)operand;
if (conv.ConversionKind == ConversionKind.ImplicitNullable)
{
operand = conv.Operand;
}
}
ConstantValue constVal = operand.ConstantValue;
if (constVal == null || !constVal.IsIntegral)
{
return null;
}
return constVal;
}
// A "surprising" sign extension is:
//
// * a conversion with no cast in source code that goes from a smaller
// signed type to a larger signed or unsigned type.
//
// * a conversion (with or without a cast) from a smaller
// signed type to a larger unsigned type.
private static ulong FindSurprisingSignExtensionBits(BoundExpression expr)
{
if (expr.Kind != BoundKind.Conversion)
{
return 0;
}
BoundConversion conv = (BoundConversion)expr;
TypeSymbol from = conv.Operand.Type;
TypeSymbol to = conv.Type;
if ((object)from == null || (object)to == null)
{
return 0;
}
if (from.IsNullableType())
{
from = from.GetNullableUnderlyingType();
}
if (to.IsNullableType())
{
to = to.GetNullableUnderlyingType();
}
SpecialType fromSpecialType = from.SpecialType;
SpecialType toSpecialType = to.SpecialType;
if (!fromSpecialType.IsIntegralType() || !toSpecialType.IsIntegralType())
{
return 0;
}
int fromSize = fromSpecialType.SizeInBytes();
int toSize = toSpecialType.SizeInBytes();
if (fromSize == 0 || toSize == 0)
{
return 0;
}
// The operand might itself be a conversion, and might be contributing
// surprising bits. We might have more, fewer or the same surprising bits
// as the operand.
ulong recursive = FindSurprisingSignExtensionBits(conv.Operand);
if (fromSize == toSize)
{
// No change.
return recursive;
}
if (toSize < fromSize)
{
// We are casting from a larger type to a smaller type, and are therefore
// losing surprising bits.
switch (toSize)
{
case 1: return unchecked((ulong)(byte)recursive);
case 2: return unchecked((ulong)(ushort)recursive);
case 4: return unchecked((ulong)(uint)recursive);
}
Debug.Assert(false, "How did we get here?");
return recursive;
}
// We are converting from a smaller type to a larger type, and therefore might
// be adding surprising bits. First of all, the smaller type has got to be signed
// for there to be sign extension.
bool fromSigned = fromSpecialType.IsSignedIntegralType();
if (!fromSigned)
{
return recursive;
}
// OK, we know that the "from" type is a signed integer that is smaller than the
// "to" type, so we are going to have sign extension. Is it surprising? The only
// time that sign extension is *not* surprising is when we have a cast operator
// to a *signed* type. That is, (int)myShort is not a surprising sign extension.
if (conv.ExplicitCastInCode && toSpecialType.IsSignedIntegralType())
{
return recursive;
}
// Note that we *could* be somewhat more clever here. Consider the following edge case:
//
// (ulong)(int)(uint)(ushort)mySbyte
//
// We could reason that the sbyte-to-ushort conversion is going to add one byte of
// unexpected sign extension. The conversion from ushort to uint adds no more bytes.
// The conversion from uint to int adds no more bytes. Does the conversion from int
// to ulong add any more bytes of unexpected sign extension? Well, no, because we
// know that the previous conversion from ushort to uint will ensure that the top bit
// of the uint is off!
//
// But we are not going to try to be that clever. In the extremely unlikely event that
// someone does this, we will record that the unexpectedly turned-on bits are
// 0xFFFFFFFF0000FF00, even though we could in theory deduce that only 0x000000000000FF00
// are the unexpected bits.
ulong result = recursive;
for (int i = fromSize; i < toSize; ++i)
{
result |= (0xFFUL) << (i * 8);
}
return result;
}
private void CheckLiftedCompoundAssignment(BoundCompoundAssignmentOperator node)
{
Debug.Assert(node != null);
if (!node.Operator.Kind.IsLifted())
{
return;
}
// CS0458: The result of the expression is always 'null' of type '{0}'
if (node.Right.NullableNeverHasValue())
{
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
}
}
private void CheckLiftedUnaryOp(BoundUnaryOperator node)
{
Debug.Assert(node != null);
if (!node.OperatorKind.IsLifted())
{
return;
}
// CS0458: The result of the expression is always 'null' of type '{0}'
if (node.Operand.NullableNeverHasValue())
{
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
}
}
private void CheckNullableNullBinOp(BoundBinaryOperator node)
{
if (node.OperatorKind.OperandTypes() != BinaryOperatorKind.NullableNull)
{
return;
}
switch (node.OperatorKind.Operator())
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
// CS0472: The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}'
//
// Produce the warning if one side is always null and the other is never null.
// That is, we have something like "if (myInt == null)"
string always = node.OperatorKind.Operator() == BinaryOperatorKind.NotEqual ? "true" : "false";
// we use a separate warning code for cases newly detected in later versions of the compiler
if (node.Right.IsLiteralNull() && node.Left.NullableAlwaysHasValue())
{
Error(ErrorCode.WRN_NubExprIsConstBool, node, always, node.Left.Type.GetNullableUnderlyingType(), node.Left.Type);
}
else if (node.Left.IsLiteralNull() && node.Right.NullableAlwaysHasValue())
{
Error(ErrorCode.WRN_NubExprIsConstBool, node, always, node.Right.Type.GetNullableUnderlyingType(), node.Right.Type);
}
break;
}
}
private void CheckLiftedBinOp(BoundBinaryOperator node)
{
Debug.Assert(node != null);
if (!node.OperatorKind.IsLifted())
{
return;
}
switch (node.OperatorKind.Operator())
{
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
// CS0464: Comparing with null of type '{0}' always produces 'false'
//
// Produce the warning if one (or both) sides are always null.
if (node.Right.NullableNeverHasValue())
{
Error(ErrorCode.WRN_CmpAlwaysFalse, node, GetTypeForLiftedComparisonWarning(node.Right));
}
else if (node.Left.NullableNeverHasValue())
{
Error(ErrorCode.WRN_CmpAlwaysFalse, node, GetTypeForLiftedComparisonWarning(node.Left));
}
break;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
// CS0472: The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}'
//
// Produce the warning if one side is always null and the other is never null.
// That is, we have something like "if (myInt == null)"
string always = node.OperatorKind.Operator() == BinaryOperatorKind.NotEqual ? "true" : "false";
if (node.Right.NullableNeverHasValue() && node.Left.NullableAlwaysHasValue())
{
Error(node.OperatorKind.IsUserDefined() ? ErrorCode.WRN_NubExprIsConstBool2 : ErrorCode.WRN_NubExprIsConstBool, node, always, node.Left.Type.GetNullableUnderlyingType(), GetTypeForLiftedComparisonWarning(node.Right));
}
else if (node.Left.NullableNeverHasValue() && node.Right.NullableAlwaysHasValue())
{
Error(node.OperatorKind.IsUserDefined() ? ErrorCode.WRN_NubExprIsConstBool2 : ErrorCode.WRN_NubExprIsConstBool, node, always, node.Right.Type.GetNullableUnderlyingType(), GetTypeForLiftedComparisonWarning(node.Left));
}
break;
case BinaryOperatorKind.Or:
case BinaryOperatorKind.And:
// CS0458: The result of the expression is always 'null' of type '{0}'
if ((node.Left.NullableNeverHasValue() && node.Right.IsNullableNonBoolean()) ||
(node.Left.IsNullableNonBoolean() && node.Right.NullableNeverHasValue()))
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
break;
default:
// CS0458: The result of the expression is always 'null' of type '{0}'
if (node.Right.NullableNeverHasValue() || node.Left.NullableNeverHasValue())
{
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
}
break;
}
}
private void CheckLiftedUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node)
{
// CS0458: The result of the expression is always 'null' of type '{0}'
if (node.Right.NullableNeverHasValue() || node.Left.NullableNeverHasValue())
{
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
}
}
private static TypeSymbol GetTypeForLiftedComparisonWarning(BoundExpression node)
{
// If we have something like "10 < new sbyte?()" we bind that as
// (int?)10 < (int?)(new sbyte?())
// but the warning we want to produce is that the null on the right hand
// side is of type sbyte?, not int?.
if ((object)node.Type == null || !node.Type.IsNullableType())
{
return null;
}
TypeSymbol type = null;
if (node.Kind == BoundKind.Conversion)
{
var conv = (BoundConversion)node;
if (conv.ConversionKind == ConversionKind.ExplicitNullable || conv.ConversionKind == ConversionKind.ImplicitNullable)
{
type = GetTypeForLiftedComparisonWarning(conv.Operand);
}
}
return type ?? node.Type;
}
private bool CheckForAssignmentToSelf(BoundAssignmentOperator node)
{
if (!node.HasAnyErrors && IsSameLocalOrField(node.Left, node.Right))
{
Error(ErrorCode.WRN_AssignmentToSelf, node);
return true;
}
return false;
}
private void CheckForDeconstructionAssignmentToSelf(BoundTupleExpression leftTuple, BoundExpression right)
{
while (right.Kind == BoundKind.Conversion)
{
var conversion = (BoundConversion)right;
switch (conversion.ConversionKind)
{
case ConversionKind.Deconstruction:
case ConversionKind.ImplicitTupleLiteral:
case ConversionKind.Identity:
right = conversion.Operand;
break;
default:
return;
}
}
if (right.Kind != BoundKind.ConvertedTupleLiteral && right.Kind != BoundKind.TupleLiteral)
{
return;
}
var rightTuple = (BoundTupleExpression)right;
var leftArguments = leftTuple.Arguments;
int length = leftArguments.Length;
Debug.Assert(length == rightTuple.Arguments.Length);
for (int i = 0; i < length; i++)
{
var leftArgument = leftArguments[i];
var rightArgument = rightTuple.Arguments[i];
if (leftArgument is BoundTupleExpression tupleExpression)
{
CheckForDeconstructionAssignmentToSelf(tupleExpression, rightArgument);
}
else if (IsSameLocalOrField(leftArgument, rightArgument))
{
Error(ErrorCode.WRN_AssignmentToSelf, leftArgument);
}
}
}
public override BoundNode VisitFieldAccess(BoundFieldAccess node)
{
CheckReceiverIfField(node.ReceiverOpt);
return base.VisitFieldAccess(node);
}
public override BoundNode VisitPropertyGroup(BoundPropertyGroup node)
{
CheckReceiverIfField(node.ReceiverOpt);
return base.VisitPropertyGroup(node);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This pass detects and reports diagnostics that do not affect lambda convertibility.
/// This part of the partial class focuses on expression and operator warnings.
/// </summary>
internal sealed partial class DiagnosticsPass : BoundTreeWalkerWithStackGuard
{
private void CheckArguments(ImmutableArray<RefKind> argumentRefKindsOpt, ImmutableArray<BoundExpression> arguments, Symbol method)
{
if (!argumentRefKindsOpt.IsDefault)
{
Debug.Assert(arguments.Length == argumentRefKindsOpt.Length);
for (int i = 0; i < arguments.Length; i++)
{
if (argumentRefKindsOpt[i] != RefKind.None)
{
var argument = arguments[i];
switch (argument.Kind)
{
case BoundKind.FieldAccess:
CheckFieldAddress((BoundFieldAccess)argument, method);
break;
case BoundKind.Local:
var local = (BoundLocal)argument;
if (local.Syntax.Kind() == SyntaxKind.DeclarationExpression)
{
CheckOutDeclaration(local);
}
break;
case BoundKind.DiscardExpression:
CheckDiscard((BoundDiscardExpression)argument);
break;
}
}
}
}
}
/// <remarks>
/// This is for when we are taking the address of a field.
/// Distinguish from <see cref="CheckFieldAsReceiver"/>.
/// </remarks>
private void CheckFieldAddress(BoundFieldAccess fieldAccess, Symbol consumerOpt)
{
FieldSymbol fieldSymbol = fieldAccess.FieldSymbol;
// We can safely suppress this warning when calling an Interlocked API
if (fieldSymbol.IsVolatile && ((object)consumerOpt == null || !IsInterlockedAPI(consumerOpt)))
{
Error(ErrorCode.WRN_VolatileByRef, fieldAccess, fieldSymbol);
}
if (IsNonAgileFieldAccess(fieldAccess, _compilation))
{
Error(ErrorCode.WRN_ByRefNonAgileField, fieldAccess, fieldSymbol);
}
}
/// <remarks>
/// This is for when we are dotting into a field.
/// Distinguish from <see cref="CheckFieldAddress"/>.
///
/// NOTE: dev11 also calls this on string initializers in fixed statements,
/// but never accomplishes anything since string is a reference type. This
/// is probably a bug, but fixing it would be a breaking change.
/// </remarks>
private void CheckFieldAsReceiver(BoundFieldAccess fieldAccess)
{
// From ExpressionBinder.cpp:
// Taking the address of a field is suspect if the type is marshalbyref.
// REVIEW ShonK: Is this really the best way to handle this? It'd be so much more
// bullet proof for ilgen to error when it spits out the ldflda....
FieldSymbol fieldSymbol = fieldAccess.FieldSymbol;
if (IsNonAgileFieldAccess(fieldAccess, _compilation) && !fieldSymbol.Type.IsReferenceType)
{
Error(ErrorCode.WRN_CallOnNonAgileField, fieldAccess, fieldSymbol);
}
}
private void CheckReceiverIfField(BoundExpression receiverOpt)
{
if (receiverOpt != null && receiverOpt.Kind == BoundKind.FieldAccess)
{
CheckFieldAsReceiver((BoundFieldAccess)receiverOpt);
}
}
/// <remarks>
/// Based on OutputContext::IsNonAgileField.
/// </remarks>
internal static bool IsNonAgileFieldAccess(BoundFieldAccess fieldAccess, CSharpCompilation compilation)
{
// Warn if taking the address of a non-static field with a receiver other than this (possibly cast)
// and a type that descends from System.MarshalByRefObject.
if (IsInstanceFieldAccessWithNonThisReceiver(fieldAccess))
{
// NOTE: We're only trying to produce a warning, so there's no point in producing an
// error if the well-known type we need for the check is missing.
NamedTypeSymbol marshalByRefType = compilation.GetWellKnownType(WellKnownType.System_MarshalByRefObject);
TypeSymbol baseType = fieldAccess.FieldSymbol.ContainingType;
while ((object)baseType != null)
{
if (TypeSymbol.Equals(baseType, marshalByRefType, TypeCompareKind.ConsiderEverything))
{
return true;
}
// NOTE: We're only trying to produce a warning, so there's no point in producing a
// use site diagnostic if we can't walk up the base type hierarchy.
baseType = baseType.BaseTypeNoUseSiteDiagnostics;
}
}
return false;
}
private static bool IsInstanceFieldAccessWithNonThisReceiver(BoundFieldAccess fieldAccess)
{
BoundExpression receiver = fieldAccess.ReceiverOpt;
if (receiver == null || fieldAccess.FieldSymbol.IsStatic)
{
return false;
}
while (receiver.Kind == BoundKind.Conversion)
{
BoundConversion conversion = (BoundConversion)receiver;
if (conversion.ExplicitCastInCode) break;
receiver = conversion.Operand;
}
return receiver.Kind != BoundKind.ThisReference && receiver.Kind != BoundKind.BaseReference;
}
private bool IsInterlockedAPI(Symbol method)
{
var interlocked = _compilation.GetWellKnownType(WellKnownType.System_Threading_Interlocked);
if ((object)interlocked != null && TypeSymbol.Equals(interlocked, method.ContainingType, TypeCompareKind.ConsiderEverything2))
return true;
return false;
}
private static BoundExpression StripImplicitCasts(BoundExpression expr)
{
BoundExpression current = expr;
while (true)
{
// CONSIDER: Dev11 doesn't strip conversions to float or double.
BoundConversion conversion = current as BoundConversion;
if (conversion == null || !conversion.ConversionKind.IsImplicitConversion())
{
return current;
}
current = conversion.Operand;
}
}
private static bool IsSameLocalOrField(BoundExpression expr1, BoundExpression expr2)
{
if (expr1 == null && expr2 == null)
{
return true;
}
if (expr1 == null || expr2 == null)
{
return false;
}
if (expr1.HasAnyErrors || expr2.HasAnyErrors)
{
return false;
}
expr1 = StripImplicitCasts(expr1);
expr2 = StripImplicitCasts(expr2);
if (expr1.Kind != expr2.Kind)
{
return false;
}
switch (expr1.Kind)
{
case BoundKind.Local:
var local1 = (BoundLocal)expr1;
var local2 = (BoundLocal)expr2;
return local1.LocalSymbol == local2.LocalSymbol;
case BoundKind.FieldAccess:
var field1 = (BoundFieldAccess)expr1;
var field2 = (BoundFieldAccess)expr2;
return field1.FieldSymbol == field2.FieldSymbol &&
(field1.FieldSymbol.IsStatic || IsSameLocalOrField(field1.ReceiverOpt, field2.ReceiverOpt));
case BoundKind.EventAccess:
var event1 = (BoundEventAccess)expr1;
var event2 = (BoundEventAccess)expr2;
return event1.EventSymbol == event2.EventSymbol &&
(event1.EventSymbol.IsStatic || IsSameLocalOrField(event1.ReceiverOpt, event2.ReceiverOpt));
case BoundKind.Parameter:
var param1 = (BoundParameter)expr1;
var param2 = (BoundParameter)expr2;
return param1.ParameterSymbol == param2.ParameterSymbol;
case BoundKind.RangeVariable:
var rangeVar1 = (BoundRangeVariable)expr1;
var rangeVar2 = (BoundRangeVariable)expr2;
return rangeVar1.RangeVariableSymbol == rangeVar2.RangeVariableSymbol;
case BoundKind.ThisReference:
case BoundKind.PreviousSubmissionReference:
case BoundKind.HostObjectMemberReference:
Debug.Assert(TypeSymbol.Equals(expr1.Type, expr2.Type, TypeCompareKind.ConsiderEverything2));
return true;
default:
return false;
}
}
private static bool IsComCallWithRefOmitted(MethodSymbol method, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> argumentRefKindsOpt)
{
if (method.ParameterCount != arguments.Length ||
(object)method.ContainingType == null ||
!method.ContainingType.IsComImport)
return false;
for (int i = 0; i < arguments.Length; i++)
{
if (method.Parameters[i].RefKind != RefKind.None && (argumentRefKindsOpt.IsDefault || argumentRefKindsOpt[i] == RefKind.None)) return true;
}
return false;
}
private void CheckBinaryOperator(BoundBinaryOperator node)
{
if (node.Method is MethodSymbol method)
{
if (_inExpressionLambda && method.IsAbstract && method.IsStatic)
{
Error(ErrorCode.ERR_ExpressionTreeContainsAbstractStaticMemberAccess, node);
}
}
else
{
CheckUnsafeType(node.Left);
CheckUnsafeType(node.Right);
}
CheckForBitwiseOrSignExtend(node, node.OperatorKind, node.Left, node.Right);
CheckNullableNullBinOp(node);
CheckLiftedBinOp(node);
CheckRelationals(node);
CheckDynamic(node);
}
private void CheckCompoundAssignmentOperator(BoundCompoundAssignmentOperator node)
{
BoundExpression left = node.Left;
if (!node.Operator.Kind.IsDynamic() && !node.LeftConversion.IsIdentity && node.LeftConversion.Exists)
{
// Need to represent the implicit conversion as a node in order to be able to produce correct diagnostics.
left = new BoundConversion(left.Syntax, left, node.LeftConversion, node.Operator.Kind.IsChecked(),
explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: node.Operator.LeftType);
}
CheckForBitwiseOrSignExtend(node, node.Operator.Kind, left, node.Right);
CheckLiftedCompoundAssignment(node);
if (_inExpressionLambda)
{
Error(ErrorCode.ERR_ExpressionTreeContainsAssignment, node);
}
}
private void CheckRelationals(BoundBinaryOperator node)
{
Debug.Assert(node != null);
if (!node.OperatorKind.IsComparison())
{
return;
}
// Don't bother to check vacuous comparisons where both sides are constant, eg, where someone
// is doing something like "if (0xFFFFFFFFU == 0)" -- these are likely to be machine-
// generated code.
if (node.Left.ConstantValue != null && node.Right.ConstantValue == null && node.Right.Kind == BoundKind.Conversion)
{
CheckVacuousComparisons(node, node.Left.ConstantValue, node.Right);
}
if (node.Right.ConstantValue != null && node.Left.ConstantValue == null && node.Left.Kind == BoundKind.Conversion)
{
CheckVacuousComparisons(node, node.Right.ConstantValue, node.Left);
}
if (node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual)
{
TypeSymbol t;
if (node.Left.Type.SpecialType == SpecialType.System_Object && !IsExplicitCast(node.Left) && !(node.Left.ConstantValue != null && node.Left.ConstantValue.IsNull) && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
{
// Possible unintended reference comparison; to get a value comparison, cast the left hand side to type '{0}'
_diagnostics.Add(ErrorCode.WRN_BadRefCompareLeft, node.Syntax.Location, t);
}
else if (node.Right.Type.SpecialType == SpecialType.System_Object && !IsExplicitCast(node.Right) && !(node.Right.ConstantValue != null && node.Right.ConstantValue.IsNull) && ConvertedHasEqual(node.OperatorKind, node.Left, out t))
{
// Possible unintended reference comparison; to get a value comparison, cast the right hand side to type '{0}'
_diagnostics.Add(ErrorCode.WRN_BadRefCompareRight, node.Syntax.Location, t);
}
}
CheckSelfComparisons(node);
}
private static bool IsExplicitCast(BoundExpression node)
{
return node.Kind == BoundKind.Conversion && ((BoundConversion)node).ExplicitCastInCode;
}
private static bool ConvertedHasEqual(BinaryOperatorKind oldOperatorKind, BoundNode node, out TypeSymbol type)
{
type = null;
if (node.Kind != BoundKind.Conversion) return false;
var conv = (BoundConversion)node;
if (conv.ExplicitCastInCode) return false;
NamedTypeSymbol nt = conv.Operand.Type as NamedTypeSymbol;
if ((object)nt == null || !nt.IsReferenceType || nt.IsInterface)
{
return false;
}
string opName = (oldOperatorKind == BinaryOperatorKind.ObjectEqual) ? WellKnownMemberNames.EqualityOperatorName : WellKnownMemberNames.InequalityOperatorName;
for (var t = nt; (object)t != null; t = t.BaseTypeNoUseSiteDiagnostics)
{
foreach (var sym in t.GetMembers(opName))
{
MethodSymbol op = sym as MethodSymbol;
if ((object)op == null || op.MethodKind != MethodKind.UserDefinedOperator) continue;
var parameters = op.GetParameters();
if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, t, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(parameters[1].Type, t, TypeCompareKind.ConsiderEverything2))
{
type = t;
return true;
}
}
}
return false;
}
private void CheckSelfComparisons(BoundBinaryOperator node)
{
Debug.Assert(node != null);
Debug.Assert(node.OperatorKind.IsComparison());
if (!node.HasAnyErrors && IsSameLocalOrField(node.Left, node.Right))
{
Error(ErrorCode.WRN_ComparisonToSelf, node);
}
}
private void CheckVacuousComparisons(BoundBinaryOperator tree, ConstantValue constantValue, BoundNode operand)
{
Debug.Assert(tree != null);
Debug.Assert(constantValue != null);
Debug.Assert(operand != null);
// We wish to detect comparisons between integers and constants which are likely to be wrong
// because we know at compile time whether they will be true or false. For example:
//
// const short s = 1000;
// byte b = whatever;
// if (b < s)
//
// We know that this will always be true because when b and s are both converted to int for
// the comparison, the left side will always be less than the right side.
//
// We only give the warning if there is no explicit conversion involved on the operand.
// For example, if we had:
//
// const uint s = 1000;
// sbyte b = whatever;
// if ((byte)b < s)
//
// Then we do not give a warning.
//
// Note that the native compiler has what looks to be some dead code. It checks to see
// if the conversion on the operand is from an enum type. But this is unnecessary if
// we are rejecting cases with explicit conversions. The only possible cases are:
//
// enum == enumConstant -- enum types must be the same, so it must be in range.
// enum == integralConstant -- not legal unless the constant is zero, which is in range.
// enum == (ENUM)anyConstant -- if the constant is out of range then this is not legal in the first place
// unless we're in an unchecked context, in which case, the user probably does
// not want the warning.
// integral == enumConstant -- never legal in the first place
//
// Since it seems pointless to try to check enums, we simply look for vacuous comparisons of
// integral types here.
for (BoundConversion conversion = operand as BoundConversion;
conversion != null;
conversion = conversion.Operand as BoundConversion)
{
if (conversion.ConversionKind != ConversionKind.ImplicitNumeric &&
conversion.ConversionKind != ConversionKind.ImplicitConstant)
{
return;
}
// As in dev11, we don't dig through explicit casts (see ExpressionBinder::WarnAboutBadRelationals).
if (conversion.ExplicitCastInCode)
{
return;
}
if (!conversion.Operand.Type.SpecialType.IsIntegralType() || !conversion.Type.SpecialType.IsIntegralType())
{
return;
}
if (!Binder.CheckConstantBounds(conversion.Operand.Type.SpecialType, constantValue, out _))
{
Error(ErrorCode.WRN_VacuousIntegralComp, tree, conversion.Operand.Type);
return;
}
}
}
private void CheckForBitwiseOrSignExtend(BoundExpression node, BinaryOperatorKind operatorKind, BoundExpression leftOperand, BoundExpression rightOperand)
{
// We wish to give a warning for situations where an unexpected sign extension wipes
// out some bits. For example:
//
// int x = 0x0ABC0000;
// short y = -2; // 0xFFFE
// int z = x | y;
//
// The user might naively expect the result to be 0x0ABCFFFE. But the short is sign-extended
// when it is converted to int before the bitwise or, so this is in fact the same as:
//
// int x = 0x0ABC0000;
// short y = -2; // 0xFFFE
// int ytemp = y; // 0xFFFFFFFE
// int z = x | ytemp;
//
// Which gives 0xFFFFFFFE, not 0x0ABCFFFE.
//
// However, we wish to suppress the warning if:
//
// * The sign extension is "expected" -- for instance, because there was an explicit cast
// from short to int: "int z = x | (int)y;" should not produce the warning.
// Note that "uint z = (uint)x | (uint)y;" should still produce the warning because
// the user might not realize that converting y to uint does a sign extension.
//
// * There is the same amount of sign extension on both sides. For example, when
// doing "short | sbyte", both sides are sign extended. The left creates two FF bytes
// and the right creates three, so we are potentially wiping out information from the
// left side. But "short | short" adds two FF bytes on both sides, so no information is lost.
//
// The native compiler also suppresses this warning in a bizarre and inconsistent way. If
// the side whose bits are going to be wiped out by sign extension is a *constant*, then the
// warning is suppressed *if the constant, when converted to a signed long, fits into the
// range of the type that is being sign-extended.*
//
// Consider the effects of this rule:
//
// (uint)0xFFFF0000 | y -- gives the warning because 0xFFFF0000 as a long is not in the range of a short,
// *even though the result will not be affected by the sign extension*.
// (ulong)0xFFFFFFFFFFFFFFFF | y -- suppresses the warning, because 0xFFFFFFFFFFFFFFFF as a signed long fits into a short.
// (int)0x0000ABCD | y -- suppresses the warning, even though the 0000 is going to be wiped out by the sign extension.
//
// It seems clear that the intention of the heuristic is to *suppress the warning when the bits being hammered
// on are either all zero, or all one.* Therefore that is the heuristic we will *actually* implement here.
//
switch (operatorKind)
{
case BinaryOperatorKind.LiftedUIntOr:
case BinaryOperatorKind.LiftedIntOr:
case BinaryOperatorKind.LiftedULongOr:
case BinaryOperatorKind.LiftedLongOr:
case BinaryOperatorKind.UIntOr:
case BinaryOperatorKind.IntOr:
case BinaryOperatorKind.ULongOr:
case BinaryOperatorKind.LongOr:
break;
default:
return;
}
// The native compiler skips this warning if both sides of the operator are constants.
//
// CONSIDER: Is that sensible? It seems reasonable that if we would warn on int | short
// when they are non-constants, or when one is a constant, that we would similarly warn
// when both are constants.
if (node.ConstantValue != null)
{
return;
}
// Start by determining *which bits on each side are going to be unexpectedly turned on*.
ulong left = FindSurprisingSignExtensionBits(leftOperand);
ulong right = FindSurprisingSignExtensionBits(rightOperand);
// If they are all the same then there's no warning to give.
if (left == right)
{
return;
}
// Suppress the warning if one side is a constant, and either all the unexpected
// bits are already off, or all the unexpected bits are already on.
ConstantValue constVal = GetConstantValueForBitwiseOrCheck(leftOperand);
if (constVal != null)
{
ulong val = constVal.UInt64Value;
if ((val & right) == right || (~val & right) == right)
{
return;
}
}
constVal = GetConstantValueForBitwiseOrCheck(rightOperand);
if (constVal != null)
{
ulong val = constVal.UInt64Value;
if ((val & left) == left || (~val & left) == left)
{
return;
}
}
// CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first
Error(ErrorCode.WRN_BitwiseOrSignExtend, node);
}
private static ConstantValue GetConstantValueForBitwiseOrCheck(BoundExpression operand)
{
// We might have a nullable conversion on top of an integer constant. But only dig out
// one level.
if (operand.Kind == BoundKind.Conversion)
{
BoundConversion conv = (BoundConversion)operand;
if (conv.ConversionKind == ConversionKind.ImplicitNullable)
{
operand = conv.Operand;
}
}
ConstantValue constVal = operand.ConstantValue;
if (constVal == null || !constVal.IsIntegral)
{
return null;
}
return constVal;
}
// A "surprising" sign extension is:
//
// * a conversion with no cast in source code that goes from a smaller
// signed type to a larger signed or unsigned type.
//
// * a conversion (with or without a cast) from a smaller
// signed type to a larger unsigned type.
private static ulong FindSurprisingSignExtensionBits(BoundExpression expr)
{
if (expr.Kind != BoundKind.Conversion)
{
return 0;
}
BoundConversion conv = (BoundConversion)expr;
TypeSymbol from = conv.Operand.Type;
TypeSymbol to = conv.Type;
if ((object)from == null || (object)to == null)
{
return 0;
}
if (from.IsNullableType())
{
from = from.GetNullableUnderlyingType();
}
if (to.IsNullableType())
{
to = to.GetNullableUnderlyingType();
}
SpecialType fromSpecialType = from.SpecialType;
SpecialType toSpecialType = to.SpecialType;
if (!fromSpecialType.IsIntegralType() || !toSpecialType.IsIntegralType())
{
return 0;
}
int fromSize = fromSpecialType.SizeInBytes();
int toSize = toSpecialType.SizeInBytes();
if (fromSize == 0 || toSize == 0)
{
return 0;
}
// The operand might itself be a conversion, and might be contributing
// surprising bits. We might have more, fewer or the same surprising bits
// as the operand.
ulong recursive = FindSurprisingSignExtensionBits(conv.Operand);
if (fromSize == toSize)
{
// No change.
return recursive;
}
if (toSize < fromSize)
{
// We are casting from a larger type to a smaller type, and are therefore
// losing surprising bits.
switch (toSize)
{
case 1: return unchecked((ulong)(byte)recursive);
case 2: return unchecked((ulong)(ushort)recursive);
case 4: return unchecked((ulong)(uint)recursive);
}
Debug.Assert(false, "How did we get here?");
return recursive;
}
// We are converting from a smaller type to a larger type, and therefore might
// be adding surprising bits. First of all, the smaller type has got to be signed
// for there to be sign extension.
bool fromSigned = fromSpecialType.IsSignedIntegralType();
if (!fromSigned)
{
return recursive;
}
// OK, we know that the "from" type is a signed integer that is smaller than the
// "to" type, so we are going to have sign extension. Is it surprising? The only
// time that sign extension is *not* surprising is when we have a cast operator
// to a *signed* type. That is, (int)myShort is not a surprising sign extension.
if (conv.ExplicitCastInCode && toSpecialType.IsSignedIntegralType())
{
return recursive;
}
// Note that we *could* be somewhat more clever here. Consider the following edge case:
//
// (ulong)(int)(uint)(ushort)mySbyte
//
// We could reason that the sbyte-to-ushort conversion is going to add one byte of
// unexpected sign extension. The conversion from ushort to uint adds no more bytes.
// The conversion from uint to int adds no more bytes. Does the conversion from int
// to ulong add any more bytes of unexpected sign extension? Well, no, because we
// know that the previous conversion from ushort to uint will ensure that the top bit
// of the uint is off!
//
// But we are not going to try to be that clever. In the extremely unlikely event that
// someone does this, we will record that the unexpectedly turned-on bits are
// 0xFFFFFFFF0000FF00, even though we could in theory deduce that only 0x000000000000FF00
// are the unexpected bits.
ulong result = recursive;
for (int i = fromSize; i < toSize; ++i)
{
result |= (0xFFUL) << (i * 8);
}
return result;
}
private void CheckLiftedCompoundAssignment(BoundCompoundAssignmentOperator node)
{
Debug.Assert(node != null);
if (!node.Operator.Kind.IsLifted())
{
return;
}
// CS0458: The result of the expression is always 'null' of type '{0}'
if (node.Right.NullableNeverHasValue())
{
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
}
}
private void CheckLiftedUnaryOp(BoundUnaryOperator node)
{
Debug.Assert(node != null);
if (!node.OperatorKind.IsLifted())
{
return;
}
// CS0458: The result of the expression is always 'null' of type '{0}'
if (node.Operand.NullableNeverHasValue())
{
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
}
}
private void CheckNullableNullBinOp(BoundBinaryOperator node)
{
if (node.OperatorKind.OperandTypes() != BinaryOperatorKind.NullableNull)
{
return;
}
switch (node.OperatorKind.Operator())
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
// CS0472: The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}'
//
// Produce the warning if one side is always null and the other is never null.
// That is, we have something like "if (myInt == null)"
string always = node.OperatorKind.Operator() == BinaryOperatorKind.NotEqual ? "true" : "false";
// we use a separate warning code for cases newly detected in later versions of the compiler
if (node.Right.IsLiteralNull() && node.Left.NullableAlwaysHasValue())
{
Error(ErrorCode.WRN_NubExprIsConstBool, node, always, node.Left.Type.GetNullableUnderlyingType(), node.Left.Type);
}
else if (node.Left.IsLiteralNull() && node.Right.NullableAlwaysHasValue())
{
Error(ErrorCode.WRN_NubExprIsConstBool, node, always, node.Right.Type.GetNullableUnderlyingType(), node.Right.Type);
}
break;
}
}
private void CheckLiftedBinOp(BoundBinaryOperator node)
{
Debug.Assert(node != null);
if (!node.OperatorKind.IsLifted())
{
return;
}
switch (node.OperatorKind.Operator())
{
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
// CS0464: Comparing with null of type '{0}' always produces 'false'
//
// Produce the warning if one (or both) sides are always null.
if (node.Right.NullableNeverHasValue())
{
Error(ErrorCode.WRN_CmpAlwaysFalse, node, GetTypeForLiftedComparisonWarning(node.Right));
}
else if (node.Left.NullableNeverHasValue())
{
Error(ErrorCode.WRN_CmpAlwaysFalse, node, GetTypeForLiftedComparisonWarning(node.Left));
}
break;
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
// CS0472: The result of the expression is always '{0}' since a value of type '{1}' is never equal to 'null' of type '{2}'
//
// Produce the warning if one side is always null and the other is never null.
// That is, we have something like "if (myInt == null)"
string always = node.OperatorKind.Operator() == BinaryOperatorKind.NotEqual ? "true" : "false";
if (node.Right.NullableNeverHasValue() && node.Left.NullableAlwaysHasValue())
{
Error(node.OperatorKind.IsUserDefined() ? ErrorCode.WRN_NubExprIsConstBool2 : ErrorCode.WRN_NubExprIsConstBool, node, always, node.Left.Type.GetNullableUnderlyingType(), GetTypeForLiftedComparisonWarning(node.Right));
}
else if (node.Left.NullableNeverHasValue() && node.Right.NullableAlwaysHasValue())
{
Error(node.OperatorKind.IsUserDefined() ? ErrorCode.WRN_NubExprIsConstBool2 : ErrorCode.WRN_NubExprIsConstBool, node, always, node.Right.Type.GetNullableUnderlyingType(), GetTypeForLiftedComparisonWarning(node.Left));
}
break;
case BinaryOperatorKind.Or:
case BinaryOperatorKind.And:
// CS0458: The result of the expression is always 'null' of type '{0}'
if ((node.Left.NullableNeverHasValue() && node.Right.IsNullableNonBoolean()) ||
(node.Left.IsNullableNonBoolean() && node.Right.NullableNeverHasValue()))
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
break;
default:
// CS0458: The result of the expression is always 'null' of type '{0}'
if (node.Right.NullableNeverHasValue() || node.Left.NullableNeverHasValue())
{
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
}
break;
}
}
private void CheckLiftedUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node)
{
// CS0458: The result of the expression is always 'null' of type '{0}'
if (node.Right.NullableNeverHasValue() || node.Left.NullableNeverHasValue())
{
Error(ErrorCode.WRN_AlwaysNull, node, node.Type);
}
}
private static TypeSymbol GetTypeForLiftedComparisonWarning(BoundExpression node)
{
// If we have something like "10 < new sbyte?()" we bind that as
// (int?)10 < (int?)(new sbyte?())
// but the warning we want to produce is that the null on the right hand
// side is of type sbyte?, not int?.
if ((object)node.Type == null || !node.Type.IsNullableType())
{
return null;
}
TypeSymbol type = null;
if (node.Kind == BoundKind.Conversion)
{
var conv = (BoundConversion)node;
if (conv.ConversionKind == ConversionKind.ExplicitNullable || conv.ConversionKind == ConversionKind.ImplicitNullable)
{
type = GetTypeForLiftedComparisonWarning(conv.Operand);
}
}
return type ?? node.Type;
}
private bool CheckForAssignmentToSelf(BoundAssignmentOperator node)
{
if (!node.HasAnyErrors && IsSameLocalOrField(node.Left, node.Right))
{
Error(ErrorCode.WRN_AssignmentToSelf, node);
return true;
}
return false;
}
private void CheckForDeconstructionAssignmentToSelf(BoundTupleExpression leftTuple, BoundExpression right)
{
while (right.Kind == BoundKind.Conversion)
{
var conversion = (BoundConversion)right;
switch (conversion.ConversionKind)
{
case ConversionKind.Deconstruction:
case ConversionKind.ImplicitTupleLiteral:
case ConversionKind.Identity:
right = conversion.Operand;
break;
default:
return;
}
}
if (right.Kind != BoundKind.ConvertedTupleLiteral && right.Kind != BoundKind.TupleLiteral)
{
return;
}
var rightTuple = (BoundTupleExpression)right;
var leftArguments = leftTuple.Arguments;
int length = leftArguments.Length;
Debug.Assert(length == rightTuple.Arguments.Length);
for (int i = 0; i < length; i++)
{
var leftArgument = leftArguments[i];
var rightArgument = rightTuple.Arguments[i];
if (leftArgument is BoundTupleExpression tupleExpression)
{
CheckForDeconstructionAssignmentToSelf(tupleExpression, rightArgument);
}
else if (IsSameLocalOrField(leftArgument, rightArgument))
{
Error(ErrorCode.WRN_AssignmentToSelf, leftArgument);
}
}
}
public override BoundNode VisitFieldAccess(BoundFieldAccess node)
{
CheckReceiverIfField(node.ReceiverOpt);
return base.VisitFieldAccess(node);
}
public override BoundNode VisitPropertyGroup(BoundPropertyGroup node)
{
CheckReceiverIfField(node.ReceiverOpt);
return base.VisitPropertyGroup(node);
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectManagementService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ProjectManagement;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Roslyn.Utilities;
namespace Roslyn.VisualStudio.Services.Implementation.ProjectSystem
{
[ExportWorkspaceService(typeof(IProjectManagementService), ServiceLayer.Host), Shared]
internal class VisualStudioProjectManagementService : ForegroundThreadAffinitizedObject, IProjectManagementService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioProjectManagementService(IThreadingContext threadingContext)
: base(threadingContext)
{
}
public string GetDefaultNamespace(Microsoft.CodeAnalysis.Project project, Workspace workspace)
{
this.AssertIsForeground();
if (project.Language == LanguageNames.VisualBasic)
{
return "";
}
var defaultNamespace = "";
if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
{
vsWorkspace.GetProjectData(project.Id,
out _, out var envDTEProject);
try
{
defaultNamespace = (string)envDTEProject.ProjectItems.ContainingProject.Properties.Item("DefaultNamespace").Value; // Do not Localize
}
catch (ArgumentException)
{
// DefaultNamespace does not exist for this project.
}
}
return defaultNamespace;
}
public IList<string> GetFolders(ProjectId projectId, Workspace workspace)
{
var folders = new List<string>();
if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
{
vsWorkspace.GetProjectData(projectId,
out var hierarchy, out var envDTEProject);
var projectItems = envDTEProject.ProjectItems;
var projectItemsStack = new Stack<Tuple<ProjectItem, string>>();
// Populate the stack
projectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, "\\")));
while (projectItemsStack.Count != 0)
{
var projectItemTuple = projectItemsStack.Pop();
var projectItem = projectItemTuple.Item1;
var currentFolderPath = projectItemTuple.Item2;
var folderPath = currentFolderPath + projectItem.Name + "\\";
folders.Add(folderPath);
projectItem.ProjectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, folderPath)));
}
}
return folders;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Composition;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ProjectManagement;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions;
using Roslyn.Utilities;
namespace Roslyn.VisualStudio.Services.Implementation.ProjectSystem
{
[ExportWorkspaceService(typeof(IProjectManagementService), ServiceLayer.Host), Shared]
internal class VisualStudioProjectManagementService : ForegroundThreadAffinitizedObject, IProjectManagementService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioProjectManagementService(IThreadingContext threadingContext)
: base(threadingContext)
{
}
public string GetDefaultNamespace(Microsoft.CodeAnalysis.Project project, Workspace workspace)
{
this.AssertIsForeground();
if (project.Language == LanguageNames.VisualBasic)
{
return "";
}
var defaultNamespace = "";
if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
{
vsWorkspace.GetProjectData(project.Id,
out _, out var envDTEProject);
try
{
defaultNamespace = (string)envDTEProject.ProjectItems.ContainingProject.Properties.Item("DefaultNamespace").Value; // Do not Localize
}
catch (ArgumentException)
{
// DefaultNamespace does not exist for this project.
}
}
return defaultNamespace;
}
public IList<string> GetFolders(ProjectId projectId, Workspace workspace)
{
var folders = new List<string>();
if (workspace is VisualStudioWorkspaceImpl vsWorkspace)
{
vsWorkspace.GetProjectData(projectId,
out var hierarchy, out var envDTEProject);
var projectItems = envDTEProject.ProjectItems;
var projectItemsStack = new Stack<Tuple<ProjectItem, string>>();
// Populate the stack
projectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, "\\")));
while (projectItemsStack.Count != 0)
{
var projectItemTuple = projectItemsStack.Pop();
var projectItem = projectItemTuple.Item1;
var currentFolderPath = projectItemTuple.Item2;
var folderPath = currentFolderPath + projectItem.Name + "\\";
folders.Add(folderPath);
projectItem.ProjectItems.OfType<ProjectItem>().Where(n => n.IsFolder()).Do(n => projectItemsStack.Push(Tuple.Create(n, folderPath)));
}
}
return folders;
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/Helpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator
{
internal static class CodeFixHelpers
{
/// <summary>
/// Creates an `^expr` index expression from a given `expr`.
/// </summary>
public static PrefixUnaryExpressionSyntax IndexExpression(ExpressionSyntax expr)
=> SyntaxFactory.PrefixUnaryExpression(
SyntaxKind.IndexExpression,
expr.Parenthesize());
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator
{
internal static class CodeFixHelpers
{
/// <summary>
/// Creates an `^expr` index expression from a given `expr`.
/// </summary>
public static PrefixUnaryExpressionSyntax IndexExpression(ExpressionSyntax expr)
=> SyntaxFactory.PrefixUnaryExpression(
SyntaxKind.IndexExpression,
expr.Parenthesize());
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/Remote/ServiceHub/ExternalAccess/UnitTesting/Api/UnitTestingBrokeredServiceImplementation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.ServiceHub.Framework;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal static class UnitTestingBrokeredServiceImplementation
{
public static ValueTask<T> RunServiceAsync<T>(Func<CancellationToken, ValueTask<T>> implementation, CancellationToken cancellationToken)
=> BrokeredServiceBase.RunServiceImplAsync(implementation, cancellationToken);
public static ValueTask RunServiceAsync(Func<CancellationToken, ValueTask> implementation, CancellationToken cancellationToken)
=> BrokeredServiceBase.RunServiceImplAsync(implementation, cancellationToken);
public static ValueTask<Solution> GetSolutionAsync(this UnitTestingPinnedSolutionInfoWrapper solutionInfo, ServiceBrokerClient client, CancellationToken cancellationToken)
=> RemoteWorkspaceManager.Default.GetSolutionAsync(client, solutionInfo.UnderlyingObject, cancellationToken);
public static UnitTestingIncrementalAnalyzerProvider? TryRegisterAnalyzerProvider(string analyzerName, IUnitTestingIncrementalAnalyzerProviderImplementation provider)
=> UnitTestingIncrementalAnalyzerProvider.TryRegister(RemoteWorkspaceManager.Default.GetWorkspace(), analyzerName, provider);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.ServiceHub.Framework;
namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal static class UnitTestingBrokeredServiceImplementation
{
public static ValueTask<T> RunServiceAsync<T>(Func<CancellationToken, ValueTask<T>> implementation, CancellationToken cancellationToken)
=> BrokeredServiceBase.RunServiceImplAsync(implementation, cancellationToken);
public static ValueTask RunServiceAsync(Func<CancellationToken, ValueTask> implementation, CancellationToken cancellationToken)
=> BrokeredServiceBase.RunServiceImplAsync(implementation, cancellationToken);
public static ValueTask<Solution> GetSolutionAsync(this UnitTestingPinnedSolutionInfoWrapper solutionInfo, ServiceBrokerClient client, CancellationToken cancellationToken)
=> RemoteWorkspaceManager.Default.GetSolutionAsync(client, solutionInfo.UnderlyingObject, cancellationToken);
public static UnitTestingIncrementalAnalyzerProvider? TryRegisterAnalyzerProvider(string analyzerName, IUnitTestingIncrementalAnalyzerProviderImplementation provider)
=> UnitTestingIncrementalAnalyzerProvider.TryRegister(RemoteWorkspaceManager.Default.GetWorkspace(), analyzerName, provider);
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/Core/Portable/Diagnostics/DocumentAnalysisScope.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Scope for analyzing a document for computing local syntax/semantic diagnostics.
/// </summary>
internal sealed class DocumentAnalysisScope
{
private readonly Lazy<AdditionalText> _lazyAdditionalFile;
public DocumentAnalysisScope(
TextDocument document,
TextSpan? span,
ImmutableArray<DiagnosticAnalyzer> analyzers,
AnalysisKind kind)
{
Debug.Assert(kind == AnalysisKind.Syntax || kind == AnalysisKind.Semantic);
Debug.Assert(!analyzers.IsDefaultOrEmpty);
TextDocument = document;
Span = span;
Analyzers = analyzers;
Kind = kind;
_lazyAdditionalFile = new Lazy<AdditionalText>(ComputeAdditionalFile);
}
public TextDocument TextDocument { get; }
public TextSpan? Span { get; }
public ImmutableArray<DiagnosticAnalyzer> Analyzers { get; }
public AnalysisKind Kind { get; }
/// <summary>
/// Gets the <see cref="AdditionalText"/> corresponding to the <see cref="TextDocument"/>.
/// NOTE: Throws an exception if <see cref="TextDocument"/> is not an <see cref="AdditionalDocument"/>.
/// </summary>
public AdditionalText AdditionalFile => _lazyAdditionalFile.Value;
private AdditionalText ComputeAdditionalFile()
{
Contract.ThrowIfFalse(TextDocument is AdditionalDocument);
var filePath = TextDocument.FilePath ?? TextDocument.Name;
return TextDocument.Project.AnalyzerOptions.AdditionalFiles.First(a => PathUtilities.Comparer.Equals(a.Path, filePath));
}
public DocumentAnalysisScope WithSpan(TextSpan? span)
=> new(TextDocument, span, Analyzers, Kind);
public DocumentAnalysisScope WithAnalyzers(ImmutableArray<DiagnosticAnalyzer> analyzers)
=> new(TextDocument, Span, analyzers, Kind);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
/// <summary>
/// Scope for analyzing a document for computing local syntax/semantic diagnostics.
/// </summary>
internal sealed class DocumentAnalysisScope
{
private readonly Lazy<AdditionalText> _lazyAdditionalFile;
public DocumentAnalysisScope(
TextDocument document,
TextSpan? span,
ImmutableArray<DiagnosticAnalyzer> analyzers,
AnalysisKind kind)
{
Debug.Assert(kind == AnalysisKind.Syntax || kind == AnalysisKind.Semantic);
Debug.Assert(!analyzers.IsDefaultOrEmpty);
TextDocument = document;
Span = span;
Analyzers = analyzers;
Kind = kind;
_lazyAdditionalFile = new Lazy<AdditionalText>(ComputeAdditionalFile);
}
public TextDocument TextDocument { get; }
public TextSpan? Span { get; }
public ImmutableArray<DiagnosticAnalyzer> Analyzers { get; }
public AnalysisKind Kind { get; }
/// <summary>
/// Gets the <see cref="AdditionalText"/> corresponding to the <see cref="TextDocument"/>.
/// NOTE: Throws an exception if <see cref="TextDocument"/> is not an <see cref="AdditionalDocument"/>.
/// </summary>
public AdditionalText AdditionalFile => _lazyAdditionalFile.Value;
private AdditionalText ComputeAdditionalFile()
{
Contract.ThrowIfFalse(TextDocument is AdditionalDocument);
var filePath = TextDocument.FilePath ?? TextDocument.Name;
return TextDocument.Project.AnalyzerOptions.AdditionalFiles.First(a => PathUtilities.Comparer.Equals(a.Path, filePath));
}
public DocumentAnalysisScope WithSpan(TextSpan? span)
=> new(TextDocument, span, Analyzers, Kind);
public DocumentAnalysisScope WithAnalyzers(ImmutableArray<DiagnosticAnalyzer> analyzers)
=> new(TextDocument, Span, analyzers, Kind);
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/StateMachineFieldSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Represents a synthesized state machine field.
/// </summary>
internal sealed class StateMachineFieldSymbol : SynthesizedFieldSymbolBase, ISynthesizedMethodBodyImplementationSymbol
{
private readonly TypeWithAnnotations _type;
private readonly bool _isThis;
// -1 if the field doesn't represent a long-lived local or an awaiter.
internal readonly int SlotIndex;
internal readonly LocalSlotDebugInfo SlotDebugInfo;
// Some fields need to be public since they are initialized directly by the kickoff method.
public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeWithAnnotations type, string name, bool isPublic, bool isThis)
: this(stateMachineType, type, name, new LocalSlotDebugInfo(SynthesizedLocalKind.LoweringTemp, LocalDebugId.None), slotIndex: -1, isPublic: isPublic)
{
_isThis = isThis;
}
public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeSymbol type, string name, SynthesizedLocalKind synthesizedKind, int slotIndex, bool isPublic)
: this(stateMachineType, type, name, new LocalSlotDebugInfo(synthesizedKind, LocalDebugId.None), slotIndex, isPublic: isPublic)
{
}
public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeSymbol type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex, bool isPublic) :
this(stateMachineType, TypeWithAnnotations.Create(type), name, slotDebugInfo, slotIndex, isPublic)
{
}
public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeWithAnnotations type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex, bool isPublic)
: base(stateMachineType, name, isPublic: isPublic, isReadOnly: false, isStatic: false)
{
Debug.Assert((object)type != null);
Debug.Assert(slotDebugInfo.SynthesizedKind.IsLongLived() == (slotIndex >= 0));
_type = type;
this.SlotIndex = slotIndex;
this.SlotDebugInfo = slotDebugInfo;
}
internal override bool SuppressDynamicAttribute
{
get { return true; }
}
internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
return _type;
}
bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
{
get { return true; }
}
IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method
{
get { return ((ISynthesizedMethodBodyImplementationSymbol)ContainingSymbol).Method; }
}
internal override bool IsCapturedFrame
{
get { return _isThis; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// Represents a synthesized state machine field.
/// </summary>
internal sealed class StateMachineFieldSymbol : SynthesizedFieldSymbolBase, ISynthesizedMethodBodyImplementationSymbol
{
private readonly TypeWithAnnotations _type;
private readonly bool _isThis;
// -1 if the field doesn't represent a long-lived local or an awaiter.
internal readonly int SlotIndex;
internal readonly LocalSlotDebugInfo SlotDebugInfo;
// Some fields need to be public since they are initialized directly by the kickoff method.
public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeWithAnnotations type, string name, bool isPublic, bool isThis)
: this(stateMachineType, type, name, new LocalSlotDebugInfo(SynthesizedLocalKind.LoweringTemp, LocalDebugId.None), slotIndex: -1, isPublic: isPublic)
{
_isThis = isThis;
}
public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeSymbol type, string name, SynthesizedLocalKind synthesizedKind, int slotIndex, bool isPublic)
: this(stateMachineType, type, name, new LocalSlotDebugInfo(synthesizedKind, LocalDebugId.None), slotIndex, isPublic: isPublic)
{
}
public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeSymbol type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex, bool isPublic) :
this(stateMachineType, TypeWithAnnotations.Create(type), name, slotDebugInfo, slotIndex, isPublic)
{
}
public StateMachineFieldSymbol(NamedTypeSymbol stateMachineType, TypeWithAnnotations type, string name, LocalSlotDebugInfo slotDebugInfo, int slotIndex, bool isPublic)
: base(stateMachineType, name, isPublic: isPublic, isReadOnly: false, isStatic: false)
{
Debug.Assert((object)type != null);
Debug.Assert(slotDebugInfo.SynthesizedKind.IsLongLived() == (slotIndex >= 0));
_type = type;
this.SlotIndex = slotIndex;
this.SlotDebugInfo = slotDebugInfo;
}
internal override bool SuppressDynamicAttribute
{
get { return true; }
}
internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound)
{
return _type;
}
bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency
{
get { return true; }
}
IMethodSymbolInternal ISynthesizedMethodBodyImplementationSymbol.Method
{
get { return ((ISynthesizedMethodBodyImplementationSymbol)ContainingSymbol).Method; }
}
internal override bool IsCapturedFrame
{
get { return _isThis; }
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.ExpressionCodeGenerator.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Partial Friend Class VisualBasicMethodExtractor
Partial Private Class VisualBasicCodeGenerator
Private Class ExpressionCodeGenerator
Inherits VisualBasicCodeGenerator
Public Sub New(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult)
MyBase.New(insertionPoint, selectionResult, analyzerResult)
End Sub
Public Shared Function IsExtractMethodOnExpression(code As SelectionResult) As Boolean
Return code.SelectionInExpression
End Function
Protected Overrides Function CreateMethodName() As SyntaxToken
Dim methodName = "NewMethod"
Dim containingScope = VBSelectionResult.GetContainingScope()
methodName = GetMethodNameBasedOnExpression(methodName, containingScope)
Dim semanticModel = SemanticDocument.SemanticModel
Dim nameGenerator = New UniqueNameGenerator(semanticModel)
Return SyntaxFactory.Identifier(
nameGenerator.CreateUniqueMethodName(containingScope, methodName))
End Function
Private Shared Function GetMethodNameBasedOnExpression(methodName As String, expression As SyntaxNode) As String
If expression.IsParentKind(SyntaxKind.EqualsValue) AndAlso
expression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then
Dim varDecl = DirectCast(expression.Parent.Parent, VariableDeclaratorSyntax)
If varDecl.Names.Count <> 1 Then
Return methodName
End If
Dim identifierNode = varDecl.Names(0)
If identifierNode Is Nothing Then
Return methodName
End If
Dim name = identifierNode.Identifier.ValueText
Return If(name IsNot Nothing AndAlso name.Length > 0, MakeMethodName("Get", name, camelCase:=False), methodName)
End If
If TypeOf expression Is MemberAccessExpressionSyntax Then
expression = CType(expression, MemberAccessExpressionSyntax).Name
End If
If TypeOf expression Is NameSyntax Then
Dim lastDottedName = CType(expression, NameSyntax).GetLastDottedName()
Dim plainName = CType(lastDottedName, SimpleNameSyntax).Identifier.ValueText
Return If(plainName IsNot Nothing AndAlso plainName.Length > 0, MakeMethodName("Get", plainName, camelCase:=False), methodName)
End If
Return methodName
End Function
Protected Overrides Function GetInitialStatementsForMethodDefinitions() As ImmutableArray(Of StatementSyntax)
Contract.ThrowIfFalse(IsExtractMethodOnExpression(VBSelectionResult))
Dim expression = DirectCast(VBSelectionResult.GetContainingScope(), ExpressionSyntax)
Dim statement As StatementSyntax
If Me.AnalyzerResult.HasReturnType Then
statement = SyntaxFactory.ReturnStatement(expression:=expression)
Else
' we have expression for void method (Sub). make the expression as call
' statement if possible we can create call statement only from invocation
' and member access expression. otherwise, it is not a valid expression.
' return error code
If expression.Kind <> SyntaxKind.InvocationExpression AndAlso
expression.Kind <> SyntaxKind.SimpleMemberAccessExpression Then
Return ImmutableArray(Of StatementSyntax).Empty
End If
statement = SyntaxFactory.ExpressionStatement(expression:=expression)
End If
Return ImmutableArray.Create(statement)
End Function
Protected Overrides Function GetOutermostCallSiteContainerToProcess(cancellationToken As CancellationToken) As SyntaxNode
Dim callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken)
Return If(callSiteContainer, (GetCallSiteContainerFromExpression()))
End Function
Private Function GetCallSiteContainerFromExpression() As SyntaxNode
Dim container = VBSelectionResult.InnermostStatementContainer()
Contract.ThrowIfNull(container)
Contract.ThrowIfFalse(container.IsStatementContainerNode() OrElse
TypeOf container Is TypeBlockSyntax OrElse
TypeOf container Is CompilationUnitSyntax)
Return container
End Function
Protected Overrides Function GetFirstStatementOrInitializerSelectedAtCallSite() As StatementSyntax
Return VBSelectionResult.GetContainingScopeOf(Of StatementSyntax)()
End Function
Protected Overrides Function GetLastStatementOrInitializerSelectedAtCallSite() As StatementSyntax
Return GetFirstStatementOrInitializerSelectedAtCallSite()
End Function
Protected Overrides Async Function GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken As CancellationToken) As Task(Of StatementSyntax)
Dim enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite()
Dim callSignature = CreateCallSignature().WithAdditionalAnnotations(CallSiteAnnotation)
Dim sourceNode = VBSelectionResult.GetContainingScope()
Contract.ThrowIfTrue(
sourceNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso
DirectCast(sourceNode.Parent, MemberAccessExpressionSyntax).Name Is sourceNode,
"invalid scope. scope is not an expression")
' To lower the chances that replacing sourceNode with callSignature will break the user's
' code, we make the enclosing statement semantically explicit. This ends up being a little
' bit more work because we need to annotate the sourceNode so that we can get back to it
' after rewriting the enclosing statement.
Dim sourceNodeAnnotation = New SyntaxAnnotation()
Dim enclosingStatementAnnotation = New SyntaxAnnotation()
Dim newEnclosingStatement = enclosingStatement _
.ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation)) _
.WithAdditionalAnnotations(enclosingStatementAnnotation)
Dim updatedDocument = Await Me.SemanticDocument.Document.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(False)
Dim updatedRoot = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
newEnclosingStatement = DirectCast(updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode(), StatementSyntax)
' because of the complexification we cannot guarantee that there is only one annotation.
' however complexification of names is prepended, so the last annotation should be the original one.
sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode()
Return newEnclosingStatement.ReplaceNode(sourceNode, callSignature)
End Function
End Class
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Partial Friend Class VisualBasicMethodExtractor
Partial Private Class VisualBasicCodeGenerator
Private Class ExpressionCodeGenerator
Inherits VisualBasicCodeGenerator
Public Sub New(insertionPoint As InsertionPoint, selectionResult As SelectionResult, analyzerResult As AnalyzerResult)
MyBase.New(insertionPoint, selectionResult, analyzerResult)
End Sub
Public Shared Function IsExtractMethodOnExpression(code As SelectionResult) As Boolean
Return code.SelectionInExpression
End Function
Protected Overrides Function CreateMethodName() As SyntaxToken
Dim methodName = "NewMethod"
Dim containingScope = VBSelectionResult.GetContainingScope()
methodName = GetMethodNameBasedOnExpression(methodName, containingScope)
Dim semanticModel = SemanticDocument.SemanticModel
Dim nameGenerator = New UniqueNameGenerator(semanticModel)
Return SyntaxFactory.Identifier(
nameGenerator.CreateUniqueMethodName(containingScope, methodName))
End Function
Private Shared Function GetMethodNameBasedOnExpression(methodName As String, expression As SyntaxNode) As String
If expression.IsParentKind(SyntaxKind.EqualsValue) AndAlso
expression.Parent.IsParentKind(SyntaxKind.VariableDeclarator) Then
Dim varDecl = DirectCast(expression.Parent.Parent, VariableDeclaratorSyntax)
If varDecl.Names.Count <> 1 Then
Return methodName
End If
Dim identifierNode = varDecl.Names(0)
If identifierNode Is Nothing Then
Return methodName
End If
Dim name = identifierNode.Identifier.ValueText
Return If(name IsNot Nothing AndAlso name.Length > 0, MakeMethodName("Get", name, camelCase:=False), methodName)
End If
If TypeOf expression Is MemberAccessExpressionSyntax Then
expression = CType(expression, MemberAccessExpressionSyntax).Name
End If
If TypeOf expression Is NameSyntax Then
Dim lastDottedName = CType(expression, NameSyntax).GetLastDottedName()
Dim plainName = CType(lastDottedName, SimpleNameSyntax).Identifier.ValueText
Return If(plainName IsNot Nothing AndAlso plainName.Length > 0, MakeMethodName("Get", plainName, camelCase:=False), methodName)
End If
Return methodName
End Function
Protected Overrides Function GetInitialStatementsForMethodDefinitions() As ImmutableArray(Of StatementSyntax)
Contract.ThrowIfFalse(IsExtractMethodOnExpression(VBSelectionResult))
Dim expression = DirectCast(VBSelectionResult.GetContainingScope(), ExpressionSyntax)
Dim statement As StatementSyntax
If Me.AnalyzerResult.HasReturnType Then
statement = SyntaxFactory.ReturnStatement(expression:=expression)
Else
' we have expression for void method (Sub). make the expression as call
' statement if possible we can create call statement only from invocation
' and member access expression. otherwise, it is not a valid expression.
' return error code
If expression.Kind <> SyntaxKind.InvocationExpression AndAlso
expression.Kind <> SyntaxKind.SimpleMemberAccessExpression Then
Return ImmutableArray(Of StatementSyntax).Empty
End If
statement = SyntaxFactory.ExpressionStatement(expression:=expression)
End If
Return ImmutableArray.Create(statement)
End Function
Protected Overrides Function GetOutermostCallSiteContainerToProcess(cancellationToken As CancellationToken) As SyntaxNode
Dim callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken)
Return If(callSiteContainer, (GetCallSiteContainerFromExpression()))
End Function
Private Function GetCallSiteContainerFromExpression() As SyntaxNode
Dim container = VBSelectionResult.InnermostStatementContainer()
Contract.ThrowIfNull(container)
Contract.ThrowIfFalse(container.IsStatementContainerNode() OrElse
TypeOf container Is TypeBlockSyntax OrElse
TypeOf container Is CompilationUnitSyntax)
Return container
End Function
Protected Overrides Function GetFirstStatementOrInitializerSelectedAtCallSite() As StatementSyntax
Return VBSelectionResult.GetContainingScopeOf(Of StatementSyntax)()
End Function
Protected Overrides Function GetLastStatementOrInitializerSelectedAtCallSite() As StatementSyntax
Return GetFirstStatementOrInitializerSelectedAtCallSite()
End Function
Protected Overrides Async Function GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(cancellationToken As CancellationToken) As Task(Of StatementSyntax)
Dim enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite()
Dim callSignature = CreateCallSignature().WithAdditionalAnnotations(CallSiteAnnotation)
Dim sourceNode = VBSelectionResult.GetContainingScope()
Contract.ThrowIfTrue(
sourceNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso
DirectCast(sourceNode.Parent, MemberAccessExpressionSyntax).Name Is sourceNode,
"invalid scope. scope is not an expression")
' To lower the chances that replacing sourceNode with callSignature will break the user's
' code, we make the enclosing statement semantically explicit. This ends up being a little
' bit more work because we need to annotate the sourceNode so that we can get back to it
' after rewriting the enclosing statement.
Dim sourceNodeAnnotation = New SyntaxAnnotation()
Dim enclosingStatementAnnotation = New SyntaxAnnotation()
Dim newEnclosingStatement = enclosingStatement _
.ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation)) _
.WithAdditionalAnnotations(enclosingStatementAnnotation)
Dim updatedDocument = Await Me.SemanticDocument.Document.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(False)
Dim updatedRoot = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
newEnclosingStatement = DirectCast(updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode(), StatementSyntax)
' because of the complexification we cannot guarantee that there is only one annotation.
' however complexification of names is prepended, so the last annotation should be the original one.
sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode()
Return newEnclosingStatement.ReplaceNode(sourceNode, callSignature)
End Function
End Class
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/Signatures/build.bat | ilasm SignatureCycle2.il
csi munge.csx SignatureCycle2.exe 15-12-05-01-20-06-08 15-12-05-01-20-0A-08
ilasm TypeSpecInWrongPlace.il
csi munge.csx TypeSpecInWrongPlace.exe 00-01-01-15-12-05-01-08 00-01-01-12-06-00-00-00
| ilasm SignatureCycle2.il
csi munge.csx SignatureCycle2.exe 15-12-05-01-20-06-08 15-12-05-01-20-0A-08
ilasm TypeSpecInWrongPlace.il
csi munge.csx TypeSpecInWrongPlace.exe 00-01-01-15-12-05-01-08 00-01-01-12-06-00-00-00
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/Test/Core/Compilation/OperationTreeVerifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class OperationTreeVerifier : OperationWalker
{
protected readonly Compilation _compilation;
protected readonly IOperation _root;
protected readonly StringBuilder _builder;
private readonly Dictionary<SyntaxNode, IOperation> _explicitNodeMap;
private readonly Dictionary<ILabelSymbol, uint> _labelIdMap;
private const string indent = " ";
protected string _currentIndent;
private bool _pendingIndent;
private uint _currentLabelId = 0;
public OperationTreeVerifier(Compilation compilation, IOperation root, int initialIndent)
{
_compilation = compilation;
_root = root;
_builder = new StringBuilder();
_currentIndent = new string(' ', initialIndent);
_pendingIndent = true;
_explicitNodeMap = new Dictionary<SyntaxNode, IOperation>();
_labelIdMap = new Dictionary<ILabelSymbol, uint>();
}
public static string GetOperationTree(Compilation compilation, IOperation operation, int initialIndent = 0)
{
var walker = new OperationTreeVerifier(compilation, operation, initialIndent);
walker.Visit(operation);
return walker._builder.ToString();
}
public static void Verify(string expectedOperationTree, string actualOperationTree)
{
char[] newLineChars = Environment.NewLine.ToCharArray();
string actual = actualOperationTree.Trim(newLineChars);
actual = actual.Replace(" \n", "\n").Replace(" \r", "\r");
expectedOperationTree = expectedOperationTree.Trim(newLineChars);
expectedOperationTree = expectedOperationTree.Replace("\r\n", "\n").Replace(" \n", "\n").Replace("\n", Environment.NewLine);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedOperationTree, actual);
}
#region Logging helpers
private void LogPatternPropertiesAndNewLine(IPatternOperation operation)
{
LogPatternProperties(operation);
LogString(")");
LogNewLine();
}
private void LogPatternProperties(IPatternOperation operation)
{
LogCommonProperties(operation);
LogString(" (");
LogType(operation.InputType, $"{nameof(operation.InputType)}");
LogString(", ");
LogType(operation.NarrowedType, $"{nameof(operation.NarrowedType)}");
}
private void LogCommonPropertiesAndNewLine(IOperation operation)
{
LogCommonProperties(operation);
LogNewLine();
}
private void LogCommonProperties(IOperation operation)
{
LogString(" (");
// Kind
LogString($"{nameof(OperationKind)}.{GetKindText(operation.Kind)}");
// Type
LogString(", ");
LogType(operation.Type);
// ConstantValue
if (operation.ConstantValue.HasValue)
{
LogString(", ");
LogConstant(operation.ConstantValue);
}
// IsInvalid
if (operation.HasErrors(_compilation))
{
LogString(", IsInvalid");
}
// IsImplicit
if (operation.IsImplicit)
{
LogString(", IsImplicit");
}
LogString(")");
// Syntax
Assert.NotNull(operation.Syntax);
LogString($" (Syntax: {GetSnippetFromSyntax(operation.Syntax)})");
// Some of these kinds were inconsistent in the first release, and in standardizing them the
// string output isn't guaranteed to be one or the other. So standardize manually.
string GetKindText(OperationKind kind)
{
switch (kind)
{
case OperationKind.Unary:
return "Unary";
case OperationKind.Binary:
return "Binary";
case OperationKind.TupleBinary:
return "TupleBinary";
case OperationKind.MethodBody:
return "MethodBody";
case OperationKind.ConstructorBody:
return "ConstructorBody";
default:
return kind.ToString();
}
}
}
private static string GetSnippetFromSyntax(SyntaxNode syntax)
{
if (syntax == null)
{
return "null";
}
var text = syntax.ToString().Trim(Environment.NewLine.ToCharArray());
var lines = text.Split(new[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).ToArray();
if (lines.Length <= 1 && text.Length < 25)
{
return $"'{text}'";
}
const int maxTokenLength = 11;
var firstLine = lines[0];
var lastLine = lines[lines.Length - 1];
var prefix = firstLine.Length <= maxTokenLength ? firstLine : firstLine.Substring(0, maxTokenLength);
var suffix = lastLine.Length <= maxTokenLength ? lastLine : lastLine.Substring(lastLine.Length - maxTokenLength, maxTokenLength);
return $"'{prefix} ... {suffix}'";
}
private static bool ShouldLogType(IOperation operation)
{
var operationKind = (int)operation.Kind;
// Expressions
if (operationKind >= 0x100 && operationKind < 0x400)
{
return true;
}
return false;
}
protected void LogString(string str)
{
if (_pendingIndent)
{
str = _currentIndent + str;
_pendingIndent = false;
}
_builder.Append(str);
}
protected void LogNewLine()
{
LogString(Environment.NewLine);
_pendingIndent = true;
}
private void Indent()
{
_currentIndent += indent;
}
private void Unindent()
{
_currentIndent = _currentIndent.Substring(indent.Length);
}
private void LogConstant(Optional<object> constant, string header = "Constant")
{
if (constant.HasValue)
{
LogConstant(constant.Value, header);
}
}
private static string ConstantToString(object constant)
{
switch (constant)
{
case null:
return "null";
case string s:
s = s.Replace("\"", "\"\"");
return @"""" + s + @"""";
case IFormattable formattable:
return formattable.ToString(null, CultureInfo.InvariantCulture).Replace("\"", "\"\"");
default:
return constant.ToString().Replace("\"", "\"\"");
}
}
private void LogConstant(object constant, string header = "Constant")
{
string valueStr = ConstantToString(constant);
LogString($"{header}: {valueStr}");
}
private void LogConversion(CommonConversion conversion, string header = "Conversion")
{
var exists = FormatBoolProperty(nameof(conversion.Exists), conversion.Exists);
var isIdentity = FormatBoolProperty(nameof(conversion.IsIdentity), conversion.IsIdentity);
var isNumeric = FormatBoolProperty(nameof(conversion.IsNumeric), conversion.IsNumeric);
var isReference = FormatBoolProperty(nameof(conversion.IsReference), conversion.IsReference);
var isUserDefined = FormatBoolProperty(nameof(conversion.IsUserDefined), conversion.IsUserDefined);
LogString($"{header}: {nameof(CommonConversion)} ({exists}, {isIdentity}, {isNumeric}, {isReference}, {isUserDefined}) (");
LogSymbol(conversion.MethodSymbol, nameof(conversion.MethodSymbol));
LogString(")");
}
private void LogSymbol(ISymbol symbol, string header, bool logDisplayString = true)
{
if (!string.IsNullOrEmpty(header))
{
LogString($"{header}: ");
}
var symbolStr = symbol != null ? (logDisplayString ? symbol.ToTestDisplayString() : symbol.Name) : "null";
LogString($"{symbolStr}");
}
private void LogType(ITypeSymbol type, string header = "Type")
{
var typeStr = type != null ? type.ToTestDisplayString() : "null";
LogString($"{header}: {typeStr}");
}
private uint GetLabelId(ILabelSymbol symbol)
{
if (_labelIdMap.ContainsKey(symbol))
{
return _labelIdMap[symbol];
}
var id = _currentLabelId++;
_labelIdMap[symbol] = id;
return id;
}
private static string FormatBoolProperty(string propertyName, bool value) => $"{propertyName}: {(value ? "True" : "False")}";
#endregion
#region Visit methods
public override void Visit(IOperation operation)
{
if (operation == null)
{
Indent();
LogString("null");
LogNewLine();
Unindent();
return;
}
if (!operation.IsImplicit)
{
try
{
_explicitNodeMap.Add(operation.Syntax, operation);
}
catch (ArgumentException)
{
Assert.False(true, $"Duplicate explicit node for syntax ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}");
}
}
Assert.True(operation.Type == null || !operation.MustHaveNullType(), $"Unexpected non-null type: {operation.Type}");
if (operation != _root)
{
Indent();
}
base.Visit(operation);
if (operation != _root)
{
Unindent();
}
Assert.True(operation.Syntax.Language == operation.Language);
}
private void Visit(IOperation operation, string header)
{
Debug.Assert(!string.IsNullOrEmpty(header));
Indent();
LogString($"{header}: ");
LogNewLine();
Visit(operation);
Unindent();
}
private void VisitArrayCommon<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault, Action<T> arrayElementVisitor)
{
Debug.Assert(!string.IsNullOrEmpty(header));
Indent();
if (!list.IsDefaultOrEmpty)
{
var elementCount = logElementCount ? $"({list.Count()})" : string.Empty;
LogString($"{header}{elementCount}:");
LogNewLine();
Indent();
foreach (var element in list)
{
arrayElementVisitor(element);
}
Unindent();
}
else
{
var suffix = logNullForDefault && list.IsDefault ? ": null" : "(0)";
LogString($"{header}{suffix}");
LogNewLine();
}
Unindent();
}
internal void VisitSymbolArrayElement(ISymbol element)
{
LogSymbol(element, header: "Symbol");
LogNewLine();
}
internal void VisitStringArrayElement(string element)
{
var valueStr = element != null ? element.ToString() : "null";
valueStr = @"""" + valueStr + @"""";
LogString(valueStr);
LogNewLine();
}
internal void VisitRefKindArrayElement(RefKind element)
{
LogString(element.ToString());
LogNewLine();
}
private void VisitChildren(IOperation operation)
{
Debug.Assert(operation.Children.All(o => o != null));
var children = operation.Children.ToImmutableArray();
if (!children.IsEmpty || operation.Kind != OperationKind.None)
{
VisitArray(children, "Children", logElementCount: true);
}
}
private void VisitArray<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault = false)
where T : IOperation
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, o => Visit(o));
}
private void VisitArray(ImmutableArray<ISymbol> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitSymbolArrayElement);
}
private void VisitArray(ImmutableArray<string> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitStringArrayElement);
}
private void VisitArray(ImmutableArray<RefKind> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitRefKindArrayElement);
}
private void VisitInstance(IOperation instance)
{
Visit(instance, header: "Instance Receiver");
}
internal override void VisitNoneOperation(IOperation operation)
{
LogString("IOperation: ");
LogCommonPropertiesAndNewLine(operation);
VisitChildren(operation);
}
public override void VisitBlock(IBlockOperation operation)
{
LogString(nameof(IBlockOperation));
var statementsStr = $"{operation.Operations.Length} statements";
var localStr = !operation.Locals.IsEmpty ? $", {operation.Locals.Length} locals" : string.Empty;
LogString($" ({statementsStr}{localStr})");
LogCommonPropertiesAndNewLine(operation);
if (operation.Operations.IsEmpty)
{
return;
}
LogLocals(operation.Locals);
base.VisitBlock(operation);
}
public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation)
{
var variablesCountStr = $"{operation.Declarations.Length} declarations";
LogString($"{nameof(IVariableDeclarationGroupOperation)} ({variablesCountStr})");
LogCommonPropertiesAndNewLine(operation);
base.VisitVariableDeclarationGroup(operation);
}
public override void VisitUsingDeclaration(IUsingDeclarationOperation operation)
{
LogString($"{nameof(IUsingDeclarationOperation)}");
LogString($"(IsAsynchronous: {operation.IsAsynchronous}");
var disposeMethod = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod;
if (disposeMethod is object)
{
LogSymbol(disposeMethod, ", DisposeMethod");
}
LogString(")");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.DeclarationGroup, "DeclarationGroup");
var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments;
if (!disposeArgs.IsDefaultOrEmpty)
{
VisitArray(disposeArgs, "DisposeArguments", logElementCount: true);
}
}
public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation)
{
LogString($"{nameof(IVariableDeclaratorOperation)} (");
LogSymbol(operation.Symbol, "Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
if (!operation.IgnoredArguments.IsEmpty)
{
VisitArray(operation.IgnoredArguments, "IgnoredArguments", logElementCount: true);
}
}
public override void VisitVariableDeclaration(IVariableDeclarationOperation operation)
{
var variableCount = operation.Declarators.Length;
LogString($"{nameof(IVariableDeclarationOperation)} ({variableCount} declarators)");
LogCommonPropertiesAndNewLine(operation);
if (!operation.IgnoredDimensions.IsEmpty)
{
VisitArray(operation.IgnoredDimensions, "Ignored Dimensions", true);
}
VisitArray(operation.Declarators, "Declarators", false);
Visit(operation.Initializer, "Initializer");
}
public override void VisitSwitch(ISwitchOperation operation)
{
var caseCountStr = $"{operation.Cases.Length} cases";
var exitLabelStr = $", Exit Label Id: {GetLabelId(operation.ExitLabel)}";
LogString($"{nameof(ISwitchOperation)} ({caseCountStr}{exitLabelStr})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, header: "Switch expression");
LogLocals(operation.Locals);
foreach (ISwitchCaseOperation section in operation.Cases)
{
foreach (ICaseClauseOperation c in section.Clauses)
{
if (c.Label != null)
{
GetLabelId(c.Label);
}
}
}
VisitArray(operation.Cases, "Sections", logElementCount: false);
}
public override void VisitSwitchCase(ISwitchCaseOperation operation)
{
var caseClauseCountStr = $"{operation.Clauses.Length} case clauses";
var statementCountStr = $"{operation.Body.Length} statements";
LogString($"{nameof(ISwitchCaseOperation)} ({caseClauseCountStr}, {statementCountStr})");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Indent();
VisitArray(operation.Clauses, "Clauses", logElementCount: false);
VisitArray(operation.Body, "Body", logElementCount: false);
Unindent();
_ = ((SwitchCaseOperation)operation).Condition;
}
public override void VisitWhileLoop(IWhileLoopOperation operation)
{
LogString(nameof(IWhileLoopOperation));
LogString($" (ConditionIsTop: {operation.ConditionIsTop}, ConditionIsUntil: {operation.ConditionIsUntil})");
LogLoopStatementHeader(operation);
Visit(operation.Condition, "Condition");
Visit(operation.Body, "Body");
Visit(operation.IgnoredCondition, "IgnoredCondition");
}
public override void VisitForLoop(IForLoopOperation operation)
{
LogString(nameof(IForLoopOperation));
LogLoopStatementHeader(operation);
LogLocals(operation.ConditionLocals, header: nameof(operation.ConditionLocals));
Visit(operation.Condition, "Condition");
VisitArray(operation.Before, "Before", logElementCount: false);
VisitArray(operation.AtLoopBottom, "AtLoopBottom", logElementCount: false);
Visit(operation.Body, "Body");
}
public override void VisitForToLoop(IForToLoopOperation operation)
{
LogString(nameof(IForToLoopOperation));
LogLoopStatementHeader(operation, operation.IsChecked);
Visit(operation.LoopControlVariable, "LoopControlVariable");
Visit(operation.InitialValue, "InitialValue");
Visit(operation.LimitValue, "LimitValue");
Visit(operation.StepValue, "StepValue");
Visit(operation.Body, "Body");
VisitArray(operation.NextVariables, "NextVariables", logElementCount: true);
(ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info;
if (userDefinedInfo != null)
{
_ = userDefinedInfo.Addition;
_ = userDefinedInfo.Subtraction;
_ = userDefinedInfo.LessThanOrEqual;
_ = userDefinedInfo.GreaterThanOrEqual;
}
}
private void LogLocals(IEnumerable<ILocalSymbol> locals, string header = "Locals")
{
if (!locals.Any())
{
return;
}
Indent();
LogString($"{header}: ");
Indent();
int localIndex = 1;
foreach (var local in locals)
{
LogSymbol(local, header: $"Local_{localIndex++}");
LogNewLine();
}
Unindent();
Unindent();
}
private void LogLoopStatementHeader(ILoopOperation operation, bool? isChecked = null)
{
Assert.Equal(OperationKind.Loop, operation.Kind);
var propertyStringBuilder = new StringBuilder();
propertyStringBuilder.Append(" (");
propertyStringBuilder.Append($"{nameof(LoopKind)}.{operation.LoopKind}");
if (operation is IForEachLoopOperation { IsAsynchronous: true })
{
propertyStringBuilder.Append($", IsAsynchronous");
}
propertyStringBuilder.Append($", Continue Label Id: {GetLabelId(operation.ContinueLabel)}");
propertyStringBuilder.Append($", Exit Label Id: {GetLabelId(operation.ExitLabel)}");
if (isChecked.GetValueOrDefault())
{
propertyStringBuilder.Append($", Checked");
}
propertyStringBuilder.Append(")");
LogString(propertyStringBuilder.ToString());
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
}
public override void VisitForEachLoop(IForEachLoopOperation operation)
{
LogString(nameof(IForEachLoopOperation));
LogLoopStatementHeader(operation);
Assert.NotNull(operation.LoopControlVariable);
Visit(operation.LoopControlVariable, "LoopControlVariable");
Visit(operation.Collection, "Collection");
Visit(operation.Body, "Body");
VisitArray(operation.NextVariables, "NextVariables", logElementCount: true);
ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info;
}
public override void VisitLabeled(ILabeledOperation operation)
{
LogString(nameof(ILabeledOperation));
if (!operation.Label.IsImplicitlyDeclared)
{
LogString($" (Label: {operation.Label.Name})");
}
else
{
LogString($" (Label Id: {GetLabelId(operation.Label)})");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Statement");
}
public override void VisitBranch(IBranchOperation operation)
{
LogString(nameof(IBranchOperation));
var kindStr = $"{nameof(BranchKind)}.{operation.BranchKind}";
// If the label is implicit, or if it has been assigned an id (such as VB Exit Do/While/Switch labels) then print the id, instead of the name.
var labelStr = !(operation.Target.IsImplicitlyDeclared || _labelIdMap.ContainsKey(operation.Target)) ? $", Label: {operation.Target.Name}" : $", Label Id: {GetLabelId(operation.Target)}";
LogString($" ({kindStr}{labelStr})");
LogCommonPropertiesAndNewLine(operation);
base.VisitBranch(operation);
}
public override void VisitEmpty(IEmptyOperation operation)
{
LogString(nameof(IEmptyOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitReturn(IReturnOperation operation)
{
LogString(nameof(IReturnOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ReturnedValue, "ReturnedValue");
}
public override void VisitLock(ILockOperation operation)
{
LogString(nameof(ILockOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LockedValue, "Expression");
Visit(operation.Body, "Body");
}
public override void VisitTry(ITryOperation operation)
{
LogString(nameof(ITryOperation));
if (operation.ExitLabel != null)
{
LogString($" (Exit Label Id: {GetLabelId(operation.ExitLabel)})");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Body, "Body");
VisitArray(operation.Catches, "Catch clauses", logElementCount: true);
Visit(operation.Finally, "Finally");
}
public override void VisitCatchClause(ICatchClauseOperation operation)
{
LogString(nameof(ICatchClauseOperation));
var exceptionTypeStr = operation.ExceptionType != null ? operation.ExceptionType.ToTestDisplayString() : "null";
LogString($" (Exception type: {exceptionTypeStr})");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.ExceptionDeclarationOrExpression, "ExceptionDeclarationOrExpression");
Visit(operation.Filter, "Filter");
Visit(operation.Handler, "Handler");
}
public override void VisitUsing(IUsingOperation operation)
{
LogString(nameof(IUsingOperation));
if (operation.IsAsynchronous)
{
LogString($" (IsAsynchronous)");
}
var disposeMethod = ((UsingOperation)operation).DisposeInfo.DisposeMethod;
if (disposeMethod is object)
{
LogSymbol(disposeMethod, " (DisposeMethod");
LogString(")");
}
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Resources, "Resources");
Visit(operation.Body, "Body");
Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind);
Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind);
var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments;
if (!disposeArgs.IsDefaultOrEmpty)
{
VisitArray(disposeArgs, "DisposeArguments", logElementCount: true);
}
}
// https://github.com/dotnet/roslyn/issues/21281
internal override void VisitFixed(IFixedOperation operation)
{
LogString(nameof(IFixedOperation));
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Variables, "Declaration");
Visit(operation.Body, "Body");
}
internal override void VisitAggregateQuery(IAggregateQueryOperation operation)
{
LogString(nameof(IAggregateQueryOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Group, "Group");
Visit(operation.Aggregation, "Aggregation");
}
public override void VisitExpressionStatement(IExpressionStatementOperation operation)
{
LogString(nameof(IExpressionStatementOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
internal override void VisitWithStatement(IWithStatementOperation operation)
{
LogString(nameof(IWithStatementOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
Visit(operation.Body, "Body");
}
public override void VisitStop(IStopOperation operation)
{
LogString(nameof(IStopOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitEnd(IEndOperation operation)
{
LogString(nameof(IEndOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitInvocation(IInvocationOperation operation)
{
LogString(nameof(IInvocationOperation));
var isVirtualStr = operation.IsVirtual ? "virtual " : string.Empty;
var spacing = !operation.IsVirtual && operation.Instance != null ? " " : string.Empty;
LogString($" ({isVirtualStr}{spacing}");
LogSymbol(operation.TargetMethod, header: string.Empty);
LogString(")");
LogCommonPropertiesAndNewLine(operation);
VisitInstance(operation.Instance);
VisitArguments(operation.Arguments);
}
private void VisitArguments(ImmutableArray<IArgumentOperation> arguments)
{
VisitArray(arguments, "Arguments", logElementCount: true);
}
private void VisitDynamicArguments(HasDynamicArgumentsExpression operation)
{
VisitArray(operation.Arguments, "Arguments", logElementCount: true);
VisitArray(operation.ArgumentNames, "ArgumentNames", logElementCount: true);
VisitArray(operation.ArgumentRefKinds, "ArgumentRefKinds", logElementCount: true, logNullForDefault: true);
VerifyGetArgumentNamePublicApi(operation, operation.ArgumentNames);
VerifyGetArgumentRefKindPublicApi(operation, operation.ArgumentRefKinds);
}
private static void VerifyGetArgumentNamePublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<string> argumentNames)
{
var length = operation.Arguments.Length;
if (argumentNames.IsDefaultOrEmpty)
{
for (int i = 0; i < length; i++)
{
Assert.Null(operation.GetArgumentName(i));
}
}
else
{
Assert.Equal(length, argumentNames.Length);
for (var i = 0; i < length; i++)
{
Assert.Equal(argumentNames[i], operation.GetArgumentName(i));
}
}
}
private static void VerifyGetArgumentRefKindPublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<RefKind> argumentRefKinds)
{
var length = operation.Arguments.Length;
if (argumentRefKinds.IsDefault)
{
for (int i = 0; i < length; i++)
{
Assert.Null(operation.GetArgumentRefKind(i));
}
}
else if (argumentRefKinds.IsEmpty)
{
for (int i = 0; i < length; i++)
{
Assert.Equal(RefKind.None, operation.GetArgumentRefKind(i));
}
}
else
{
Assert.Equal(length, argumentRefKinds.Length);
for (var i = 0; i < length; i++)
{
Assert.Equal(argumentRefKinds[i], operation.GetArgumentRefKind(i));
}
}
}
public override void VisitArgument(IArgumentOperation operation)
{
LogString($"{nameof(IArgumentOperation)} (");
LogString($"{nameof(ArgumentKind)}.{operation.ArgumentKind}, ");
LogSymbol(operation.Parameter, header: "Matching Parameter", logDisplayString: false);
LogString(")");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value);
Indent();
LogConversion(operation.InConversion, "InConversion");
LogNewLine();
LogConversion(operation.OutConversion, "OutConversion");
LogNewLine();
Unindent();
}
public override void VisitOmittedArgument(IOmittedArgumentOperation operation)
{
LogString(nameof(IOmittedArgumentOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitArrayElementReference(IArrayElementReferenceOperation operation)
{
LogString(nameof(IArrayElementReferenceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ArrayReference, "Array reference");
VisitArray(operation.Indices, "Indices", logElementCount: true);
}
internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation)
{
LogString(nameof(IPointerIndirectionReferenceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Pointer, "Pointer");
}
public override void VisitLocalReference(ILocalReferenceOperation operation)
{
LogString(nameof(ILocalReferenceOperation));
LogString($": {operation.Local.Name}");
if (operation.IsDeclaration)
{
LogString($" (IsDeclaration: {operation.IsDeclaration})");
}
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitFlowCapture(IFlowCaptureOperation operation)
{
LogString(nameof(IFlowCaptureOperation));
LogString($": {operation.Id.Value}");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
TestOperationVisitor.Singleton.VisitFlowCapture(operation);
}
public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation)
{
LogString(nameof(IFlowCaptureReferenceOperation));
LogString($": {operation.Id.Value}");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitIsNull(IIsNullOperation operation)
{
LogString(nameof(IIsNullOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitCaughtException(ICaughtExceptionOperation operation)
{
LogString(nameof(ICaughtExceptionOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitParameterReference(IParameterReferenceOperation operation)
{
LogString(nameof(IParameterReferenceOperation));
LogString($": {operation.Parameter.Name}");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitInstanceReference(IInstanceReferenceOperation operation)
{
LogString(nameof(IInstanceReferenceOperation));
LogString($" (ReferenceKind: {operation.ReferenceKind})");
LogCommonPropertiesAndNewLine(operation);
if (operation.IsImplicit)
{
if (operation.Parent is IMemberReferenceOperation memberReference && memberReference.Instance == operation)
{
Assert.False(memberReference.Member.IsStatic && !operation.HasErrors(this._compilation));
}
else if (operation.Parent is IInvocationOperation invocation && invocation.Instance == operation)
{
Assert.False(invocation.TargetMethod.IsStatic);
}
}
}
private void VisitMemberReferenceExpressionCommon(IMemberReferenceOperation operation)
{
if (operation.Member.IsStatic)
{
LogString(" (Static)");
}
LogCommonPropertiesAndNewLine(operation);
VisitInstance(operation.Instance);
}
public override void VisitFieldReference(IFieldReferenceOperation operation)
{
LogString(nameof(IFieldReferenceOperation));
LogString($": {operation.Field.ToTestDisplayString()}");
if (operation.IsDeclaration)
{
LogString($" (IsDeclaration: {operation.IsDeclaration})");
}
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitMethodReference(IMethodReferenceOperation operation)
{
LogString(nameof(IMethodReferenceOperation));
LogString($": {operation.Method.ToTestDisplayString()}");
if (operation.IsVirtual)
{
LogString(" (IsVirtual)");
}
Assert.Null(operation.Type);
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitPropertyReference(IPropertyReferenceOperation operation)
{
LogString(nameof(IPropertyReferenceOperation));
LogString($": {operation.Property.ToTestDisplayString()}");
VisitMemberReferenceExpressionCommon(operation);
if (operation.Arguments.Length > 0)
{
VisitArguments(operation.Arguments);
}
}
public override void VisitEventReference(IEventReferenceOperation operation)
{
LogString(nameof(IEventReferenceOperation));
LogString($": {operation.Event.ToTestDisplayString()}");
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitEventAssignment(IEventAssignmentOperation operation)
{
var kindStr = operation.Adds ? "EventAdd" : "EventRemove";
LogString($"{nameof(IEventAssignmentOperation)} ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
Assert.NotNull(operation.EventReference);
Visit(operation.EventReference, header: "Event Reference");
Visit(operation.HandlerValue, header: "Handler");
}
public override void VisitConditionalAccess(IConditionalAccessOperation operation)
{
LogString(nameof(IConditionalAccessOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, header: nameof(operation.Operation));
Visit(operation.WhenNotNull, header: nameof(operation.WhenNotNull));
Assert.NotNull(operation.Type);
}
public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation)
{
LogString(nameof(IConditionalAccessInstanceOperation));
LogCommonPropertiesAndNewLine(operation);
}
internal override void VisitPlaceholder(IPlaceholderOperation operation)
{
LogString(nameof(IPlaceholderOperation));
LogCommonPropertiesAndNewLine(operation);
Assert.Equal(PlaceholderKind.AggregationGroup, operation.PlaceholderKind);
}
public override void VisitUnaryOperator(IUnaryOperation operation)
{
LogString(nameof(IUnaryOperation));
var kindStr = $"{nameof(UnaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitBinaryOperator(IBinaryOperation operation)
{
LogString(nameof(IBinaryOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
if (operation.IsCompareText)
{
kindStr += ", CompareText";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod;
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, "Left");
Visit(operation.RightOperand, "Right");
}
public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation)
{
LogString(nameof(ITupleBinaryOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
LogString($" ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, "Left");
Visit(operation.RightOperand, "Right");
}
private void LogHasOperatorMethodExpressionCommon(IMethodSymbol operatorMethodOpt)
{
if (operatorMethodOpt != null)
{
LogSymbol(operatorMethodOpt, header: " (OperatorMethod");
LogString(")");
}
}
public override void VisitConversion(IConversionOperation operation)
{
LogString(nameof(IConversionOperation));
var isTryCast = $"TryCast: {(operation.IsTryCast ? "True" : "False")}";
var isChecked = operation.IsChecked ? "Checked" : "Unchecked";
LogString($" ({isTryCast}, {isChecked})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Indent();
LogConversion(operation.Conversion);
if (((Operation)operation).OwningSemanticModel == null)
{
LogNewLine();
Indent();
LogString($"({((ConversionOperation)operation).ConversionConvertible})");
Unindent();
}
Unindent();
LogNewLine();
Visit(operation.Operand, "Operand");
}
public override void VisitConditional(IConditionalOperation operation)
{
LogString(nameof(IConditionalOperation));
if (operation.IsRef)
{
LogString(" (IsRef)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Condition, "Condition");
Visit(operation.WhenTrue, "WhenTrue");
Visit(operation.WhenFalse, "WhenFalse");
}
public override void VisitCoalesce(ICoalesceOperation operation)
{
LogString(nameof(ICoalesceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Expression");
Indent();
LogConversion(operation.ValueConversion, "ValueConversion");
LogNewLine();
Indent();
LogString($"({((CoalesceOperation)operation).ValueConversionConvertible})");
Unindent();
LogNewLine();
Unindent();
Visit(operation.WhenNull, "WhenNull");
}
public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation)
{
LogString(nameof(ICoalesceAssignmentOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, nameof(operation.Target));
Visit(operation.Value, nameof(operation.Value));
}
public override void VisitIsType(IIsTypeOperation operation)
{
LogString(nameof(IIsTypeOperation));
if (operation.IsNegated)
{
LogString(" (IsNotExpression)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ValueOperand, "Operand");
Indent();
LogType(operation.TypeOperand, "IsType");
LogNewLine();
Unindent();
}
public override void VisitSizeOf(ISizeOfOperation operation)
{
LogString(nameof(ISizeOfOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.TypeOperand, "TypeOperand");
LogNewLine();
Unindent();
}
public override void VisitTypeOf(ITypeOfOperation operation)
{
LogString(nameof(ITypeOfOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.TypeOperand, "TypeOperand");
LogNewLine();
Unindent();
}
public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation)
{
LogString(nameof(IAnonymousFunctionOperation));
// For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart.
// That is how symbol display is implemented for C#.
// https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output.
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
base.VisitAnonymousFunction(operation);
}
public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation)
{
LogString(nameof(IFlowAnonymousFunctionOperation));
// For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart.
// That is how symbol display is implemented for C#.
// https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output.
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
base.VisitFlowAnonymousFunction(operation);
}
public override void VisitDelegateCreation(IDelegateCreationOperation operation)
{
LogString(nameof(IDelegateCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, nameof(operation.Target));
}
public override void VisitLiteral(ILiteralOperation operation)
{
LogString(nameof(ILiteralOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitAwait(IAwaitOperation operation)
{
LogString(nameof(IAwaitOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
public override void VisitNameOf(INameOfOperation operation)
{
LogString(nameof(INameOfOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Argument);
}
public override void VisitThrow(IThrowOperation operation)
{
LogString(nameof(IThrowOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Exception);
}
public override void VisitAddressOf(IAddressOfOperation operation)
{
LogString(nameof(IAddressOfOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Reference, "Reference");
}
public override void VisitObjectCreation(IObjectCreationOperation operation)
{
LogString(nameof(IObjectCreationOperation));
LogString($" (Constructor: {operation.Constructor?.ToTestDisplayString() ?? "<null>"})");
LogCommonPropertiesAndNewLine(operation);
VisitArguments(operation.Arguments);
Visit(operation.Initializer, "Initializer");
}
public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation)
{
LogString(nameof(IAnonymousObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
foreach (var initializer in operation.Initializers)
{
var simpleAssignment = (ISimpleAssignmentOperation)initializer;
var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target;
Assert.Empty(propertyReference.Arguments);
Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind);
Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind);
}
VisitArray(operation.Initializers, "Initializers", logElementCount: true);
}
public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation)
{
LogString(nameof(IDynamicObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
Visit(operation.Initializer, "Initializer");
}
public override void VisitDynamicInvocation(IDynamicInvocationOperation operation)
{
LogString(nameof(IDynamicInvocationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
}
public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation)
{
LogString(nameof(IDynamicIndexerAccessOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
}
public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation)
{
LogString(nameof(IObjectOrCollectionInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Initializers, "Initializers", logElementCount: true);
}
public override void VisitMemberInitializer(IMemberInitializerOperation operation)
{
LogString(nameof(IMemberInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.InitializedMember, "InitializedMember");
Visit(operation.Initializer, "Initializer");
}
[Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", error: true)]
public override void VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation)
{
// Kept to ensure that it's never called, as we can't override DefaultVisit in this visitor
throw ExceptionUtilities.Unreachable;
}
public override void VisitFieldInitializer(IFieldInitializerOperation operation)
{
LogString(nameof(IFieldInitializerOperation));
if (operation.InitializedFields.Length <= 1)
{
if (operation.InitializedFields.Length == 1)
{
LogSymbol(operation.InitializedFields[0], header: " (Field");
LogString(")");
}
LogCommonPropertiesAndNewLine(operation);
}
else
{
LogString($" ({operation.InitializedFields.Length} initialized fields)");
LogCommonPropertiesAndNewLine(operation);
Indent();
int index = 1;
foreach (var local in operation.InitializedFields)
{
LogSymbol(local, header: $"Field_{index++}");
LogNewLine();
}
Unindent();
}
LogLocals(operation.Locals);
base.VisitFieldInitializer(operation);
}
public override void VisitVariableInitializer(IVariableInitializerOperation operation)
{
LogString(nameof(IVariableInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
Assert.Empty(operation.Locals);
base.VisitVariableInitializer(operation);
}
public override void VisitPropertyInitializer(IPropertyInitializerOperation operation)
{
LogString(nameof(IPropertyInitializerOperation));
if (operation.InitializedProperties.Length <= 1)
{
if (operation.InitializedProperties.Length == 1)
{
LogSymbol(operation.InitializedProperties[0], header: " (Property");
LogString(")");
}
LogCommonPropertiesAndNewLine(operation);
}
else
{
LogString($" ({operation.InitializedProperties.Length} initialized properties)");
LogCommonPropertiesAndNewLine(operation);
Indent();
int index = 1;
foreach (var property in operation.InitializedProperties)
{
LogSymbol(property, header: $"Property_{index++}");
LogNewLine();
}
Unindent();
}
LogLocals(operation.Locals);
base.VisitPropertyInitializer(operation);
}
public override void VisitParameterInitializer(IParameterInitializerOperation operation)
{
LogString(nameof(IParameterInitializerOperation));
LogSymbol(operation.Parameter, header: " (Parameter");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
base.VisitParameterInitializer(operation);
}
public override void VisitArrayCreation(IArrayCreationOperation operation)
{
LogString(nameof(IArrayCreationOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.DimensionSizes, "Dimension Sizes", logElementCount: true);
Visit(operation.Initializer, "Initializer");
}
public override void VisitArrayInitializer(IArrayInitializerOperation operation)
{
LogString(nameof(IArrayInitializerOperation));
LogString($" ({operation.ElementValues.Length} elements)");
LogCommonPropertiesAndNewLine(operation);
Assert.Null(operation.Type);
VisitArray(operation.ElementValues, "Element Values", logElementCount: true);
}
public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation)
{
LogString(nameof(ISimpleAssignmentOperation));
if (operation.IsRef)
{
LogString(" (IsRef)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation)
{
LogString(nameof(IDeconstructionAssignmentOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation)
{
LogString(nameof(IDeclarationExpressionOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Expression);
}
public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation)
{
LogString(nameof(ICompoundAssignmentOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Indent();
LogConversion(operation.InConversion, "InConversion");
LogNewLine();
LogConversion(operation.OutConversion, "OutConversion");
LogNewLine();
Unindent();
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation)
{
LogString(nameof(IIncrementOrDecrementOperation));
var kindStr = operation.IsPostfix ? "Postfix" : "Prefix";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Target");
}
public override void VisitParenthesized(IParenthesizedOperation operation)
{
LogString(nameof(IParenthesizedOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation)
{
LogString(nameof(IDynamicMemberReferenceOperation));
// (Member Name: "quoted name", Containing Type: type)
LogString(" (");
LogConstant((object)operation.MemberName, "Member Name");
LogString(", ");
LogType(operation.ContainingType, "Containing Type");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
VisitArrayCommon(operation.TypeArguments, "Type Arguments", logElementCount: true, logNullForDefault: false, arrayElementVisitor: VisitSymbolArrayElement);
VisitInstance(operation.Instance);
}
public override void VisitDefaultValue(IDefaultValueOperation operation)
{
LogString(nameof(IDefaultValueOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation)
{
LogString(nameof(ITypeParameterObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
}
internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation)
{
LogString(nameof(INoPiaObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
}
public override void VisitInvalid(IInvalidOperation operation)
{
LogString(nameof(IInvalidOperation));
LogCommonPropertiesAndNewLine(operation);
VisitChildren(operation);
}
public override void VisitLocalFunction(ILocalFunctionOperation operation)
{
LogString(nameof(ILocalFunctionOperation));
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
if (operation.Body != null)
{
if (operation.IgnoredBody != null)
{
Visit(operation.Body, "Body");
Visit(operation.IgnoredBody, "IgnoredBody");
}
else
{
Visit(operation.Body);
}
}
else
{
Assert.Null(operation.IgnoredBody);
}
}
private void LogCaseClauseCommon(ICaseClauseOperation operation)
{
Assert.Equal(OperationKind.CaseClause, operation.Kind);
if (operation.Label != null)
{
LogString($" (Label Id: {GetLabelId(operation.Label)})");
}
var kindStr = $"{nameof(CaseKind)}.{operation.CaseKind}";
LogString($" ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation)
{
LogString(nameof(ISingleValueCaseClauseOperation));
LogCaseClauseCommon(operation);
Visit(operation.Value, "Value");
}
public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation)
{
LogString(nameof(IRelationalCaseClauseOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.Relation}";
LogString($" (Relational operator kind: {kindStr})");
LogCaseClauseCommon(operation);
Visit(operation.Value, "Value");
}
public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation)
{
LogString(nameof(IRangeCaseClauseOperation));
LogCaseClauseCommon(operation);
Visit(operation.MinimumValue, "Min");
Visit(operation.MaximumValue, "Max");
}
public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation)
{
LogString(nameof(IDefaultCaseClauseOperation));
LogCaseClauseCommon(operation);
}
public override void VisitTuple(ITupleOperation operation)
{
LogString(nameof(ITupleOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.NaturalType, nameof(operation.NaturalType));
LogNewLine();
Unindent();
VisitArray(operation.Elements, "Elements", logElementCount: true);
}
public override void VisitInterpolatedString(IInterpolatedStringOperation operation)
{
LogString(nameof(IInterpolatedStringOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Parts, "Parts", logElementCount: true);
}
public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation)
{
LogString(nameof(IInterpolatedStringTextOperation));
LogCommonPropertiesAndNewLine(operation);
if (operation.Text.Kind != OperationKind.Literal)
{
Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind);
}
Visit(operation.Text, "Text");
}
public override void VisitInterpolation(IInterpolationOperation operation)
{
LogString(nameof(IInterpolationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Expression, "Expression");
Visit(operation.Alignment, "Alignment");
Visit(operation.FormatString, "FormatString");
if (operation.FormatString != null && operation.FormatString.Kind != OperationKind.Literal)
{
Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind);
}
}
public override void VisitConstantPattern(IConstantPatternOperation operation)
{
LogString(nameof(IConstantPatternOperation));
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
}
public override void VisitRelationalPattern(IRelationalPatternOperation operation)
{
LogString(nameof(IRelationalPatternOperation));
LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})");
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
}
public override void VisitNegatedPattern(INegatedPatternOperation operation)
{
LogString(nameof(INegatedPatternOperation));
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Pattern, "Pattern");
}
public override void VisitBinaryPattern(IBinaryPatternOperation operation)
{
LogString(nameof(IBinaryPatternOperation));
LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})");
LogPatternPropertiesAndNewLine(operation);
Visit(operation.LeftPattern, "LeftPattern");
Visit(operation.RightPattern, "RightPattern");
}
public override void VisitTypePattern(ITypePatternOperation operation)
{
LogString(nameof(ITypePatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.MatchedType, $", {nameof(operation.MatchedType)}");
LogString(")");
LogNewLine();
}
public override void VisitDeclarationPattern(IDeclarationPatternOperation operation)
{
LogString(nameof(IDeclarationPatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}");
LogConstant((object)operation.MatchesNull, $", {nameof(operation.MatchesNull)}");
LogString(")");
LogNewLine();
}
public override void VisitRecursivePattern(IRecursivePatternOperation operation)
{
LogString(nameof(IRecursivePatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}");
LogType(operation.MatchedType, $", {nameof(operation.MatchedType)}");
LogSymbol(operation.DeconstructSymbol, $", {nameof(operation.DeconstructSymbol)}");
LogString(")");
LogNewLine();
VisitArray(operation.DeconstructionSubpatterns, $"{nameof(operation.DeconstructionSubpatterns)} ", true, true);
VisitArray(operation.PropertySubpatterns, $"{nameof(operation.PropertySubpatterns)} ", true, true);
}
public override void VisitPropertySubpattern(IPropertySubpatternOperation operation)
{
LogString(nameof(IPropertySubpatternOperation));
LogCommonProperties(operation);
LogNewLine();
Visit(operation.Member, $"{nameof(operation.Member)}");
Visit(operation.Pattern, $"{nameof(operation.Pattern)}");
}
public override void VisitIsPattern(IIsPatternOperation operation)
{
LogString(nameof(IIsPatternOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, $"{nameof(operation.Value)}");
Visit(operation.Pattern, "Pattern");
}
public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation)
{
LogString(nameof(IPatternCaseClauseOperation));
LogCaseClauseCommon(operation);
Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label);
Visit(operation.Pattern, "Pattern");
if (operation.Guard != null)
Visit(operation.Guard, nameof(operation.Guard));
}
public override void VisitTranslatedQuery(ITranslatedQueryOperation operation)
{
LogString(nameof(ITranslatedQueryOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
public override void VisitRaiseEvent(IRaiseEventOperation operation)
{
LogString(nameof(IRaiseEventOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.EventReference, header: "Event Reference");
VisitArguments(operation.Arguments);
}
public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation)
{
LogString(nameof(IConstructorBodyOperation));
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Initializer, "Initializer");
Visit(operation.BlockBody, "BlockBody");
Visit(operation.ExpressionBody, "ExpressionBody");
}
public override void VisitMethodBodyOperation(IMethodBodyOperation operation)
{
LogString(nameof(IMethodBodyOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.BlockBody, "BlockBody");
Visit(operation.ExpressionBody, "ExpressionBody");
}
public override void VisitDiscardOperation(IDiscardOperation operation)
{
LogString(nameof(IDiscardOperation));
LogString(" (");
LogSymbol(operation.DiscardSymbol, "Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitDiscardPattern(IDiscardPatternOperation operation)
{
LogString(nameof(IDiscardPatternOperation));
LogPatternPropertiesAndNewLine(operation);
}
public override void VisitSwitchExpression(ISwitchExpressionOperation operation)
{
LogString($"{nameof(ISwitchExpressionOperation)} ({operation.Arms.Length} arms, IsExhaustive: {operation.IsExhaustive})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, nameof(operation.Value));
VisitArray(operation.Arms, nameof(operation.Arms), logElementCount: true);
}
public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation)
{
LogString($"{nameof(ISwitchExpressionArmOperation)} ({operation.Locals.Length} locals)");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Pattern, nameof(operation.Pattern));
if (operation.Guard != null)
Visit(operation.Guard, nameof(operation.Guard));
Visit(operation.Value, nameof(operation.Value));
LogLocals(operation.Locals);
}
public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation)
{
LogString(nameof(IStaticLocalInitializationSemaphoreOperation));
LogSymbol(operation.Local, " (Local Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitRangeOperation(IRangeOperation operation)
{
LogString(nameof(IRangeOperation));
if (operation.IsLifted)
{
LogString(" (IsLifted)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, nameof(operation.LeftOperand));
Visit(operation.RightOperand, nameof(operation.RightOperand));
}
public override void VisitReDim(IReDimOperation operation)
{
LogString(nameof(IReDimOperation));
if (operation.Preserve)
{
LogString(" (Preserve)");
}
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Clauses, "Clauses", logElementCount: true);
}
public override void VisitReDimClause(IReDimClauseOperation operation)
{
LogString(nameof(IReDimClauseOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
VisitArray(operation.DimensionSizes, "DimensionSizes", logElementCount: true);
}
public override void VisitWith(IWithOperation operation)
{
LogString(nameof(IWithOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
Indent();
LogSymbol(operation.CloneMethod, nameof(operation.CloneMethod));
LogNewLine();
Unindent();
Visit(operation.Initializer, "Initializer");
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class OperationTreeVerifier : OperationWalker
{
protected readonly Compilation _compilation;
protected readonly IOperation _root;
protected readonly StringBuilder _builder;
private readonly Dictionary<SyntaxNode, IOperation> _explicitNodeMap;
private readonly Dictionary<ILabelSymbol, uint> _labelIdMap;
private const string indent = " ";
protected string _currentIndent;
private bool _pendingIndent;
private uint _currentLabelId = 0;
public OperationTreeVerifier(Compilation compilation, IOperation root, int initialIndent)
{
_compilation = compilation;
_root = root;
_builder = new StringBuilder();
_currentIndent = new string(' ', initialIndent);
_pendingIndent = true;
_explicitNodeMap = new Dictionary<SyntaxNode, IOperation>();
_labelIdMap = new Dictionary<ILabelSymbol, uint>();
}
public static string GetOperationTree(Compilation compilation, IOperation operation, int initialIndent = 0)
{
var walker = new OperationTreeVerifier(compilation, operation, initialIndent);
walker.Visit(operation);
return walker._builder.ToString();
}
public static void Verify(string expectedOperationTree, string actualOperationTree)
{
char[] newLineChars = Environment.NewLine.ToCharArray();
string actual = actualOperationTree.Trim(newLineChars);
actual = actual.Replace(" \n", "\n").Replace(" \r", "\r");
expectedOperationTree = expectedOperationTree.Trim(newLineChars);
expectedOperationTree = expectedOperationTree.Replace("\r\n", "\n").Replace(" \n", "\n").Replace("\n", Environment.NewLine);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedOperationTree, actual);
}
#region Logging helpers
private void LogPatternPropertiesAndNewLine(IPatternOperation operation)
{
LogPatternProperties(operation);
LogString(")");
LogNewLine();
}
private void LogPatternProperties(IPatternOperation operation)
{
LogCommonProperties(operation);
LogString(" (");
LogType(operation.InputType, $"{nameof(operation.InputType)}");
LogString(", ");
LogType(operation.NarrowedType, $"{nameof(operation.NarrowedType)}");
}
private void LogCommonPropertiesAndNewLine(IOperation operation)
{
LogCommonProperties(operation);
LogNewLine();
}
private void LogCommonProperties(IOperation operation)
{
LogString(" (");
// Kind
LogString($"{nameof(OperationKind)}.{GetKindText(operation.Kind)}");
// Type
LogString(", ");
LogType(operation.Type);
// ConstantValue
if (operation.ConstantValue.HasValue)
{
LogString(", ");
LogConstant(operation.ConstantValue);
}
// IsInvalid
if (operation.HasErrors(_compilation))
{
LogString(", IsInvalid");
}
// IsImplicit
if (operation.IsImplicit)
{
LogString(", IsImplicit");
}
LogString(")");
// Syntax
Assert.NotNull(operation.Syntax);
LogString($" (Syntax: {GetSnippetFromSyntax(operation.Syntax)})");
// Some of these kinds were inconsistent in the first release, and in standardizing them the
// string output isn't guaranteed to be one or the other. So standardize manually.
string GetKindText(OperationKind kind)
{
switch (kind)
{
case OperationKind.Unary:
return "Unary";
case OperationKind.Binary:
return "Binary";
case OperationKind.TupleBinary:
return "TupleBinary";
case OperationKind.MethodBody:
return "MethodBody";
case OperationKind.ConstructorBody:
return "ConstructorBody";
default:
return kind.ToString();
}
}
}
private static string GetSnippetFromSyntax(SyntaxNode syntax)
{
if (syntax == null)
{
return "null";
}
var text = syntax.ToString().Trim(Environment.NewLine.ToCharArray());
var lines = text.Split(new[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).ToArray();
if (lines.Length <= 1 && text.Length < 25)
{
return $"'{text}'";
}
const int maxTokenLength = 11;
var firstLine = lines[0];
var lastLine = lines[lines.Length - 1];
var prefix = firstLine.Length <= maxTokenLength ? firstLine : firstLine.Substring(0, maxTokenLength);
var suffix = lastLine.Length <= maxTokenLength ? lastLine : lastLine.Substring(lastLine.Length - maxTokenLength, maxTokenLength);
return $"'{prefix} ... {suffix}'";
}
private static bool ShouldLogType(IOperation operation)
{
var operationKind = (int)operation.Kind;
// Expressions
if (operationKind >= 0x100 && operationKind < 0x400)
{
return true;
}
return false;
}
protected void LogString(string str)
{
if (_pendingIndent)
{
str = _currentIndent + str;
_pendingIndent = false;
}
_builder.Append(str);
}
protected void LogNewLine()
{
LogString(Environment.NewLine);
_pendingIndent = true;
}
private void Indent()
{
_currentIndent += indent;
}
private void Unindent()
{
_currentIndent = _currentIndent.Substring(indent.Length);
}
private void LogConstant(Optional<object> constant, string header = "Constant")
{
if (constant.HasValue)
{
LogConstant(constant.Value, header);
}
}
private static string ConstantToString(object constant)
{
switch (constant)
{
case null:
return "null";
case string s:
s = s.Replace("\"", "\"\"");
return @"""" + s + @"""";
case IFormattable formattable:
return formattable.ToString(null, CultureInfo.InvariantCulture).Replace("\"", "\"\"");
default:
return constant.ToString().Replace("\"", "\"\"");
}
}
private void LogConstant(object constant, string header = "Constant")
{
string valueStr = ConstantToString(constant);
LogString($"{header}: {valueStr}");
}
private void LogConversion(CommonConversion conversion, string header = "Conversion")
{
var exists = FormatBoolProperty(nameof(conversion.Exists), conversion.Exists);
var isIdentity = FormatBoolProperty(nameof(conversion.IsIdentity), conversion.IsIdentity);
var isNumeric = FormatBoolProperty(nameof(conversion.IsNumeric), conversion.IsNumeric);
var isReference = FormatBoolProperty(nameof(conversion.IsReference), conversion.IsReference);
var isUserDefined = FormatBoolProperty(nameof(conversion.IsUserDefined), conversion.IsUserDefined);
LogString($"{header}: {nameof(CommonConversion)} ({exists}, {isIdentity}, {isNumeric}, {isReference}, {isUserDefined}) (");
LogSymbol(conversion.MethodSymbol, nameof(conversion.MethodSymbol));
LogString(")");
}
private void LogSymbol(ISymbol symbol, string header, bool logDisplayString = true)
{
if (!string.IsNullOrEmpty(header))
{
LogString($"{header}: ");
}
var symbolStr = symbol != null ? (logDisplayString ? symbol.ToTestDisplayString() : symbol.Name) : "null";
LogString($"{symbolStr}");
}
private void LogType(ITypeSymbol type, string header = "Type")
{
var typeStr = type != null ? type.ToTestDisplayString() : "null";
LogString($"{header}: {typeStr}");
}
private uint GetLabelId(ILabelSymbol symbol)
{
if (_labelIdMap.ContainsKey(symbol))
{
return _labelIdMap[symbol];
}
var id = _currentLabelId++;
_labelIdMap[symbol] = id;
return id;
}
private static string FormatBoolProperty(string propertyName, bool value) => $"{propertyName}: {(value ? "True" : "False")}";
#endregion
#region Visit methods
public override void Visit(IOperation operation)
{
if (operation == null)
{
Indent();
LogString("null");
LogNewLine();
Unindent();
return;
}
if (!operation.IsImplicit)
{
try
{
_explicitNodeMap.Add(operation.Syntax, operation);
}
catch (ArgumentException)
{
Assert.False(true, $"Duplicate explicit node for syntax ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}");
}
}
Assert.True(operation.Type == null || !operation.MustHaveNullType(), $"Unexpected non-null type: {operation.Type}");
if (operation != _root)
{
Indent();
}
base.Visit(operation);
if (operation != _root)
{
Unindent();
}
Assert.True(operation.Syntax.Language == operation.Language);
}
private void Visit(IOperation operation, string header)
{
Debug.Assert(!string.IsNullOrEmpty(header));
Indent();
LogString($"{header}: ");
LogNewLine();
Visit(operation);
Unindent();
}
private void VisitArrayCommon<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault, Action<T> arrayElementVisitor)
{
Debug.Assert(!string.IsNullOrEmpty(header));
Indent();
if (!list.IsDefaultOrEmpty)
{
var elementCount = logElementCount ? $"({list.Count()})" : string.Empty;
LogString($"{header}{elementCount}:");
LogNewLine();
Indent();
foreach (var element in list)
{
arrayElementVisitor(element);
}
Unindent();
}
else
{
var suffix = logNullForDefault && list.IsDefault ? ": null" : "(0)";
LogString($"{header}{suffix}");
LogNewLine();
}
Unindent();
}
internal void VisitSymbolArrayElement(ISymbol element)
{
LogSymbol(element, header: "Symbol");
LogNewLine();
}
internal void VisitStringArrayElement(string element)
{
var valueStr = element != null ? element.ToString() : "null";
valueStr = @"""" + valueStr + @"""";
LogString(valueStr);
LogNewLine();
}
internal void VisitRefKindArrayElement(RefKind element)
{
LogString(element.ToString());
LogNewLine();
}
private void VisitChildren(IOperation operation)
{
Debug.Assert(operation.Children.All(o => o != null));
var children = operation.Children.ToImmutableArray();
if (!children.IsEmpty || operation.Kind != OperationKind.None)
{
VisitArray(children, "Children", logElementCount: true);
}
}
private void VisitArray<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault = false)
where T : IOperation
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, o => Visit(o));
}
private void VisitArray(ImmutableArray<ISymbol> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitSymbolArrayElement);
}
private void VisitArray(ImmutableArray<string> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitStringArrayElement);
}
private void VisitArray(ImmutableArray<RefKind> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitRefKindArrayElement);
}
private void VisitInstance(IOperation instance)
{
Visit(instance, header: "Instance Receiver");
}
internal override void VisitNoneOperation(IOperation operation)
{
LogString("IOperation: ");
LogCommonPropertiesAndNewLine(operation);
VisitChildren(operation);
}
public override void VisitBlock(IBlockOperation operation)
{
LogString(nameof(IBlockOperation));
var statementsStr = $"{operation.Operations.Length} statements";
var localStr = !operation.Locals.IsEmpty ? $", {operation.Locals.Length} locals" : string.Empty;
LogString($" ({statementsStr}{localStr})");
LogCommonPropertiesAndNewLine(operation);
if (operation.Operations.IsEmpty)
{
return;
}
LogLocals(operation.Locals);
base.VisitBlock(operation);
}
public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation)
{
var variablesCountStr = $"{operation.Declarations.Length} declarations";
LogString($"{nameof(IVariableDeclarationGroupOperation)} ({variablesCountStr})");
LogCommonPropertiesAndNewLine(operation);
base.VisitVariableDeclarationGroup(operation);
}
public override void VisitUsingDeclaration(IUsingDeclarationOperation operation)
{
LogString($"{nameof(IUsingDeclarationOperation)}");
LogString($"(IsAsynchronous: {operation.IsAsynchronous}");
var disposeMethod = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeMethod;
if (disposeMethod is object)
{
LogSymbol(disposeMethod, ", DisposeMethod");
}
LogString(")");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.DeclarationGroup, "DeclarationGroup");
var disposeArgs = ((UsingDeclarationOperation)operation).DisposeInfo.DisposeArguments;
if (!disposeArgs.IsDefaultOrEmpty)
{
VisitArray(disposeArgs, "DisposeArguments", logElementCount: true);
}
}
public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation)
{
LogString($"{nameof(IVariableDeclaratorOperation)} (");
LogSymbol(operation.Symbol, "Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
if (!operation.IgnoredArguments.IsEmpty)
{
VisitArray(operation.IgnoredArguments, "IgnoredArguments", logElementCount: true);
}
}
public override void VisitVariableDeclaration(IVariableDeclarationOperation operation)
{
var variableCount = operation.Declarators.Length;
LogString($"{nameof(IVariableDeclarationOperation)} ({variableCount} declarators)");
LogCommonPropertiesAndNewLine(operation);
if (!operation.IgnoredDimensions.IsEmpty)
{
VisitArray(operation.IgnoredDimensions, "Ignored Dimensions", true);
}
VisitArray(operation.Declarators, "Declarators", false);
Visit(operation.Initializer, "Initializer");
}
public override void VisitSwitch(ISwitchOperation operation)
{
var caseCountStr = $"{operation.Cases.Length} cases";
var exitLabelStr = $", Exit Label Id: {GetLabelId(operation.ExitLabel)}";
LogString($"{nameof(ISwitchOperation)} ({caseCountStr}{exitLabelStr})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, header: "Switch expression");
LogLocals(operation.Locals);
foreach (ISwitchCaseOperation section in operation.Cases)
{
foreach (ICaseClauseOperation c in section.Clauses)
{
if (c.Label != null)
{
GetLabelId(c.Label);
}
}
}
VisitArray(operation.Cases, "Sections", logElementCount: false);
}
public override void VisitSwitchCase(ISwitchCaseOperation operation)
{
var caseClauseCountStr = $"{operation.Clauses.Length} case clauses";
var statementCountStr = $"{operation.Body.Length} statements";
LogString($"{nameof(ISwitchCaseOperation)} ({caseClauseCountStr}, {statementCountStr})");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Indent();
VisitArray(operation.Clauses, "Clauses", logElementCount: false);
VisitArray(operation.Body, "Body", logElementCount: false);
Unindent();
_ = ((SwitchCaseOperation)operation).Condition;
}
public override void VisitWhileLoop(IWhileLoopOperation operation)
{
LogString(nameof(IWhileLoopOperation));
LogString($" (ConditionIsTop: {operation.ConditionIsTop}, ConditionIsUntil: {operation.ConditionIsUntil})");
LogLoopStatementHeader(operation);
Visit(operation.Condition, "Condition");
Visit(operation.Body, "Body");
Visit(operation.IgnoredCondition, "IgnoredCondition");
}
public override void VisitForLoop(IForLoopOperation operation)
{
LogString(nameof(IForLoopOperation));
LogLoopStatementHeader(operation);
LogLocals(operation.ConditionLocals, header: nameof(operation.ConditionLocals));
Visit(operation.Condition, "Condition");
VisitArray(operation.Before, "Before", logElementCount: false);
VisitArray(operation.AtLoopBottom, "AtLoopBottom", logElementCount: false);
Visit(operation.Body, "Body");
}
public override void VisitForToLoop(IForToLoopOperation operation)
{
LogString(nameof(IForToLoopOperation));
LogLoopStatementHeader(operation, operation.IsChecked);
Visit(operation.LoopControlVariable, "LoopControlVariable");
Visit(operation.InitialValue, "InitialValue");
Visit(operation.LimitValue, "LimitValue");
Visit(operation.StepValue, "StepValue");
Visit(operation.Body, "Body");
VisitArray(operation.NextVariables, "NextVariables", logElementCount: true);
(ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((ForToLoopOperation)operation).Info;
if (userDefinedInfo != null)
{
_ = userDefinedInfo.Addition;
_ = userDefinedInfo.Subtraction;
_ = userDefinedInfo.LessThanOrEqual;
_ = userDefinedInfo.GreaterThanOrEqual;
}
}
private void LogLocals(IEnumerable<ILocalSymbol> locals, string header = "Locals")
{
if (!locals.Any())
{
return;
}
Indent();
LogString($"{header}: ");
Indent();
int localIndex = 1;
foreach (var local in locals)
{
LogSymbol(local, header: $"Local_{localIndex++}");
LogNewLine();
}
Unindent();
Unindent();
}
private void LogLoopStatementHeader(ILoopOperation operation, bool? isChecked = null)
{
Assert.Equal(OperationKind.Loop, operation.Kind);
var propertyStringBuilder = new StringBuilder();
propertyStringBuilder.Append(" (");
propertyStringBuilder.Append($"{nameof(LoopKind)}.{operation.LoopKind}");
if (operation is IForEachLoopOperation { IsAsynchronous: true })
{
propertyStringBuilder.Append($", IsAsynchronous");
}
propertyStringBuilder.Append($", Continue Label Id: {GetLabelId(operation.ContinueLabel)}");
propertyStringBuilder.Append($", Exit Label Id: {GetLabelId(operation.ExitLabel)}");
if (isChecked.GetValueOrDefault())
{
propertyStringBuilder.Append($", Checked");
}
propertyStringBuilder.Append(")");
LogString(propertyStringBuilder.ToString());
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
}
public override void VisitForEachLoop(IForEachLoopOperation operation)
{
LogString(nameof(IForEachLoopOperation));
LogLoopStatementHeader(operation);
Assert.NotNull(operation.LoopControlVariable);
Visit(operation.LoopControlVariable, "LoopControlVariable");
Visit(operation.Collection, "Collection");
Visit(operation.Body, "Body");
VisitArray(operation.NextVariables, "NextVariables", logElementCount: true);
ForEachLoopOperationInfo info = ((ForEachLoopOperation)operation).Info;
}
public override void VisitLabeled(ILabeledOperation operation)
{
LogString(nameof(ILabeledOperation));
if (!operation.Label.IsImplicitlyDeclared)
{
LogString($" (Label: {operation.Label.Name})");
}
else
{
LogString($" (Label Id: {GetLabelId(operation.Label)})");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Statement");
}
public override void VisitBranch(IBranchOperation operation)
{
LogString(nameof(IBranchOperation));
var kindStr = $"{nameof(BranchKind)}.{operation.BranchKind}";
// If the label is implicit, or if it has been assigned an id (such as VB Exit Do/While/Switch labels) then print the id, instead of the name.
var labelStr = !(operation.Target.IsImplicitlyDeclared || _labelIdMap.ContainsKey(operation.Target)) ? $", Label: {operation.Target.Name}" : $", Label Id: {GetLabelId(operation.Target)}";
LogString($" ({kindStr}{labelStr})");
LogCommonPropertiesAndNewLine(operation);
base.VisitBranch(operation);
}
public override void VisitEmpty(IEmptyOperation operation)
{
LogString(nameof(IEmptyOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitReturn(IReturnOperation operation)
{
LogString(nameof(IReturnOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ReturnedValue, "ReturnedValue");
}
public override void VisitLock(ILockOperation operation)
{
LogString(nameof(ILockOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LockedValue, "Expression");
Visit(operation.Body, "Body");
}
public override void VisitTry(ITryOperation operation)
{
LogString(nameof(ITryOperation));
if (operation.ExitLabel != null)
{
LogString($" (Exit Label Id: {GetLabelId(operation.ExitLabel)})");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Body, "Body");
VisitArray(operation.Catches, "Catch clauses", logElementCount: true);
Visit(operation.Finally, "Finally");
}
public override void VisitCatchClause(ICatchClauseOperation operation)
{
LogString(nameof(ICatchClauseOperation));
var exceptionTypeStr = operation.ExceptionType != null ? operation.ExceptionType.ToTestDisplayString() : "null";
LogString($" (Exception type: {exceptionTypeStr})");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.ExceptionDeclarationOrExpression, "ExceptionDeclarationOrExpression");
Visit(operation.Filter, "Filter");
Visit(operation.Handler, "Handler");
}
public override void VisitUsing(IUsingOperation operation)
{
LogString(nameof(IUsingOperation));
if (operation.IsAsynchronous)
{
LogString($" (IsAsynchronous)");
}
var disposeMethod = ((UsingOperation)operation).DisposeInfo.DisposeMethod;
if (disposeMethod is object)
{
LogSymbol(disposeMethod, " (DisposeMethod");
LogString(")");
}
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Resources, "Resources");
Visit(operation.Body, "Body");
Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind);
Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind);
var disposeArgs = ((UsingOperation)operation).DisposeInfo.DisposeArguments;
if (!disposeArgs.IsDefaultOrEmpty)
{
VisitArray(disposeArgs, "DisposeArguments", logElementCount: true);
}
}
// https://github.com/dotnet/roslyn/issues/21281
internal override void VisitFixed(IFixedOperation operation)
{
LogString(nameof(IFixedOperation));
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Variables, "Declaration");
Visit(operation.Body, "Body");
}
internal override void VisitAggregateQuery(IAggregateQueryOperation operation)
{
LogString(nameof(IAggregateQueryOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Group, "Group");
Visit(operation.Aggregation, "Aggregation");
}
public override void VisitExpressionStatement(IExpressionStatementOperation operation)
{
LogString(nameof(IExpressionStatementOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
internal override void VisitWithStatement(IWithStatementOperation operation)
{
LogString(nameof(IWithStatementOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
Visit(operation.Body, "Body");
}
public override void VisitStop(IStopOperation operation)
{
LogString(nameof(IStopOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitEnd(IEndOperation operation)
{
LogString(nameof(IEndOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitInvocation(IInvocationOperation operation)
{
LogString(nameof(IInvocationOperation));
var isVirtualStr = operation.IsVirtual ? "virtual " : string.Empty;
var spacing = !operation.IsVirtual && operation.Instance != null ? " " : string.Empty;
LogString($" ({isVirtualStr}{spacing}");
LogSymbol(operation.TargetMethod, header: string.Empty);
LogString(")");
LogCommonPropertiesAndNewLine(operation);
VisitInstance(operation.Instance);
VisitArguments(operation.Arguments);
}
private void VisitArguments(ImmutableArray<IArgumentOperation> arguments)
{
VisitArray(arguments, "Arguments", logElementCount: true);
}
private void VisitDynamicArguments(HasDynamicArgumentsExpression operation)
{
VisitArray(operation.Arguments, "Arguments", logElementCount: true);
VisitArray(operation.ArgumentNames, "ArgumentNames", logElementCount: true);
VisitArray(operation.ArgumentRefKinds, "ArgumentRefKinds", logElementCount: true, logNullForDefault: true);
VerifyGetArgumentNamePublicApi(operation, operation.ArgumentNames);
VerifyGetArgumentRefKindPublicApi(operation, operation.ArgumentRefKinds);
}
private static void VerifyGetArgumentNamePublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<string> argumentNames)
{
var length = operation.Arguments.Length;
if (argumentNames.IsDefaultOrEmpty)
{
for (int i = 0; i < length; i++)
{
Assert.Null(operation.GetArgumentName(i));
}
}
else
{
Assert.Equal(length, argumentNames.Length);
for (var i = 0; i < length; i++)
{
Assert.Equal(argumentNames[i], operation.GetArgumentName(i));
}
}
}
private static void VerifyGetArgumentRefKindPublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<RefKind> argumentRefKinds)
{
var length = operation.Arguments.Length;
if (argumentRefKinds.IsDefault)
{
for (int i = 0; i < length; i++)
{
Assert.Null(operation.GetArgumentRefKind(i));
}
}
else if (argumentRefKinds.IsEmpty)
{
for (int i = 0; i < length; i++)
{
Assert.Equal(RefKind.None, operation.GetArgumentRefKind(i));
}
}
else
{
Assert.Equal(length, argumentRefKinds.Length);
for (var i = 0; i < length; i++)
{
Assert.Equal(argumentRefKinds[i], operation.GetArgumentRefKind(i));
}
}
}
public override void VisitArgument(IArgumentOperation operation)
{
LogString($"{nameof(IArgumentOperation)} (");
LogString($"{nameof(ArgumentKind)}.{operation.ArgumentKind}, ");
LogSymbol(operation.Parameter, header: "Matching Parameter", logDisplayString: false);
LogString(")");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value);
Indent();
LogConversion(operation.InConversion, "InConversion");
LogNewLine();
LogConversion(operation.OutConversion, "OutConversion");
LogNewLine();
Unindent();
}
public override void VisitOmittedArgument(IOmittedArgumentOperation operation)
{
LogString(nameof(IOmittedArgumentOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitArrayElementReference(IArrayElementReferenceOperation operation)
{
LogString(nameof(IArrayElementReferenceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ArrayReference, "Array reference");
VisitArray(operation.Indices, "Indices", logElementCount: true);
}
internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation)
{
LogString(nameof(IPointerIndirectionReferenceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Pointer, "Pointer");
}
public override void VisitLocalReference(ILocalReferenceOperation operation)
{
LogString(nameof(ILocalReferenceOperation));
LogString($": {operation.Local.Name}");
if (operation.IsDeclaration)
{
LogString($" (IsDeclaration: {operation.IsDeclaration})");
}
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitFlowCapture(IFlowCaptureOperation operation)
{
LogString(nameof(IFlowCaptureOperation));
LogString($": {operation.Id.Value}");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
TestOperationVisitor.Singleton.VisitFlowCapture(operation);
}
public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation)
{
LogString(nameof(IFlowCaptureReferenceOperation));
LogString($": {operation.Id.Value}");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitIsNull(IIsNullOperation operation)
{
LogString(nameof(IIsNullOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitCaughtException(ICaughtExceptionOperation operation)
{
LogString(nameof(ICaughtExceptionOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitParameterReference(IParameterReferenceOperation operation)
{
LogString(nameof(IParameterReferenceOperation));
LogString($": {operation.Parameter.Name}");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitInstanceReference(IInstanceReferenceOperation operation)
{
LogString(nameof(IInstanceReferenceOperation));
LogString($" (ReferenceKind: {operation.ReferenceKind})");
LogCommonPropertiesAndNewLine(operation);
if (operation.IsImplicit)
{
if (operation.Parent is IMemberReferenceOperation memberReference && memberReference.Instance == operation)
{
Assert.False(memberReference.Member.IsStatic && !operation.HasErrors(this._compilation));
}
else if (operation.Parent is IInvocationOperation invocation && invocation.Instance == operation)
{
Assert.False(invocation.TargetMethod.IsStatic);
}
}
}
private void VisitMemberReferenceExpressionCommon(IMemberReferenceOperation operation)
{
if (operation.Member.IsStatic)
{
LogString(" (Static)");
}
LogCommonPropertiesAndNewLine(operation);
VisitInstance(operation.Instance);
}
public override void VisitFieldReference(IFieldReferenceOperation operation)
{
LogString(nameof(IFieldReferenceOperation));
LogString($": {operation.Field.ToTestDisplayString()}");
if (operation.IsDeclaration)
{
LogString($" (IsDeclaration: {operation.IsDeclaration})");
}
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitMethodReference(IMethodReferenceOperation operation)
{
LogString(nameof(IMethodReferenceOperation));
LogString($": {operation.Method.ToTestDisplayString()}");
if (operation.IsVirtual)
{
LogString(" (IsVirtual)");
}
Assert.Null(operation.Type);
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitPropertyReference(IPropertyReferenceOperation operation)
{
LogString(nameof(IPropertyReferenceOperation));
LogString($": {operation.Property.ToTestDisplayString()}");
VisitMemberReferenceExpressionCommon(operation);
if (operation.Arguments.Length > 0)
{
VisitArguments(operation.Arguments);
}
}
public override void VisitEventReference(IEventReferenceOperation operation)
{
LogString(nameof(IEventReferenceOperation));
LogString($": {operation.Event.ToTestDisplayString()}");
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitEventAssignment(IEventAssignmentOperation operation)
{
var kindStr = operation.Adds ? "EventAdd" : "EventRemove";
LogString($"{nameof(IEventAssignmentOperation)} ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
Assert.NotNull(operation.EventReference);
Visit(operation.EventReference, header: "Event Reference");
Visit(operation.HandlerValue, header: "Handler");
}
public override void VisitConditionalAccess(IConditionalAccessOperation operation)
{
LogString(nameof(IConditionalAccessOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, header: nameof(operation.Operation));
Visit(operation.WhenNotNull, header: nameof(operation.WhenNotNull));
Assert.NotNull(operation.Type);
}
public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation)
{
LogString(nameof(IConditionalAccessInstanceOperation));
LogCommonPropertiesAndNewLine(operation);
}
internal override void VisitPlaceholder(IPlaceholderOperation operation)
{
LogString(nameof(IPlaceholderOperation));
LogCommonPropertiesAndNewLine(operation);
Assert.Equal(PlaceholderKind.AggregationGroup, operation.PlaceholderKind);
}
public override void VisitUnaryOperator(IUnaryOperation operation)
{
LogString(nameof(IUnaryOperation));
var kindStr = $"{nameof(UnaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitBinaryOperator(IBinaryOperation operation)
{
LogString(nameof(IBinaryOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
if (operation.IsCompareText)
{
kindStr += ", CompareText";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
var unaryOperatorMethod = ((BinaryOperation)operation).UnaryOperatorMethod;
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, "Left");
Visit(operation.RightOperand, "Right");
}
public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation)
{
LogString(nameof(ITupleBinaryOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
LogString($" ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, "Left");
Visit(operation.RightOperand, "Right");
}
private void LogHasOperatorMethodExpressionCommon(IMethodSymbol operatorMethodOpt)
{
if (operatorMethodOpt != null)
{
LogSymbol(operatorMethodOpt, header: " (OperatorMethod");
LogString(")");
}
}
public override void VisitConversion(IConversionOperation operation)
{
LogString(nameof(IConversionOperation));
var isTryCast = $"TryCast: {(operation.IsTryCast ? "True" : "False")}";
var isChecked = operation.IsChecked ? "Checked" : "Unchecked";
LogString($" ({isTryCast}, {isChecked})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Indent();
LogConversion(operation.Conversion);
if (((Operation)operation).OwningSemanticModel == null)
{
LogNewLine();
Indent();
LogString($"({((ConversionOperation)operation).ConversionConvertible})");
Unindent();
}
Unindent();
LogNewLine();
Visit(operation.Operand, "Operand");
}
public override void VisitConditional(IConditionalOperation operation)
{
LogString(nameof(IConditionalOperation));
if (operation.IsRef)
{
LogString(" (IsRef)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Condition, "Condition");
Visit(operation.WhenTrue, "WhenTrue");
Visit(operation.WhenFalse, "WhenFalse");
}
public override void VisitCoalesce(ICoalesceOperation operation)
{
LogString(nameof(ICoalesceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Expression");
Indent();
LogConversion(operation.ValueConversion, "ValueConversion");
LogNewLine();
Indent();
LogString($"({((CoalesceOperation)operation).ValueConversionConvertible})");
Unindent();
LogNewLine();
Unindent();
Visit(operation.WhenNull, "WhenNull");
}
public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation)
{
LogString(nameof(ICoalesceAssignmentOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, nameof(operation.Target));
Visit(operation.Value, nameof(operation.Value));
}
public override void VisitIsType(IIsTypeOperation operation)
{
LogString(nameof(IIsTypeOperation));
if (operation.IsNegated)
{
LogString(" (IsNotExpression)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ValueOperand, "Operand");
Indent();
LogType(operation.TypeOperand, "IsType");
LogNewLine();
Unindent();
}
public override void VisitSizeOf(ISizeOfOperation operation)
{
LogString(nameof(ISizeOfOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.TypeOperand, "TypeOperand");
LogNewLine();
Unindent();
}
public override void VisitTypeOf(ITypeOfOperation operation)
{
LogString(nameof(ITypeOfOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.TypeOperand, "TypeOperand");
LogNewLine();
Unindent();
}
public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation)
{
LogString(nameof(IAnonymousFunctionOperation));
// For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart.
// That is how symbol display is implemented for C#.
// https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output.
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
base.VisitAnonymousFunction(operation);
}
public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation)
{
LogString(nameof(IFlowAnonymousFunctionOperation));
// For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart.
// That is how symbol display is implemented for C#.
// https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output.
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
base.VisitFlowAnonymousFunction(operation);
}
public override void VisitDelegateCreation(IDelegateCreationOperation operation)
{
LogString(nameof(IDelegateCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, nameof(operation.Target));
}
public override void VisitLiteral(ILiteralOperation operation)
{
LogString(nameof(ILiteralOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitAwait(IAwaitOperation operation)
{
LogString(nameof(IAwaitOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
public override void VisitNameOf(INameOfOperation operation)
{
LogString(nameof(INameOfOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Argument);
}
public override void VisitThrow(IThrowOperation operation)
{
LogString(nameof(IThrowOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Exception);
}
public override void VisitAddressOf(IAddressOfOperation operation)
{
LogString(nameof(IAddressOfOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Reference, "Reference");
}
public override void VisitObjectCreation(IObjectCreationOperation operation)
{
LogString(nameof(IObjectCreationOperation));
LogString($" (Constructor: {operation.Constructor?.ToTestDisplayString() ?? "<null>"})");
LogCommonPropertiesAndNewLine(operation);
VisitArguments(operation.Arguments);
Visit(operation.Initializer, "Initializer");
}
public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation)
{
LogString(nameof(IAnonymousObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
foreach (var initializer in operation.Initializers)
{
var simpleAssignment = (ISimpleAssignmentOperation)initializer;
var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target;
Assert.Empty(propertyReference.Arguments);
Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind);
Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind);
}
VisitArray(operation.Initializers, "Initializers", logElementCount: true);
}
public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation)
{
LogString(nameof(IDynamicObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
Visit(operation.Initializer, "Initializer");
}
public override void VisitDynamicInvocation(IDynamicInvocationOperation operation)
{
LogString(nameof(IDynamicInvocationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
}
public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation)
{
LogString(nameof(IDynamicIndexerAccessOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
}
public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation)
{
LogString(nameof(IObjectOrCollectionInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Initializers, "Initializers", logElementCount: true);
}
public override void VisitMemberInitializer(IMemberInitializerOperation operation)
{
LogString(nameof(IMemberInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.InitializedMember, "InitializedMember");
Visit(operation.Initializer, "Initializer");
}
[Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", error: true)]
public override void VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation)
{
// Kept to ensure that it's never called, as we can't override DefaultVisit in this visitor
throw ExceptionUtilities.Unreachable;
}
public override void VisitFieldInitializer(IFieldInitializerOperation operation)
{
LogString(nameof(IFieldInitializerOperation));
if (operation.InitializedFields.Length <= 1)
{
if (operation.InitializedFields.Length == 1)
{
LogSymbol(operation.InitializedFields[0], header: " (Field");
LogString(")");
}
LogCommonPropertiesAndNewLine(operation);
}
else
{
LogString($" ({operation.InitializedFields.Length} initialized fields)");
LogCommonPropertiesAndNewLine(operation);
Indent();
int index = 1;
foreach (var local in operation.InitializedFields)
{
LogSymbol(local, header: $"Field_{index++}");
LogNewLine();
}
Unindent();
}
LogLocals(operation.Locals);
base.VisitFieldInitializer(operation);
}
public override void VisitVariableInitializer(IVariableInitializerOperation operation)
{
LogString(nameof(IVariableInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
Assert.Empty(operation.Locals);
base.VisitVariableInitializer(operation);
}
public override void VisitPropertyInitializer(IPropertyInitializerOperation operation)
{
LogString(nameof(IPropertyInitializerOperation));
if (operation.InitializedProperties.Length <= 1)
{
if (operation.InitializedProperties.Length == 1)
{
LogSymbol(operation.InitializedProperties[0], header: " (Property");
LogString(")");
}
LogCommonPropertiesAndNewLine(operation);
}
else
{
LogString($" ({operation.InitializedProperties.Length} initialized properties)");
LogCommonPropertiesAndNewLine(operation);
Indent();
int index = 1;
foreach (var property in operation.InitializedProperties)
{
LogSymbol(property, header: $"Property_{index++}");
LogNewLine();
}
Unindent();
}
LogLocals(operation.Locals);
base.VisitPropertyInitializer(operation);
}
public override void VisitParameterInitializer(IParameterInitializerOperation operation)
{
LogString(nameof(IParameterInitializerOperation));
LogSymbol(operation.Parameter, header: " (Parameter");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
base.VisitParameterInitializer(operation);
}
public override void VisitArrayCreation(IArrayCreationOperation operation)
{
LogString(nameof(IArrayCreationOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.DimensionSizes, "Dimension Sizes", logElementCount: true);
Visit(operation.Initializer, "Initializer");
}
public override void VisitArrayInitializer(IArrayInitializerOperation operation)
{
LogString(nameof(IArrayInitializerOperation));
LogString($" ({operation.ElementValues.Length} elements)");
LogCommonPropertiesAndNewLine(operation);
Assert.Null(operation.Type);
VisitArray(operation.ElementValues, "Element Values", logElementCount: true);
}
public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation)
{
LogString(nameof(ISimpleAssignmentOperation));
if (operation.IsRef)
{
LogString(" (IsRef)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation)
{
LogString(nameof(IDeconstructionAssignmentOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation)
{
LogString(nameof(IDeclarationExpressionOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Expression);
}
public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation)
{
LogString(nameof(ICompoundAssignmentOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Indent();
LogConversion(operation.InConversion, "InConversion");
LogNewLine();
LogConversion(operation.OutConversion, "OutConversion");
LogNewLine();
Unindent();
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation)
{
LogString(nameof(IIncrementOrDecrementOperation));
var kindStr = operation.IsPostfix ? "Postfix" : "Prefix";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Target");
}
public override void VisitParenthesized(IParenthesizedOperation operation)
{
LogString(nameof(IParenthesizedOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation)
{
LogString(nameof(IDynamicMemberReferenceOperation));
// (Member Name: "quoted name", Containing Type: type)
LogString(" (");
LogConstant((object)operation.MemberName, "Member Name");
LogString(", ");
LogType(operation.ContainingType, "Containing Type");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
VisitArrayCommon(operation.TypeArguments, "Type Arguments", logElementCount: true, logNullForDefault: false, arrayElementVisitor: VisitSymbolArrayElement);
VisitInstance(operation.Instance);
}
public override void VisitDefaultValue(IDefaultValueOperation operation)
{
LogString(nameof(IDefaultValueOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation)
{
LogString(nameof(ITypeParameterObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
}
internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation)
{
LogString(nameof(INoPiaObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
}
public override void VisitInvalid(IInvalidOperation operation)
{
LogString(nameof(IInvalidOperation));
LogCommonPropertiesAndNewLine(operation);
VisitChildren(operation);
}
public override void VisitLocalFunction(ILocalFunctionOperation operation)
{
LogString(nameof(ILocalFunctionOperation));
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
if (operation.Body != null)
{
if (operation.IgnoredBody != null)
{
Visit(operation.Body, "Body");
Visit(operation.IgnoredBody, "IgnoredBody");
}
else
{
Visit(operation.Body);
}
}
else
{
Assert.Null(operation.IgnoredBody);
}
}
private void LogCaseClauseCommon(ICaseClauseOperation operation)
{
Assert.Equal(OperationKind.CaseClause, operation.Kind);
if (operation.Label != null)
{
LogString($" (Label Id: {GetLabelId(operation.Label)})");
}
var kindStr = $"{nameof(CaseKind)}.{operation.CaseKind}";
LogString($" ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation)
{
LogString(nameof(ISingleValueCaseClauseOperation));
LogCaseClauseCommon(operation);
Visit(operation.Value, "Value");
}
public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation)
{
LogString(nameof(IRelationalCaseClauseOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.Relation}";
LogString($" (Relational operator kind: {kindStr})");
LogCaseClauseCommon(operation);
Visit(operation.Value, "Value");
}
public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation)
{
LogString(nameof(IRangeCaseClauseOperation));
LogCaseClauseCommon(operation);
Visit(operation.MinimumValue, "Min");
Visit(operation.MaximumValue, "Max");
}
public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation)
{
LogString(nameof(IDefaultCaseClauseOperation));
LogCaseClauseCommon(operation);
}
public override void VisitTuple(ITupleOperation operation)
{
LogString(nameof(ITupleOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.NaturalType, nameof(operation.NaturalType));
LogNewLine();
Unindent();
VisitArray(operation.Elements, "Elements", logElementCount: true);
}
public override void VisitInterpolatedString(IInterpolatedStringOperation operation)
{
LogString(nameof(IInterpolatedStringOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Parts, "Parts", logElementCount: true);
}
public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation)
{
LogString(nameof(IInterpolatedStringTextOperation));
LogCommonPropertiesAndNewLine(operation);
if (operation.Text.Kind != OperationKind.Literal)
{
Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.Text).Operand.Kind);
}
Visit(operation.Text, "Text");
}
public override void VisitInterpolation(IInterpolationOperation operation)
{
LogString(nameof(IInterpolationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Expression, "Expression");
Visit(operation.Alignment, "Alignment");
Visit(operation.FormatString, "FormatString");
if (operation.FormatString != null && operation.FormatString.Kind != OperationKind.Literal)
{
Assert.Equal(OperationKind.Literal, ((IConversionOperation)operation.FormatString).Operand.Kind);
}
}
public override void VisitConstantPattern(IConstantPatternOperation operation)
{
LogString(nameof(IConstantPatternOperation));
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
}
public override void VisitRelationalPattern(IRelationalPatternOperation operation)
{
LogString(nameof(IRelationalPatternOperation));
LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})");
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
}
public override void VisitNegatedPattern(INegatedPatternOperation operation)
{
LogString(nameof(INegatedPatternOperation));
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Pattern, "Pattern");
}
public override void VisitBinaryPattern(IBinaryPatternOperation operation)
{
LogString(nameof(IBinaryPatternOperation));
LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})");
LogPatternPropertiesAndNewLine(operation);
Visit(operation.LeftPattern, "LeftPattern");
Visit(operation.RightPattern, "RightPattern");
}
public override void VisitTypePattern(ITypePatternOperation operation)
{
LogString(nameof(ITypePatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.MatchedType, $", {nameof(operation.MatchedType)}");
LogString(")");
LogNewLine();
}
public override void VisitDeclarationPattern(IDeclarationPatternOperation operation)
{
LogString(nameof(IDeclarationPatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}");
LogConstant((object)operation.MatchesNull, $", {nameof(operation.MatchesNull)}");
LogString(")");
LogNewLine();
}
public override void VisitRecursivePattern(IRecursivePatternOperation operation)
{
LogString(nameof(IRecursivePatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}");
LogType(operation.MatchedType, $", {nameof(operation.MatchedType)}");
LogSymbol(operation.DeconstructSymbol, $", {nameof(operation.DeconstructSymbol)}");
LogString(")");
LogNewLine();
VisitArray(operation.DeconstructionSubpatterns, $"{nameof(operation.DeconstructionSubpatterns)} ", true, true);
VisitArray(operation.PropertySubpatterns, $"{nameof(operation.PropertySubpatterns)} ", true, true);
}
public override void VisitPropertySubpattern(IPropertySubpatternOperation operation)
{
LogString(nameof(IPropertySubpatternOperation));
LogCommonProperties(operation);
LogNewLine();
Visit(operation.Member, $"{nameof(operation.Member)}");
Visit(operation.Pattern, $"{nameof(operation.Pattern)}");
}
public override void VisitIsPattern(IIsPatternOperation operation)
{
LogString(nameof(IIsPatternOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, $"{nameof(operation.Value)}");
Visit(operation.Pattern, "Pattern");
}
public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation)
{
LogString(nameof(IPatternCaseClauseOperation));
LogCaseClauseCommon(operation);
Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label);
Visit(operation.Pattern, "Pattern");
if (operation.Guard != null)
Visit(operation.Guard, nameof(operation.Guard));
}
public override void VisitTranslatedQuery(ITranslatedQueryOperation operation)
{
LogString(nameof(ITranslatedQueryOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
public override void VisitRaiseEvent(IRaiseEventOperation operation)
{
LogString(nameof(IRaiseEventOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.EventReference, header: "Event Reference");
VisitArguments(operation.Arguments);
}
public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation)
{
LogString(nameof(IConstructorBodyOperation));
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Initializer, "Initializer");
Visit(operation.BlockBody, "BlockBody");
Visit(operation.ExpressionBody, "ExpressionBody");
}
public override void VisitMethodBodyOperation(IMethodBodyOperation operation)
{
LogString(nameof(IMethodBodyOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.BlockBody, "BlockBody");
Visit(operation.ExpressionBody, "ExpressionBody");
}
public override void VisitDiscardOperation(IDiscardOperation operation)
{
LogString(nameof(IDiscardOperation));
LogString(" (");
LogSymbol(operation.DiscardSymbol, "Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitDiscardPattern(IDiscardPatternOperation operation)
{
LogString(nameof(IDiscardPatternOperation));
LogPatternPropertiesAndNewLine(operation);
}
public override void VisitSwitchExpression(ISwitchExpressionOperation operation)
{
LogString($"{nameof(ISwitchExpressionOperation)} ({operation.Arms.Length} arms, IsExhaustive: {operation.IsExhaustive})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, nameof(operation.Value));
VisitArray(operation.Arms, nameof(operation.Arms), logElementCount: true);
}
public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation)
{
LogString($"{nameof(ISwitchExpressionArmOperation)} ({operation.Locals.Length} locals)");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Pattern, nameof(operation.Pattern));
if (operation.Guard != null)
Visit(operation.Guard, nameof(operation.Guard));
Visit(operation.Value, nameof(operation.Value));
LogLocals(operation.Locals);
}
public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation)
{
LogString(nameof(IStaticLocalInitializationSemaphoreOperation));
LogSymbol(operation.Local, " (Local Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitRangeOperation(IRangeOperation operation)
{
LogString(nameof(IRangeOperation));
if (operation.IsLifted)
{
LogString(" (IsLifted)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, nameof(operation.LeftOperand));
Visit(operation.RightOperand, nameof(operation.RightOperand));
}
public override void VisitReDim(IReDimOperation operation)
{
LogString(nameof(IReDimOperation));
if (operation.Preserve)
{
LogString(" (Preserve)");
}
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Clauses, "Clauses", logElementCount: true);
}
public override void VisitReDimClause(IReDimClauseOperation operation)
{
LogString(nameof(IReDimClauseOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
VisitArray(operation.DimensionSizes, "DimensionSizes", logElementCount: true);
}
public override void VisitWith(IWithOperation operation)
{
LogString(nameof(IWithOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
Indent();
LogSymbol(operation.CloneMethod, nameof(operation.CloneMethod));
LogNewLine();
Unindent();
Visit(operation.Initializer, "Initializer");
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/OfKeywordRecommenderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class OfKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfAfterPossibleMethodTypeParamTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(|</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotAfterMethodTypeParamTest()
VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo(Of T)(|</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfDefinitelyInMethodTypeParamTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(|)(x As Integer)</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfAfterPossibleDelegateTypeParamTest()
VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub Goo(|</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotAfterDelegateTypeParamTest()
VerifyRecommendationsMissing(<ClassDeclaration>Delegate Sub Goo(Of T)(|</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfDefinitelyInDelegateTypeParamTest()
VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub Goo(|)(x As Integer)</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInClassDeclarationTypeParamTest()
VerifyRecommendationsContain(<File>Class Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInStructureDeclarationTypeParamTest()
VerifyRecommendationsContain(<File>Structure Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInInterfaceDeclarationTypeParamTest()
VerifyRecommendationsContain(<File>Interface Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotInEnumDeclarationTest()
' This is invalid code, so make sure we don't show it
VerifyRecommendationsMissing(<File>Enum Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotInModuleDeclarationTest()
VerifyRecommendationsMissing(<File>Module Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInVariableDeclaration1Test()
VerifyRecommendationsMissing(<MethodBody>Dim f As Goo(|</MethodBody>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInVariableDeclaration2Test()
VerifyRecommendationsContain(<MethodBody>Dim f As New Goo(|</MethodBody>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotInRealArraySpecifierTest()
VerifyRecommendationsMissing(<MethodBody>Dim f(|</MethodBody>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInMethodCallTest()
VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "Of")
End Sub
<WorkItem(541636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541636")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInGenericArrayBoundRankSpecifierTest()
VerifyRecommendationsContain(<MethodBody>Dim i As List(|</MethodBody>, "Of")
End Sub
<WorkItem(541636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541636")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NoOfInNonGenericArrayBoundRankSpecifierTest()
VerifyRecommendationsMissing(<MethodBody>Dim i As Integer(|</MethodBody>, "Of")
End Sub
<WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInNonGenericDelegateCreationTest()
Dim code =
<File>
Class C
Delegate Sub Goo()
Sub Main(args As String())
Dim f1 As New Goo(|
End Sub
End Class
</File>
VerifyRecommendationsMissing(code, "Of")
End Sub
<WorkItem(529552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529552")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InGenericDelegateCreationTest()
Dim code = <ModuleDeclaration><![CDATA[
Class C
Delegate Sub Goo(Of C)()
Sub Main(args As String())
Dim f1 As New Goo(|
End Sub
End Class
]]></ModuleDeclaration>
VerifyRecommendationsContain(code, "Of")
End Sub
<WorkItem(529552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529552")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InPotentiallyGenericDelegateCreationTest()
Dim code = <ModuleDeclaration><![CDATA[
Class C
Delegate Sub Goo()
Delegate Sub Goo(Of C)()
Sub Main(args As String())
Dim f1 As New Goo(|
End Sub
End Class
]]></ModuleDeclaration>
VerifyRecommendationsContain(code, "Of")
End Sub
<WorkItem(529552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529552")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInNonGenericDelegateCreationWithGenericTypeOfSameNameTest()
Dim code =
<File>
Class Goo(Of U)
End Class
Class C
Delegate Sub Goo()
Sub Main(args As String())
Dim f1 As New Goo(|
End Sub
End Class
</File>
VerifyRecommendationsMissing(code, "Of")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterEolTest()
VerifyRecommendationsContain(
<MethodBody>Goo(
|</MethodBody>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InImplementsClauseTest()
Dim code =
<File>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class G(Of U)
Implements IEquatable(Of U)
Public Function Equals(other As U) As Boolean Implements IEquatable(|
Throw New NotImplementedException()
End Function
End Class
</File>
VerifyRecommendationsContain(code, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InInheritsStatementTest()
Dim code =
<File>
Class G(Of T)
End Class
Class DG
Inherits G(|
End Class
</File>
VerifyRecommendationsContain(code, "Of")
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class OfKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfAfterPossibleMethodTypeParamTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(|</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotAfterMethodTypeParamTest()
VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo(Of T)(|</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfDefinitelyInMethodTypeParamTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(|)(x As Integer)</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfAfterPossibleDelegateTypeParamTest()
VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub Goo(|</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotAfterDelegateTypeParamTest()
VerifyRecommendationsMissing(<ClassDeclaration>Delegate Sub Goo(Of T)(|</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfDefinitelyInDelegateTypeParamTest()
VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub Goo(|)(x As Integer)</ClassDeclaration>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInClassDeclarationTypeParamTest()
VerifyRecommendationsContain(<File>Class Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInStructureDeclarationTypeParamTest()
VerifyRecommendationsContain(<File>Structure Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInInterfaceDeclarationTypeParamTest()
VerifyRecommendationsContain(<File>Interface Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotInEnumDeclarationTest()
' This is invalid code, so make sure we don't show it
VerifyRecommendationsMissing(<File>Enum Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotInModuleDeclarationTest()
VerifyRecommendationsMissing(<File>Module Goo(|</File>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInVariableDeclaration1Test()
VerifyRecommendationsMissing(<MethodBody>Dim f As Goo(|</MethodBody>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInVariableDeclaration2Test()
VerifyRecommendationsContain(<MethodBody>Dim f As New Goo(|</MethodBody>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfNotInRealArraySpecifierTest()
VerifyRecommendationsMissing(<MethodBody>Dim f(|</MethodBody>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInMethodCallTest()
VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "Of")
End Sub
<WorkItem(541636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541636")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OfInGenericArrayBoundRankSpecifierTest()
VerifyRecommendationsContain(<MethodBody>Dim i As List(|</MethodBody>, "Of")
End Sub
<WorkItem(541636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541636")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NoOfInNonGenericArrayBoundRankSpecifierTest()
VerifyRecommendationsMissing(<MethodBody>Dim i As Integer(|</MethodBody>, "Of")
End Sub
<WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInNonGenericDelegateCreationTest()
Dim code =
<File>
Class C
Delegate Sub Goo()
Sub Main(args As String())
Dim f1 As New Goo(|
End Sub
End Class
</File>
VerifyRecommendationsMissing(code, "Of")
End Sub
<WorkItem(529552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529552")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InGenericDelegateCreationTest()
Dim code = <ModuleDeclaration><![CDATA[
Class C
Delegate Sub Goo(Of C)()
Sub Main(args As String())
Dim f1 As New Goo(|
End Sub
End Class
]]></ModuleDeclaration>
VerifyRecommendationsContain(code, "Of")
End Sub
<WorkItem(529552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529552")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InPotentiallyGenericDelegateCreationTest()
Dim code = <ModuleDeclaration><![CDATA[
Class C
Delegate Sub Goo()
Delegate Sub Goo(Of C)()
Sub Main(args As String())
Dim f1 As New Goo(|
End Sub
End Class
]]></ModuleDeclaration>
VerifyRecommendationsContain(code, "Of")
End Sub
<WorkItem(529552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529552")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInNonGenericDelegateCreationWithGenericTypeOfSameNameTest()
Dim code =
<File>
Class Goo(Of U)
End Class
Class C
Delegate Sub Goo()
Sub Main(args As String())
Dim f1 As New Goo(|
End Sub
End Class
</File>
VerifyRecommendationsMissing(code, "Of")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterEolTest()
VerifyRecommendationsContain(
<MethodBody>Goo(
|</MethodBody>, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InImplementsClauseTest()
Dim code =
<File>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class G(Of U)
Implements IEquatable(Of U)
Public Function Equals(other As U) As Boolean Implements IEquatable(|
Throw New NotImplementedException()
End Function
End Class
</File>
VerifyRecommendationsContain(code, "Of")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub InInheritsStatementTest()
Dim code =
<File>
Class G(Of T)
End Class
Class DG
Inherits G(|
End Class
</File>
VerifyRecommendationsContain(code, "Of")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicCastReducer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
Partial Friend Class VisualBasicCastReducer
Inherits AbstractVisualBasicReducer
Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) =
New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool))
Public Sub New()
MyBase.New(s_pool)
End Sub
Private Shared ReadOnly s_simplifyCast As Func(Of CastExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyCast
Private Overloads Shared Function SimplifyCast(
node As CastExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As ExpressionSyntax
If Not node.IsUnnecessaryCast(semanticModel, cancellationToken) Then
Return node
End If
Return node.Uncast()
End Function
Private Shared ReadOnly s_simplifyPredefinedCast As Func(Of PredefinedCastExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyPredefinedCast
Private Overloads Shared Function SimplifyPredefinedCast(
node As PredefinedCastExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As ExpressionSyntax
If Not node.IsUnnecessaryCast(semanticModel, cancellationToken) Then
Return node
End If
Return node.Uncast()
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification
Partial Friend Class VisualBasicCastReducer
Inherits AbstractVisualBasicReducer
Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) =
New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool))
Public Sub New()
MyBase.New(s_pool)
End Sub
Private Shared ReadOnly s_simplifyCast As Func(Of CastExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyCast
Private Overloads Shared Function SimplifyCast(
node As CastExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As ExpressionSyntax
If Not node.IsUnnecessaryCast(semanticModel, cancellationToken) Then
Return node
End If
Return node.Uncast()
End Function
Private Shared ReadOnly s_simplifyPredefinedCast As Func(Of PredefinedCastExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyPredefinedCast
Private Overloads Shared Function SimplifyPredefinedCast(
node As PredefinedCastExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As ExpressionSyntax
If Not node.IsUnnecessaryCast(semanticModel, cancellationToken) Then
Return node
End If
Return node.Uncast()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/EditorFeatures/VisualBasicTest/Structure/DisabledCodeStructureTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Structure
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class DisabledCodeStructureProviderTests
Inherits AbstractVisualBasicSyntaxTriviaStructureProviderTests
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New DisabledTextTriviaStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDisabledIf() As Task
Const code = "
#If False
{|span:$$Blah
Blah
Blah|}
#End If
"
Await VerifyBlockSpansAsync(code,
Region("span", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDisabledElse() As Task
Const code = "
#If True
#Else
{|span:$$Blah
Blah
Blah|}
#End If
"
Await VerifyBlockSpansAsync(code,
Region("span", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDisabledElseIf() As Task
Const code = "
#If True
#ElseIf False
{|span:$$Blah
Blah
Blah|}
#End If
"
Await VerifyBlockSpansAsync(code,
Region("span", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True))
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.VisualBasic.Structure
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class DisabledCodeStructureProviderTests
Inherits AbstractVisualBasicSyntaxTriviaStructureProviderTests
Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider
Return New DisabledTextTriviaStructureProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDisabledIf() As Task
Const code = "
#If False
{|span:$$Blah
Blah
Blah|}
#End If
"
Await VerifyBlockSpansAsync(code,
Region("span", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDisabledElse() As Task
Const code = "
#If True
#Else
{|span:$$Blah
Blah
Blah|}
#End If
"
Await VerifyBlockSpansAsync(code,
Region("span", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDisabledElseIf() As Task
Const code = "
#If True
#ElseIf False
{|span:$$Blah
Blah
Blah|}
#End If
"
Await VerifyBlockSpansAsync(code,
Region("span", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True))
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/VisualBasic/Portable/Symbols/UsedAssemblies.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Private _lazyUsedAssemblyReferences As ConcurrentSet(Of AssemblySymbol)
Private _usedAssemblyReferencesFrozen As Boolean
Public Overrides Function GetUsedAssemblyReferences(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of MetadataReference)
Dim usedAssemblies As ConcurrentSet(Of AssemblySymbol) = GetCompleteSetOfUsedAssemblies(cancellationToken)
If usedAssemblies Is Nothing Then
Return ImmutableArray(Of MetadataReference).Empty
End If
' Use stable ordering for the result, matching the order in References.
Dim builder = ArrayBuilder(Of MetadataReference).GetInstance(usedAssemblies.Count)
For Each reference In References
If reference.Properties.Kind = MetadataImageKind.Assembly Then
Dim symbol As Symbol = GetBoundReferenceManager().GetReferencedAssemblySymbol(reference)
If symbol IsNot Nothing AndAlso usedAssemblies.Contains(DirectCast(symbol, AssemblySymbol)) Then
builder.Add(reference)
End If
End If
Next
Return builder.ToImmutableAndFree()
End Function
Private Function GetCompleteSetOfUsedAssemblies(cancellationToken As CancellationToken) As ConcurrentSet(Of AssemblySymbol)
If Not _usedAssemblyReferencesFrozen AndAlso Not Volatile.Read(_usedAssemblyReferencesFrozen) Then
Dim diagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance(), New ConcurrentSet(Of AssemblySymbol)())
RoslynDebug.Assert(diagnostics.AccumulatesDiagnostics)
GetDiagnosticsWithoutFiltering(CompilationStage.Declare, includeEarlierStages:=True, diagnostics, cancellationToken)
Dim seenErrors As Boolean = diagnostics.HasAnyErrors()
If Not seenErrors Then
diagnostics.DiagnosticBag.Clear()
GetDiagnosticsForAllMethodBodies(hasDeclarationErrors:=False, diagnostics, doLowering:=True, cancellationToken)
seenErrors = diagnostics.HasAnyErrors()
If Not seenErrors Then
AddUsedAssemblies(diagnostics.DependenciesBag)
End If
End If
CompleteTheSetOfUsedAssemblies(seenErrors, cancellationToken)
diagnostics.DiagnosticBag.Free()
End If
Return _lazyUsedAssemblyReferences
End Function
Private Sub AddUsedAssembly(dependency As AssemblySymbol, stack As ArrayBuilder(Of AssemblySymbol))
If AddUsedAssembly(dependency) Then
stack.Push(dependency)
End If
End Sub
Private Sub AddReferencedAssemblies(assembly As AssemblySymbol, includeMainModule As Boolean, stack As ArrayBuilder(Of AssemblySymbol))
For i As Integer = If(includeMainModule, 0, 1) To assembly.Modules.Length - 1
For Each dependency In assembly.Modules(i).ReferencedAssemblySymbols
AddUsedAssembly(dependency, stack)
Next
Next
End Sub
Private Sub CompleteTheSetOfUsedAssemblies(seenErrors As Boolean, cancellationToken As CancellationToken)
If _usedAssemblyReferencesFrozen OrElse Volatile.Read(_usedAssemblyReferencesFrozen) Then
Return
End If
If seenErrors Then
' Add all referenced assemblies
For Each assembly As AssemblySymbol In SourceModule.ReferencedAssemblySymbols
AddUsedAssembly(assembly)
Next
Else
' Assume that all assemblies used by the added modules are also used
For i As Integer = 1 To SourceAssembly.Modules.Length - 1
For Each dependency In SourceAssembly.Modules(i).ReferencedAssemblySymbols
AddUsedAssembly(dependency)
Next
Next
If _usedAssemblyReferencesFrozen OrElse Volatile.Read(_usedAssemblyReferencesFrozen) Then
Return
End If
' Assume that all assemblies used by the used assemblies are also used
' This, for example, takes care of including facade assemblies that forward types around.
If _lazyUsedAssemblyReferences IsNot Nothing Then
SyncLock _lazyUsedAssemblyReferences
If _usedAssemblyReferencesFrozen OrElse Volatile.Read(_usedAssemblyReferencesFrozen) Then
Return
End If
Dim stack = ArrayBuilder(Of AssemblySymbol).GetInstance(_lazyUsedAssemblyReferences.Count)
stack.AddRange(_lazyUsedAssemblyReferences)
While stack.Count <> 0
Dim current As AssemblySymbol = stack.Pop()
Dim usedAssemblies As ConcurrentSet(Of AssemblySymbol)
Dim sourceAssembly = TryCast(current, SourceAssemblySymbol)
If sourceAssembly IsNot Nothing Then
' The set of assemblies used by the referenced compilation feels Like
' a reasonable approximation to the set of assembly references that would
' be emitted into the resulting binary for that compilation. An alternative
' would be to attempt to emit and get the exact set of emitted references
' in case of success. This might be too slow though.
usedAssemblies = sourceAssembly.DeclaringCompilation.GetCompleteSetOfUsedAssemblies(cancellationToken)
If usedAssemblies IsNot Nothing Then
For Each dependency As AssemblySymbol In usedAssemblies
Debug.Assert(Not dependency.IsLinked)
AddUsedAssembly(dependency, stack)
Next
End If
Continue While
End If
Dim retargetingAssembly = TryCast(current, RetargetingAssemblySymbol)
If retargetingAssembly IsNot Nothing Then
usedAssemblies = retargetingAssembly.UnderlyingAssembly.DeclaringCompilation.GetCompleteSetOfUsedAssemblies(cancellationToken)
If usedAssemblies IsNot Nothing Then
For Each underlyingDependency As AssemblySymbol In retargetingAssembly.UnderlyingAssembly.SourceModule.ReferencedAssemblySymbols
If Not underlyingDependency.IsLinked AndAlso usedAssemblies.Contains(underlyingDependency) Then
Dim dependency As AssemblySymbol = Nothing
If Not DirectCast(retargetingAssembly.Modules(0), RetargetingModuleSymbol).RetargetingDefinitions(underlyingDependency, dependency) Then
Debug.Assert(retargetingAssembly.Modules(0).ReferencedAssemblySymbols.Contains(underlyingDependency))
dependency = underlyingDependency
End If
AddUsedAssembly(dependency, stack)
End If
Next
End If
AddReferencedAssemblies(retargetingAssembly, includeMainModule:=False, stack)
Continue While
End If
AddReferencedAssemblies(current, includeMainModule:=True, stack)
End While
stack.Free()
End SyncLock
End If
If SourceAssembly.CorLibrary IsNot Nothing Then
' Add core library
AddUsedAssembly(sourceAssembly.CorLibrary)
End If
End If
_usedAssemblyReferencesFrozen = True
End Sub
Friend Sub AddUsedAssemblies(assemblies As ICollection(Of AssemblySymbol))
If Not assemblies.IsNullOrEmpty() Then
For Each candidate In assemblies
AddUsedAssembly(candidate)
Next
End If
End Sub
Friend Function AddUsedAssembly(assembly As AssemblySymbol) As Boolean
If assembly Is Nothing OrElse assembly Is SourceAssembly OrElse assembly.IsMissing Then
Return False
End If
If _lazyUsedAssemblyReferences Is Nothing Then
Interlocked.CompareExchange(_lazyUsedAssemblyReferences, New ConcurrentSet(Of AssemblySymbol)(), Nothing)
End If
#If DEBUG Then
Dim wasFrozen As Boolean = _usedAssemblyReferencesFrozen
#End If
Dim added As Boolean = _lazyUsedAssemblyReferences.Add(assembly)
#If DEBUG Then
Debug.Assert(Not added OrElse Not wasFrozen)
#End If
Return added
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Private _lazyUsedAssemblyReferences As ConcurrentSet(Of AssemblySymbol)
Private _usedAssemblyReferencesFrozen As Boolean
Public Overrides Function GetUsedAssemblyReferences(Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of MetadataReference)
Dim usedAssemblies As ConcurrentSet(Of AssemblySymbol) = GetCompleteSetOfUsedAssemblies(cancellationToken)
If usedAssemblies Is Nothing Then
Return ImmutableArray(Of MetadataReference).Empty
End If
' Use stable ordering for the result, matching the order in References.
Dim builder = ArrayBuilder(Of MetadataReference).GetInstance(usedAssemblies.Count)
For Each reference In References
If reference.Properties.Kind = MetadataImageKind.Assembly Then
Dim symbol As Symbol = GetBoundReferenceManager().GetReferencedAssemblySymbol(reference)
If symbol IsNot Nothing AndAlso usedAssemblies.Contains(DirectCast(symbol, AssemblySymbol)) Then
builder.Add(reference)
End If
End If
Next
Return builder.ToImmutableAndFree()
End Function
Private Function GetCompleteSetOfUsedAssemblies(cancellationToken As CancellationToken) As ConcurrentSet(Of AssemblySymbol)
If Not _usedAssemblyReferencesFrozen AndAlso Not Volatile.Read(_usedAssemblyReferencesFrozen) Then
Dim diagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance(), New ConcurrentSet(Of AssemblySymbol)())
RoslynDebug.Assert(diagnostics.AccumulatesDiagnostics)
GetDiagnosticsWithoutFiltering(CompilationStage.Declare, includeEarlierStages:=True, diagnostics, cancellationToken)
Dim seenErrors As Boolean = diagnostics.HasAnyErrors()
If Not seenErrors Then
diagnostics.DiagnosticBag.Clear()
GetDiagnosticsForAllMethodBodies(hasDeclarationErrors:=False, diagnostics, doLowering:=True, cancellationToken)
seenErrors = diagnostics.HasAnyErrors()
If Not seenErrors Then
AddUsedAssemblies(diagnostics.DependenciesBag)
End If
End If
CompleteTheSetOfUsedAssemblies(seenErrors, cancellationToken)
diagnostics.DiagnosticBag.Free()
End If
Return _lazyUsedAssemblyReferences
End Function
Private Sub AddUsedAssembly(dependency As AssemblySymbol, stack As ArrayBuilder(Of AssemblySymbol))
If AddUsedAssembly(dependency) Then
stack.Push(dependency)
End If
End Sub
Private Sub AddReferencedAssemblies(assembly As AssemblySymbol, includeMainModule As Boolean, stack As ArrayBuilder(Of AssemblySymbol))
For i As Integer = If(includeMainModule, 0, 1) To assembly.Modules.Length - 1
For Each dependency In assembly.Modules(i).ReferencedAssemblySymbols
AddUsedAssembly(dependency, stack)
Next
Next
End Sub
Private Sub CompleteTheSetOfUsedAssemblies(seenErrors As Boolean, cancellationToken As CancellationToken)
If _usedAssemblyReferencesFrozen OrElse Volatile.Read(_usedAssemblyReferencesFrozen) Then
Return
End If
If seenErrors Then
' Add all referenced assemblies
For Each assembly As AssemblySymbol In SourceModule.ReferencedAssemblySymbols
AddUsedAssembly(assembly)
Next
Else
' Assume that all assemblies used by the added modules are also used
For i As Integer = 1 To SourceAssembly.Modules.Length - 1
For Each dependency In SourceAssembly.Modules(i).ReferencedAssemblySymbols
AddUsedAssembly(dependency)
Next
Next
If _usedAssemblyReferencesFrozen OrElse Volatile.Read(_usedAssemblyReferencesFrozen) Then
Return
End If
' Assume that all assemblies used by the used assemblies are also used
' This, for example, takes care of including facade assemblies that forward types around.
If _lazyUsedAssemblyReferences IsNot Nothing Then
SyncLock _lazyUsedAssemblyReferences
If _usedAssemblyReferencesFrozen OrElse Volatile.Read(_usedAssemblyReferencesFrozen) Then
Return
End If
Dim stack = ArrayBuilder(Of AssemblySymbol).GetInstance(_lazyUsedAssemblyReferences.Count)
stack.AddRange(_lazyUsedAssemblyReferences)
While stack.Count <> 0
Dim current As AssemblySymbol = stack.Pop()
Dim usedAssemblies As ConcurrentSet(Of AssemblySymbol)
Dim sourceAssembly = TryCast(current, SourceAssemblySymbol)
If sourceAssembly IsNot Nothing Then
' The set of assemblies used by the referenced compilation feels Like
' a reasonable approximation to the set of assembly references that would
' be emitted into the resulting binary for that compilation. An alternative
' would be to attempt to emit and get the exact set of emitted references
' in case of success. This might be too slow though.
usedAssemblies = sourceAssembly.DeclaringCompilation.GetCompleteSetOfUsedAssemblies(cancellationToken)
If usedAssemblies IsNot Nothing Then
For Each dependency As AssemblySymbol In usedAssemblies
Debug.Assert(Not dependency.IsLinked)
AddUsedAssembly(dependency, stack)
Next
End If
Continue While
End If
Dim retargetingAssembly = TryCast(current, RetargetingAssemblySymbol)
If retargetingAssembly IsNot Nothing Then
usedAssemblies = retargetingAssembly.UnderlyingAssembly.DeclaringCompilation.GetCompleteSetOfUsedAssemblies(cancellationToken)
If usedAssemblies IsNot Nothing Then
For Each underlyingDependency As AssemblySymbol In retargetingAssembly.UnderlyingAssembly.SourceModule.ReferencedAssemblySymbols
If Not underlyingDependency.IsLinked AndAlso usedAssemblies.Contains(underlyingDependency) Then
Dim dependency As AssemblySymbol = Nothing
If Not DirectCast(retargetingAssembly.Modules(0), RetargetingModuleSymbol).RetargetingDefinitions(underlyingDependency, dependency) Then
Debug.Assert(retargetingAssembly.Modules(0).ReferencedAssemblySymbols.Contains(underlyingDependency))
dependency = underlyingDependency
End If
AddUsedAssembly(dependency, stack)
End If
Next
End If
AddReferencedAssemblies(retargetingAssembly, includeMainModule:=False, stack)
Continue While
End If
AddReferencedAssemblies(current, includeMainModule:=True, stack)
End While
stack.Free()
End SyncLock
End If
If SourceAssembly.CorLibrary IsNot Nothing Then
' Add core library
AddUsedAssembly(sourceAssembly.CorLibrary)
End If
End If
_usedAssemblyReferencesFrozen = True
End Sub
Friend Sub AddUsedAssemblies(assemblies As ICollection(Of AssemblySymbol))
If Not assemblies.IsNullOrEmpty() Then
For Each candidate In assemblies
AddUsedAssembly(candidate)
Next
End If
End Sub
Friend Function AddUsedAssembly(assembly As AssemblySymbol) As Boolean
If assembly Is Nothing OrElse assembly Is SourceAssembly OrElse assembly.IsMissing Then
Return False
End If
If _lazyUsedAssemblyReferences Is Nothing Then
Interlocked.CompareExchange(_lazyUsedAssemblyReferences, New ConcurrentSet(Of AssemblySymbol)(), Nothing)
End If
#If DEBUG Then
Dim wasFrozen As Boolean = _usedAssemblyReferencesFrozen
#End If
Dim added As Boolean = _lazyUsedAssemblyReferences.Add(assembly)
#If DEBUG Then
Debug.Assert(Not added OrElse Not wasFrozen)
#End If
Return added
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.NamedTypeSymbolKey.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class NamedTypeSymbolKey
{
public static void Create(INamedTypeSymbol symbol, SymbolKeyWriter visitor)
{
visitor.WriteString(symbol.MetadataName);
visitor.WriteSymbolKey(symbol.ContainingSymbol);
visitor.WriteInteger(symbol.Arity);
visitor.WriteBoolean(symbol.IsUnboundGenericType);
if (!symbol.Equals(symbol.ConstructedFrom) && !symbol.IsUnboundGenericType)
{
visitor.WriteSymbolKeyArray(symbol.TypeArguments);
}
else
{
visitor.WriteSymbolKeyArray(ImmutableArray<ITypeSymbol>.Empty);
}
}
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var metadataName = reader.ReadString()!;
var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason);
var arity = reader.ReadInteger();
var isUnboundGenericType = reader.ReadBoolean();
using var typeArguments = reader.ReadSymbolKeyArray<ITypeSymbol>(out var typeArgumentsFailureReason);
if (containingSymbolFailureReason != null)
{
failureReason = $"({nameof(NamedTypeSymbolKey)} {nameof(containingSymbolFailureReason)} failed -> {containingSymbolFailureReason})";
return default;
}
if (typeArgumentsFailureReason != null)
{
failureReason = $"({nameof(NamedTypeSymbolKey)} {nameof(typeArguments)} failed -> {typeArgumentsFailureReason})";
return default;
}
if (typeArguments.IsDefault)
{
failureReason = $"({nameof(NamedTypeSymbolKey)} {nameof(typeArguments)} failed)";
return default;
}
var typeArgumentArray = typeArguments.Count == 0
? Array.Empty<ITypeSymbol>()
: typeArguments.Builder.ToArray();
using var result = PooledArrayBuilder<INamedTypeSymbol>.GetInstance();
foreach (var nsOrType in containingSymbolResolution.OfType<INamespaceOrTypeSymbol>())
{
Resolve(
result, nsOrType, metadataName, arity,
isUnboundGenericType, typeArgumentArray);
}
return CreateResolution(result, $"({nameof(NamedTypeSymbolKey)} failed)", out failureReason);
}
private static void Resolve(
PooledArrayBuilder<INamedTypeSymbol> result,
INamespaceOrTypeSymbol container,
string metadataName,
int arity,
bool isUnboundGenericType,
ITypeSymbol[] typeArguments)
{
foreach (var type in container.GetTypeMembers(GetName(metadataName), arity))
{
var currentType = typeArguments.Length > 0 ? type.Construct(typeArguments) : type;
currentType = isUnboundGenericType ? currentType.ConstructUnboundGenericType() : currentType;
result.AddIfNotNull(currentType);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class NamedTypeSymbolKey
{
public static void Create(INamedTypeSymbol symbol, SymbolKeyWriter visitor)
{
visitor.WriteString(symbol.MetadataName);
visitor.WriteSymbolKey(symbol.ContainingSymbol);
visitor.WriteInteger(symbol.Arity);
visitor.WriteBoolean(symbol.IsUnboundGenericType);
if (!symbol.Equals(symbol.ConstructedFrom) && !symbol.IsUnboundGenericType)
{
visitor.WriteSymbolKeyArray(symbol.TypeArguments);
}
else
{
visitor.WriteSymbolKeyArray(ImmutableArray<ITypeSymbol>.Empty);
}
}
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var metadataName = reader.ReadString()!;
var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason);
var arity = reader.ReadInteger();
var isUnboundGenericType = reader.ReadBoolean();
using var typeArguments = reader.ReadSymbolKeyArray<ITypeSymbol>(out var typeArgumentsFailureReason);
if (containingSymbolFailureReason != null)
{
failureReason = $"({nameof(NamedTypeSymbolKey)} {nameof(containingSymbolFailureReason)} failed -> {containingSymbolFailureReason})";
return default;
}
if (typeArgumentsFailureReason != null)
{
failureReason = $"({nameof(NamedTypeSymbolKey)} {nameof(typeArguments)} failed -> {typeArgumentsFailureReason})";
return default;
}
if (typeArguments.IsDefault)
{
failureReason = $"({nameof(NamedTypeSymbolKey)} {nameof(typeArguments)} failed)";
return default;
}
var typeArgumentArray = typeArguments.Count == 0
? Array.Empty<ITypeSymbol>()
: typeArguments.Builder.ToArray();
using var result = PooledArrayBuilder<INamedTypeSymbol>.GetInstance();
foreach (var nsOrType in containingSymbolResolution.OfType<INamespaceOrTypeSymbol>())
{
Resolve(
result, nsOrType, metadataName, arity,
isUnboundGenericType, typeArgumentArray);
}
return CreateResolution(result, $"({nameof(NamedTypeSymbolKey)} failed)", out failureReason);
}
private static void Resolve(
PooledArrayBuilder<INamedTypeSymbol> result,
INamespaceOrTypeSymbol container,
string metadataName,
int arity,
bool isUnboundGenericType,
ITypeSymbol[] typeArguments)
{
foreach (var type in container.GetTypeMembers(GetName(metadataName), arity))
{
var currentType = typeArguments.Length > 0 ? type.Construct(typeArguments) : type;
currentType = isUnboundGenericType ? currentType.ConstructUnboundGenericType() : currentType;
result.AddIfNotNull(currentType);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicSelectionResult.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Friend Class VisualBasicSelectionResult
Inherits SelectionResult
Public Shared Async Function CreateResultAsync(
status As OperationStatus,
originalSpan As TextSpan,
finalSpan As TextSpan,
options As OptionSet,
selectionInExpression As Boolean,
document As SemanticDocument,
firstToken As SyntaxToken,
lastToken As SyntaxToken,
cancellationToken As CancellationToken) As Task(Of VisualBasicSelectionResult)
Contract.ThrowIfNull(document)
Dim firstAnnotation = New SyntaxAnnotation()
Dim lastAnnotation = New SyntaxAnnotation()
Dim root = document.Root
Dim newDocument = Await SemanticDocument.CreateAsync(document.Document.WithSyntaxRoot(root.AddAnnotations(
{Tuple.Create(Of SyntaxToken, SyntaxAnnotation)(firstToken, firstAnnotation),
Tuple.Create(Of SyntaxToken, SyntaxAnnotation)(lastToken, lastAnnotation)})), cancellationToken).ConfigureAwait(False)
Return New VisualBasicSelectionResult(
status,
originalSpan,
finalSpan,
options,
selectionInExpression,
newDocument,
firstAnnotation,
lastAnnotation)
End Function
Private Sub New(
status As OperationStatus,
originalSpan As TextSpan,
finalSpan As TextSpan,
options As OptionSet,
selectionInExpression As Boolean,
document As SemanticDocument,
firstTokenAnnotation As SyntaxAnnotation,
lastTokenAnnotation As SyntaxAnnotation)
MyBase.New(
status,
originalSpan,
finalSpan,
options,
selectionInExpression,
document,
firstTokenAnnotation,
lastTokenAnnotation)
End Sub
Protected Overrides Function UnderAnonymousOrLocalMethod(token As SyntaxToken, firstToken As SyntaxToken, lastToken As SyntaxToken) As Boolean
Dim current = token.Parent
While current IsNot Nothing
If TypeOf current Is DeclarationStatementSyntax OrElse
TypeOf current Is LambdaExpressionSyntax Then
Exit While
End If
current = current.Parent
End While
If current Is Nothing OrElse TypeOf current Is DeclarationStatementSyntax Then
Return False
End If
' make sure selection contains the lambda
Return firstToken.SpanStart <= current.GetFirstToken().SpanStart AndAlso
current.GetLastToken().Span.End <= lastToken.Span.End
End Function
Public Overrides Function ContainingScopeHasAsyncKeyword() As Boolean
If SelectionInExpression Then
Return False
End If
Dim node = Me.GetContainingScope()
If TypeOf node Is MethodBlockBaseSyntax Then
Dim methodBlock = DirectCast(node, MethodBlockBaseSyntax)
If methodBlock.BlockStatement IsNot Nothing Then
Return methodBlock.BlockStatement.Modifiers.Any(SyntaxKind.AsyncKeyword)
End If
Return False
ElseIf TypeOf node Is LambdaExpressionSyntax Then
Dim lambda = DirectCast(node, LambdaExpressionSyntax)
If lambda.SubOrFunctionHeader IsNot Nothing Then
Return lambda.SubOrFunctionHeader.Modifiers.Any(SyntaxKind.AsyncKeyword)
End If
End If
Return False
End Function
Public Overrides Function GetContainingScope() As SyntaxNode
Contract.ThrowIfNull(Me.SemanticDocument)
Dim first = GetFirstTokenInSelection()
If SelectionInExpression Then
Dim last = GetLastTokenInSelection()
Dim scope = first.GetCommonRoot(last).GetAncestorOrThis(Of ExpressionSyntax)()
Contract.ThrowIfNull(scope, "Should always find an expression given that SelectionInExpression was true")
Return VisualBasicSyntaxFacts.Instance.GetRootStandaloneExpression(scope)
Else
' it contains statements
Return first.GetAncestors(Of SyntaxNode).FirstOrDefault(Function(n) TypeOf n Is MethodBlockBaseSyntax OrElse TypeOf n Is LambdaExpressionSyntax)
End If
End Function
Public Overrides Function GetContainingScopeType() As ITypeSymbol
Dim node = Me.GetContainingScope()
Dim semanticModel = Me.SemanticDocument.SemanticModel
' special case for collection initializer and explicit cast
If node.IsExpressionInCast() Then
Dim castExpression = TryCast(node.Parent, CastExpressionSyntax)
If castExpression IsNot Nothing Then
Return semanticModel.GetTypeInfo(castExpression.Type).Type
End If
End If
Dim expression As ExpressionSyntax
If TypeOf node Is CollectionInitializerSyntax Then
expression = node.GetUnparenthesizedExpression()
Return semanticModel.GetTypeInfo(expression).ConvertedType
End If
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
Dim symbol = semanticModel.GetDeclaredSymbol(methodBlock.BlockStatement)
Dim propertySymbol = TryCast(symbol, IPropertySymbol)
If propertySymbol IsNot Nothing Then
Return propertySymbol.Type
Else
Return DirectCast(symbol, IMethodSymbol).ReturnType
End If
End If
Dim info As TypeInfo
Dim lambda = TryCast(node, LambdaExpressionSyntax)
If lambda IsNot Nothing Then
If SelectionInExpression Then
info = semanticModel.GetTypeInfo(lambda)
Return If(info.Type.IsObjectType(), info.ConvertedType, info.Type)
Else
Return semanticModel.GetLambdaOrAnonymousMethodReturnType(lambda)
End If
End If
expression = DirectCast(node, ExpressionSyntax)
' regular case. always use ConvertedType to get implicit conversion right.
expression = expression.GetUnparenthesizedExpression()
info = semanticModel.GetTypeInfo(expression)
If info.ConvertedType IsNot Nothing AndAlso
Not info.ConvertedType.IsErrorType() Then
If expression.Kind = SyntaxKind.AddressOfExpression Then
Return info.ConvertedType
End If
Dim conversion = semanticModel.ClassifyConversion(expression, info.ConvertedType)
If conversion.IsNumeric AndAlso conversion.IsWidening Then
Return info.ConvertedType
End If
Dim conv = semanticModel.GetConversion(expression)
If IsCoClassImplicitConversion(info, conv, semanticModel.Compilation.CoClassType()) Then
Return info.ConvertedType
End If
End If
' use FormattableString if conversion between String And FormattableString
If If(info.Type?.SpecialType = SpecialType.System_String, False) AndAlso
info.ConvertedType?.IsFormattableStringOrIFormattable() Then
Return info.ConvertedType
End If
' get type without considering implicit conversion
Return If(info.Type.IsObjectType(), info.ConvertedType, info.Type)
End Function
Private Shared Function IsCoClassImplicitConversion(info As TypeInfo, conversion As Conversion, coclassSymbol As ISymbol) As Boolean
If Not conversion.IsWidening OrElse
info.ConvertedType Is Nothing OrElse
info.ConvertedType.TypeKind <> TypeKind.Interface Then
Return False
End If
' let's see whether this interface has coclass attribute
Return info.ConvertedType.GetAttributes().Any(Function(c) c.AttributeClass.Equals(coclassSymbol))
End Function
Public Overloads Function GetFirstStatement() As ExecutableStatementSyntax
Return GetFirstStatement(Of ExecutableStatementSyntax)()
End Function
Public Overloads Function GetLastStatement() As ExecutableStatementSyntax
Return GetLastStatement(Of ExecutableStatementSyntax)()
End Function
Public Function GetFirstStatementUnderContainer() As ExecutableStatementSyntax
Contract.ThrowIfTrue(SelectionInExpression)
Dim firstToken = GetFirstTokenInSelection()
Dim lastToken = GetLastTokenInSelection()
Dim commonRoot = firstToken.GetCommonRoot(lastToken)
Dim statement As ExecutableStatementSyntax
If commonRoot.IsStatementContainerNode() Then
Dim firstStatement = GetFirstStatement()
statement = firstStatement.GetAncestorsOrThis(Of ExecutableStatementSyntax) _
.SkipWhile(Function(s) s.Parent IsNot commonRoot) _
.First()
If statement.Parent.ContainStatement(statement) Then
Return statement
End If
End If
statement = commonRoot.GetStatementUnderContainer()
Contract.ThrowIfNull(statement)
Return statement
End Function
Public Function GetLastStatementUnderContainer() As ExecutableStatementSyntax
Contract.ThrowIfTrue(SelectionInExpression)
Dim firstStatement = GetFirstStatementUnderContainer()
Dim container = firstStatement.GetStatementContainer()
Dim lastStatement = Me.GetLastStatement().GetAncestorsOrThis(Of ExecutableStatementSyntax) _
.SkipWhile(Function(s) s.Parent IsNot container) _
.First()
Contract.ThrowIfNull(lastStatement)
Contract.ThrowIfFalse(lastStatement.Parent Is (GetFirstStatementUnderContainer()).Parent)
Return lastStatement
End Function
Public Function InnermostStatementContainer() As SyntaxNode
Contract.ThrowIfFalse(SelectionInExpression)
Dim containingScope = GetContainingScope()
Dim statementContainer =
containingScope.Parent _
.GetAncestorsOrThis(Of SyntaxNode)() _
.FirstOrDefault(Function(n) n.IsStatementContainerNode)
If statementContainer IsNot Nothing Then
Return statementContainer
End If
Dim field = containingScope.GetAncestor(Of FieldDeclarationSyntax)()
If field IsNot Nothing Then
Return field.Parent
End If
Dim [property] = containingScope.GetAncestor(Of PropertyStatementSyntax)()
If [property] IsNot Nothing Then
Return [property].Parent
End If
' no repl yet
' Contract.ThrowIfFalse(last.IsParentKind(SyntaxKind.GlobalStatement))
' Contract.ThrowIfFalse(last.Parent.IsParentKind(SyntaxKind.CompilationUnit))
' Return last.Parent.Parent
Throw ExceptionUtilities.Unreachable
End Function
Public Function IsUnderModuleBlock() As Boolean
Dim currentScope = GetContainingScope()
Dim types = currentScope.GetAncestors(Of TypeBlockSyntax)()
Return types.Any(Function(t) t.BlockStatement.Kind = SyntaxKind.ModuleStatement)
End Function
Public Function ContainsInstanceExpression() As Boolean
Dim first = GetFirstTokenInSelection()
Dim last = GetLastTokenInSelection()
Dim node = first.GetCommonRoot(last)
Return node.DescendantNodesAndSelf(
TextSpan.FromBounds(first.SpanStart, last.Span.End)) _
.Any(Function(n) TypeOf n Is InstanceExpressionSyntax)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Friend Class VisualBasicSelectionResult
Inherits SelectionResult
Public Shared Async Function CreateResultAsync(
status As OperationStatus,
originalSpan As TextSpan,
finalSpan As TextSpan,
options As OptionSet,
selectionInExpression As Boolean,
document As SemanticDocument,
firstToken As SyntaxToken,
lastToken As SyntaxToken,
cancellationToken As CancellationToken) As Task(Of VisualBasicSelectionResult)
Contract.ThrowIfNull(document)
Dim firstAnnotation = New SyntaxAnnotation()
Dim lastAnnotation = New SyntaxAnnotation()
Dim root = document.Root
Dim newDocument = Await SemanticDocument.CreateAsync(document.Document.WithSyntaxRoot(root.AddAnnotations(
{Tuple.Create(Of SyntaxToken, SyntaxAnnotation)(firstToken, firstAnnotation),
Tuple.Create(Of SyntaxToken, SyntaxAnnotation)(lastToken, lastAnnotation)})), cancellationToken).ConfigureAwait(False)
Return New VisualBasicSelectionResult(
status,
originalSpan,
finalSpan,
options,
selectionInExpression,
newDocument,
firstAnnotation,
lastAnnotation)
End Function
Private Sub New(
status As OperationStatus,
originalSpan As TextSpan,
finalSpan As TextSpan,
options As OptionSet,
selectionInExpression As Boolean,
document As SemanticDocument,
firstTokenAnnotation As SyntaxAnnotation,
lastTokenAnnotation As SyntaxAnnotation)
MyBase.New(
status,
originalSpan,
finalSpan,
options,
selectionInExpression,
document,
firstTokenAnnotation,
lastTokenAnnotation)
End Sub
Protected Overrides Function UnderAnonymousOrLocalMethod(token As SyntaxToken, firstToken As SyntaxToken, lastToken As SyntaxToken) As Boolean
Dim current = token.Parent
While current IsNot Nothing
If TypeOf current Is DeclarationStatementSyntax OrElse
TypeOf current Is LambdaExpressionSyntax Then
Exit While
End If
current = current.Parent
End While
If current Is Nothing OrElse TypeOf current Is DeclarationStatementSyntax Then
Return False
End If
' make sure selection contains the lambda
Return firstToken.SpanStart <= current.GetFirstToken().SpanStart AndAlso
current.GetLastToken().Span.End <= lastToken.Span.End
End Function
Public Overrides Function ContainingScopeHasAsyncKeyword() As Boolean
If SelectionInExpression Then
Return False
End If
Dim node = Me.GetContainingScope()
If TypeOf node Is MethodBlockBaseSyntax Then
Dim methodBlock = DirectCast(node, MethodBlockBaseSyntax)
If methodBlock.BlockStatement IsNot Nothing Then
Return methodBlock.BlockStatement.Modifiers.Any(SyntaxKind.AsyncKeyword)
End If
Return False
ElseIf TypeOf node Is LambdaExpressionSyntax Then
Dim lambda = DirectCast(node, LambdaExpressionSyntax)
If lambda.SubOrFunctionHeader IsNot Nothing Then
Return lambda.SubOrFunctionHeader.Modifiers.Any(SyntaxKind.AsyncKeyword)
End If
End If
Return False
End Function
Public Overrides Function GetContainingScope() As SyntaxNode
Contract.ThrowIfNull(Me.SemanticDocument)
Dim first = GetFirstTokenInSelection()
If SelectionInExpression Then
Dim last = GetLastTokenInSelection()
Dim scope = first.GetCommonRoot(last).GetAncestorOrThis(Of ExpressionSyntax)()
Contract.ThrowIfNull(scope, "Should always find an expression given that SelectionInExpression was true")
Return VisualBasicSyntaxFacts.Instance.GetRootStandaloneExpression(scope)
Else
' it contains statements
Return first.GetAncestors(Of SyntaxNode).FirstOrDefault(Function(n) TypeOf n Is MethodBlockBaseSyntax OrElse TypeOf n Is LambdaExpressionSyntax)
End If
End Function
Public Overrides Function GetContainingScopeType() As ITypeSymbol
Dim node = Me.GetContainingScope()
Dim semanticModel = Me.SemanticDocument.SemanticModel
' special case for collection initializer and explicit cast
If node.IsExpressionInCast() Then
Dim castExpression = TryCast(node.Parent, CastExpressionSyntax)
If castExpression IsNot Nothing Then
Return semanticModel.GetTypeInfo(castExpression.Type).Type
End If
End If
Dim expression As ExpressionSyntax
If TypeOf node Is CollectionInitializerSyntax Then
expression = node.GetUnparenthesizedExpression()
Return semanticModel.GetTypeInfo(expression).ConvertedType
End If
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
Dim symbol = semanticModel.GetDeclaredSymbol(methodBlock.BlockStatement)
Dim propertySymbol = TryCast(symbol, IPropertySymbol)
If propertySymbol IsNot Nothing Then
Return propertySymbol.Type
Else
Return DirectCast(symbol, IMethodSymbol).ReturnType
End If
End If
Dim info As TypeInfo
Dim lambda = TryCast(node, LambdaExpressionSyntax)
If lambda IsNot Nothing Then
If SelectionInExpression Then
info = semanticModel.GetTypeInfo(lambda)
Return If(info.Type.IsObjectType(), info.ConvertedType, info.Type)
Else
Return semanticModel.GetLambdaOrAnonymousMethodReturnType(lambda)
End If
End If
expression = DirectCast(node, ExpressionSyntax)
' regular case. always use ConvertedType to get implicit conversion right.
expression = expression.GetUnparenthesizedExpression()
info = semanticModel.GetTypeInfo(expression)
If info.ConvertedType IsNot Nothing AndAlso
Not info.ConvertedType.IsErrorType() Then
If expression.Kind = SyntaxKind.AddressOfExpression Then
Return info.ConvertedType
End If
Dim conversion = semanticModel.ClassifyConversion(expression, info.ConvertedType)
If conversion.IsNumeric AndAlso conversion.IsWidening Then
Return info.ConvertedType
End If
Dim conv = semanticModel.GetConversion(expression)
If IsCoClassImplicitConversion(info, conv, semanticModel.Compilation.CoClassType()) Then
Return info.ConvertedType
End If
End If
' use FormattableString if conversion between String And FormattableString
If If(info.Type?.SpecialType = SpecialType.System_String, False) AndAlso
info.ConvertedType?.IsFormattableStringOrIFormattable() Then
Return info.ConvertedType
End If
' get type without considering implicit conversion
Return If(info.Type.IsObjectType(), info.ConvertedType, info.Type)
End Function
Private Shared Function IsCoClassImplicitConversion(info As TypeInfo, conversion As Conversion, coclassSymbol As ISymbol) As Boolean
If Not conversion.IsWidening OrElse
info.ConvertedType Is Nothing OrElse
info.ConvertedType.TypeKind <> TypeKind.Interface Then
Return False
End If
' let's see whether this interface has coclass attribute
Return info.ConvertedType.GetAttributes().Any(Function(c) c.AttributeClass.Equals(coclassSymbol))
End Function
Public Overloads Function GetFirstStatement() As ExecutableStatementSyntax
Return GetFirstStatement(Of ExecutableStatementSyntax)()
End Function
Public Overloads Function GetLastStatement() As ExecutableStatementSyntax
Return GetLastStatement(Of ExecutableStatementSyntax)()
End Function
Public Function GetFirstStatementUnderContainer() As ExecutableStatementSyntax
Contract.ThrowIfTrue(SelectionInExpression)
Dim firstToken = GetFirstTokenInSelection()
Dim lastToken = GetLastTokenInSelection()
Dim commonRoot = firstToken.GetCommonRoot(lastToken)
Dim statement As ExecutableStatementSyntax
If commonRoot.IsStatementContainerNode() Then
Dim firstStatement = GetFirstStatement()
statement = firstStatement.GetAncestorsOrThis(Of ExecutableStatementSyntax) _
.SkipWhile(Function(s) s.Parent IsNot commonRoot) _
.First()
If statement.Parent.ContainStatement(statement) Then
Return statement
End If
End If
statement = commonRoot.GetStatementUnderContainer()
Contract.ThrowIfNull(statement)
Return statement
End Function
Public Function GetLastStatementUnderContainer() As ExecutableStatementSyntax
Contract.ThrowIfTrue(SelectionInExpression)
Dim firstStatement = GetFirstStatementUnderContainer()
Dim container = firstStatement.GetStatementContainer()
Dim lastStatement = Me.GetLastStatement().GetAncestorsOrThis(Of ExecutableStatementSyntax) _
.SkipWhile(Function(s) s.Parent IsNot container) _
.First()
Contract.ThrowIfNull(lastStatement)
Contract.ThrowIfFalse(lastStatement.Parent Is (GetFirstStatementUnderContainer()).Parent)
Return lastStatement
End Function
Public Function InnermostStatementContainer() As SyntaxNode
Contract.ThrowIfFalse(SelectionInExpression)
Dim containingScope = GetContainingScope()
Dim statementContainer =
containingScope.Parent _
.GetAncestorsOrThis(Of SyntaxNode)() _
.FirstOrDefault(Function(n) n.IsStatementContainerNode)
If statementContainer IsNot Nothing Then
Return statementContainer
End If
Dim field = containingScope.GetAncestor(Of FieldDeclarationSyntax)()
If field IsNot Nothing Then
Return field.Parent
End If
Dim [property] = containingScope.GetAncestor(Of PropertyStatementSyntax)()
If [property] IsNot Nothing Then
Return [property].Parent
End If
' no repl yet
' Contract.ThrowIfFalse(last.IsParentKind(SyntaxKind.GlobalStatement))
' Contract.ThrowIfFalse(last.Parent.IsParentKind(SyntaxKind.CompilationUnit))
' Return last.Parent.Parent
Throw ExceptionUtilities.Unreachable
End Function
Public Function IsUnderModuleBlock() As Boolean
Dim currentScope = GetContainingScope()
Dim types = currentScope.GetAncestors(Of TypeBlockSyntax)()
Return types.Any(Function(t) t.BlockStatement.Kind = SyntaxKind.ModuleStatement)
End Function
Public Function ContainsInstanceExpression() As Boolean
Dim first = GetFirstTokenInSelection()
Dim last = GetLastTokenInSelection()
Dim node = first.GetCommonRoot(last)
Return node.DescendantNodesAndSelf(
TextSpan.FromBounds(first.SpanStart, last.Span.End)) _
.Any(Function(n) TypeOf n Is InstanceExpressionSyntax)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IDelegateCreationExpression.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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
#Region "Lambda Expressions"
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = Sub() Console.WriteLine("")'BIND:"Dim a As Action = Sub() Console.WriteLine("")"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... iteLine("")')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... iteLine("")')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Sub() Con ... iteLine("")')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "") (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_JustInitializerReturnsOnlyLambda()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = Sub() Console.WriteLine("")'BIND:"Sub() Console.WriteLine("")"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "") (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of SingleLineLambdaExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = Sub(i As Integer) Console.WriteLine("")'BIND:"Dim a As Action = Sub(i As Integer) Console.WriteLine("")"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... iteLine("")')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... iteLine("")')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Sub(i As ... iteLine("")')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... iteLine("")')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action'.
Dim a As Action = Sub(i As Integer) Console.WriteLine("")'BIND:"Dim a As Action = Sub(i As Integer) Console.WriteLine("")"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = Sub(c1 As C1) Console.WriteLine("")'BIND:"Dim a As Action(Of String) = Sub(c1 As C1) Console.WriteLine("")"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... iteLine("")')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... iteLine("")')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Sub(c1 As ... iteLine("")')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = Sub(c1 As C1) Console.WriteLine("")'BIND:"Dim a As Action(Of String) = Sub(c1 As C1) Console.WriteLine("")"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_InvalidReturnType()
Dim source = <![CDATA[
Option Strict Off
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = Function() New NonExistant()'BIND:"Dim a As Func(Of String) = Function() New NonExistant()"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Fu ... nExistant()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Func(O ... nExistant()')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Func(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Function( ... nExistant()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of String) = Function() New NonExistant()'BIND:"Dim a As Func(Of String) = Function() New NonExistant()"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = Function() 1'BIND:"Dim a As Func(Of String) = Function() 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Fu ... unction() 1')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Func(O ... unction() 1')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Func(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Function() 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim a As Func(Of String) = Function() 1'BIND:"Dim a As Func(Of String) = Function() 1"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = Function() 1'BIND:"Dim a As Action = Function() 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... unction() 1')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... unction() 1')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Function() 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'Function() 1')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Int32) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Int32
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaExpression_RelaxationOfArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action(Of String) = Sub(o As Object) Console.WriteLine(o)'BIND:"Dim a As Action(Of String) = Sub(o As Object) Console.WriteLine(o)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... riteLine(o)')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... riteLine(o)')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Sub(o As ... riteLine(o)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsImplicit) (Syntax: 'Sub(o As Ob ... riteLine(o)')
Target:
IAnonymousFunctionOperation (Symbol: Sub (o As System.Object)) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub(o As Ob ... riteLine(o)')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub(o As Ob ... riteLine(o)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(o)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(o)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'o')
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
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)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub(o As Ob ... riteLine(o)')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub(o As Ob ... riteLine(o)')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Action = CType(Sub() Console.WriteLine(), Action)'BIND:"CType(Sub() Console.WriteLine(), Action)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Sub() ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Action = CType(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"CType(Sub(i As Integer) Console.WriteLine(), Action)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'CType(Sub(i ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action'.
Dim a As Action = CType(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"CType(Sub(i As Integer) Console.WriteLine(), Action)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = CType(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"CType(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'CType(Sub(c ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = CType(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"CType(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Func(Of String) = CType(Function() 1, Func(Of String))'BIND:"CType(Function() 1, Func(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(Funct ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim a As Func(Of String) = CType(Function() 1, Func(Of String))'BIND:"CType(Function() 1, Func(Of String))"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_InvalidReturnType()
Dim source = <![CDATA[
Option Strict Off
Imports System
Module M1
Sub Main()
Dim a As Func(Of String) = CType(Function() New NonExistant(), Func(Of String)) 'BIND:"CType(Function() New NonExistant(), Func(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(Funct ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of String) = CType(Function() New NonExistant(), Func(Of String)) 'BIND:"CType(Function() New NonExistant(), Func(Of String))"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of Object) = CType(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))'BIND:"Dim a As Action(Of Object) = CType(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... f Integer))')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... f Integer))')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.Object)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= CType(Sub ... f Integer))')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action(Of System.Object), IsInvalid, IsImplicit) (Syntax: 'CType(Sub(i ... f Integer))')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsInvalid) (Syntax: 'CType(Sub(i ... f Integer))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36755: 'Action(Of Integer)' cannot be converted to 'Action(Of Object)' because 'Object' is not derived from 'Integer', as required for the 'In' generic parameter 'T' in 'Delegate Sub Action(Of In T)(obj As T)'.
Dim a As Action(Of Object) = CType(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))'BIND:"Dim a As Action(Of Object) = CType(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Func(Of Object) = CType(Function() 1, Func(Of Object))'BIND:"CType(Function() 1, Func(Of Object))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object)) (Syntax: 'CType(Funct ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Object) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Object
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Action(Of Object) = CType(Sub() Console.WriteLine(), Action(Of Object))'BIND:"CType(Sub() Console.WriteLine(), Action(Of Object))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Object)) (Syntax: 'CType(Sub() ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeMethodBinding()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = CType(AddressOf M1, Action)'BIND:"CType(AddressOf M1, Action)"
End Sub
Sub M1()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Addre ... M1, Action)')
Target:
IMethodReferenceOperation: Sub Program.M1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeMethodBinding_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of Object) = CType(AddressOf M1, Action(Of Integer))'BIND:"Dim a As Action(Of Object) = CType(AddressOf M1, Action(Of Integer))"
End Sub
Sub M1(i As Integer)
End Sub
End Module
]]>.Value
' Explicitly verifying the entire tree here to ensure that the top level initializer statement is actually an IConversion, and not
' a delegate creation
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... f Integer))')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... f Integer))')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.Object)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= CType(Add ... f Integer))')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action(Of System.Object), IsInvalid, IsImplicit) (Syntax: 'CType(Addre ... f Integer))')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsInvalid) (Syntax: 'CType(Addre ... f Integer))')
Target:
IMethodReferenceOperation: Sub Program.M1(i As System.Int32) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36755: 'Action(Of Integer)' cannot be converted to 'Action(Of Object)' because 'Object' is not derived from 'Integer', as required for the 'In' generic parameter 'T' in 'Delegate Sub Action(Of In T)(obj As T)'.
Dim a As Action(Of Object) = CType(AddressOf M1, Action(Of Integer))'BIND:"Dim a As Action(Of Object) = CType(AddressOf M1, Action(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = DirectCast(Sub() Console.WriteLine(), Action)'BIND:"DirectCast(Sub() Console.WriteLine(), Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = DirectCast(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"DirectCast(Sub(i As Integer) Console.WriteLine(), Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'DirectCast( ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action'.
Dim a As Action = DirectCast(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"DirectCast(Sub(i As Integer) Console.WriteLine(), Action)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = DirectCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"DirectCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = DirectCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"DirectCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of String) = DirectCast(Function() 1, Func(Of String))'BIND:"DirectCast(Function() 1, Func(Of String))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim a As Func(Of String) = DirectCast(Function() 1, Func(Of String))'BIND:"DirectCast(Function() 1, Func(Of String))"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_InvalidReturnType()
Dim source = <![CDATA[
Option Strict Off
Imports System
Module Program
Sub Main()
Dim a As Func(Of String) = DirectCast(Function() New NonExistant(), Func(Of String)) 'BIND:"DirectCast(Function() New NonExistant(), Func(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of String) = DirectCast(Function() New NonExistant(), Func(Of String)) 'BIND:"DirectCast(Function() New NonExistant(), Func(Of String))"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of String) = DirectCast(Function() 1, Func(Of Integer))'BIND:"DirectCast(Function() 1, Func(Of Integer))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsInvalid) (Syntax: 'DirectCast( ... f Integer))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Int32
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36754: 'Func(Of Integer)' cannot be converted to 'Func(Of String)' because 'Integer' is not derived from 'String', as required for the 'Out' generic parameter 'TResult' in 'Delegate Function Func(Of Out TResult)() As TResult'.
Dim a As Func(Of String) = DirectCast(Function() 1, Func(Of Integer))'BIND:"DirectCast(Function() 1, Func(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of Object) = DirectCast(Function() 1, Func(Of Object))'BIND:"DirectCast(Function() 1, Func(Of Object))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object)) (Syntax: 'DirectCast( ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Object) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Object
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of Object) = DirectCast(Sub() Console.WriteLine(), Action(Of Object))'BIND:"DirectCast(Sub() Console.WriteLine(), Action(Of Object))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Object)) (Syntax: 'DirectCast( ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = TryCast(Sub() Console.WriteLine(), Action)'BIND:"TryCast(Sub() Console.WriteLine(), Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Sub ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = TryCast(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"TryCast(Sub(i As Integer) Console.WriteLine(), Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'TryCast(Sub ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action'.
Dim a As Action = TryCast(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"TryCast(Sub(i As Integer) Console.WriteLine(), Action)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = TryCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"TryCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'TryCast(Sub ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = TryCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"TryCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of Object) = TryCast(Sub() Console.WriteLine(), Func(Of Object))'BIND:"TryCast(Sub() Console.WriteLine(), Func(Of Object))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'TryCast(Sub ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of Object)'.
Dim a As Func(Of Object) = TryCast(Sub() Console.WriteLine(), Func(Of Object))'BIND:"TryCast(Sub() Console.WriteLine(), Func(Of Object))"
~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of Object) = TryCast(Function() New NonExistant(), Func(Of Object)) 'BIND:"TryCast(Function() New NonExistant(), Func(Of Object))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'TryCast(Fun ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Object) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.Object
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of Object) = TryCast(Function() New NonExistant(), Func(Of Object)) 'BIND:"TryCast(Function() New NonExistant(), Func(Of Object))"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of String) = TryCast(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))'BIND:"TryCast(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsInvalid) (Syntax: 'TryCast(Sub ... f Integer))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36755: 'Action(Of Integer)' cannot be converted to 'Action(Of String)' because 'String' is not derived from 'Integer', as required for the 'In' generic parameter 'T' in 'Delegate Sub Action(Of In T)(obj As T)'.
Dim a As Action(Of String) = TryCast(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))'BIND:"TryCast(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of Object) = TryCast(Sub() Console.WriteLine(), Action(Of Object))'BIND:"TryCast(Sub() Console.WriteLine(), Action(Of Object))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Object)) (Syntax: 'TryCast(Sub ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = TryCast(Function() 1, Action)'BIND:"TryCast(Function() 1, Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Fun ... 1, Action)')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Int32) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Int32
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(Sub() Console.WriteLine())'BIND:"New Action(Sub() Console.WriteLine())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... riteLine())')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_MultipleArgumentsToConstructor()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(Sub() Console.WriteLine(), 1)'BIND:"Dim a As Action = New Action(Sub() Console.WriteLine(), 1)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... eLine(), 1)')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... eLine(), 1)')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New Actio ... eLine(), 1)')
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'New Action( ... eLine(), 1)')
Children(2):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32008: Delegate 'Action' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.
Dim a As Action = New Action(Sub() Console.WriteLine(), 1)'BIND:"Dim a As Action = New Action(Sub() Console.WriteLine(), 1)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action(Of String) = New Action(Of String)(Sub() Console.WriteLine())'BIND:"New Action(Of String)(Sub() Console.WriteLine())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String)) (Syntax: 'New Action( ... riteLine())')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(Function() 1)'BIND:"New Action(Function() 1)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action(Function() 1)')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Int32) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Int32
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action(Of Object) = New Action(Of Object)(Sub(i As Integer) Console.WriteLine())'BIND:"New Action(Of Object)(Sub(i As Integer) Console.WriteLine())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Object), IsInvalid) (Syntax: 'New Action( ... riteLine())')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'.
Dim a As Action(Of Object) = New Action(Of Object)(Sub(i As Integer) Console.WriteLine())'BIND:"New Action(Of Object)(Sub(i As Integer) Console.WriteLine())"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = New Action(Of String)(Sub(c1 As C1) Console.WriteLine(""))'BIND:"New Action(Of String)(Sub(c1 As C1) Console.WriteLine(""))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'New Action( ... teLine(""))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = New Action(Of String)(Sub(c1 As C1) Console.WriteLine(""))'BIND:"New Action(Of String)(Sub(c1 As C1) Console.WriteLine(""))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of Object) = New Func(Of Object)(Sub() Console.WriteLine())'BIND:"New Func(Of Object)(Sub() Console.WriteLine())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'New Func(Of ... riteLine())')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of Object)'.
Dim a As Func(Of Object) = New Func(Of Object)(Sub() Console.WriteLine())'BIND:"New Func(Of Object)(Sub() Console.WriteLine())"
~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of Object) = New Func(Of Object)(Function() New NonExistant())'BIND:"New Func(Of Object)(Function() New NonExistant())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'New Func(Of ... Existant())')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Object) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.Object
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of Object) = New Func(Of Object)(Function() New NonExistant())'BIND:"New Func(Of Object)(Function() New NonExistant())"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((Sub() Console.WriteLine())), Action)'BIND:"CType(((Sub() Console.WriteLine())), Action)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(((Sub ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_Multiline()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((Sub()'BIND:"CType(((Sub()"
End Sub)), Action)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(((Sub ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_Implicit()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a As Action = ((Sub() Console.WriteLine()))'BIND:"= ((Sub() Console.WriteLine()))"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ((Sub() C ... iteLine()))')
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_InvalidMissingParameter()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((Sub()'BIND:"CType(((Sub()"
End Sub)), Action(Of String))
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'CType(((Sub ... Of String))')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'obj' of 'Action(Of String)'.
CType(((Sub()'BIND:"CType(((Sub()"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_InvalidConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((Sub()'BIND:"CType(((Sub()"
End Sub)), Func(Of String))
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(((Sub ... Of String))')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of String)'.
CType(((Sub()'BIND:"CType(((Sub()"
~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_NonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = CType(((Sub() Console.WriteLine())), Object)'BIND:"CType(((Sub() Console.WriteLine())), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'CType(((Sub ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_NestedCTypeNonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = CType(((CType(Sub() Console.WriteLine(), Action))), Object)'BIND:"CType(((CType(Sub() Console.WriteLine(), Action))), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'CType(((CTy ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((CType(Sub ... , Action)))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(CType(Sub( ... ), Action))')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Sub() ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_DirectCast_NonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = DirectCast(((Sub() Console.WriteLine())), Object)'BIND:"DirectCast(((Sub() Console.WriteLine())), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'DirectCast( ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_DirectCast_NestedDirectCastNonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = DirectCast(((DirectCast(Sub() Console.WriteLine(), Action))), Object)'BIND:"DirectCast(((DirectCast(Sub() Console.WriteLine(), Action))), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'DirectCast( ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((DirectCas ... , Action)))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(DirectCast ... ), Action))')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_TryCast_NonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = TryCast(((Sub() Console.WriteLine())), Object)'BIND:"TryCast(((Sub() Console.WriteLine())), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'TryCast(((S ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_TryCast_NestedTryCastNonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = TryCast(((TryCast(Sub() Console.WriteLine(), Action))), Object)'BIND:"TryCast(((TryCast(Sub() Console.WriteLine(), Action))), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'TryCast(((T ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((TryCast(S ... , Action)))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(TryCast(Su ... ), Action))')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Sub ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_Implicit_NonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a As Object = ((Sub() Console.WriteLine()))'BIND:"= ((Sub() Console.WriteLine()))"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ((Sub() C ... iteLine()))')
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Object) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Object) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_InvalidNonDelegateTargetType_InvalidConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = CType(((Sub() Console.WriteLine())), String)'BIND:"CType(((Sub() Console.WriteLine())), String)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid) (Syntax: 'CType(((Sub ... )), String)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36625: Lambda expression cannot be converted to 'String' because 'String' is not a delegate type.
Dim a = CType(((Sub() Console.WriteLine())), String)'BIND:"CType(((Sub() Console.WriteLine())), String)"
~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_DirectCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
DirectCast(((Sub()'BIND:"DirectCast(((Sub()"
End Sub)), Action)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_TryCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
TryCast(((Sub()'BIND:"TryCast(((Sub()"
End Sub)), Action)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(((S ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
#End Region
#Region "AddressOf"
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = AddressOf Method2'BIND:"Dim a As Action = AddressOf Method2"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_JustInitializerReturnsOnlyMethodReference()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = AddressOf Method2'BIND:"AddressOf Method2"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_WithReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = AddressOf o.ToString'BIND:"Dim a As Action = AddressOf o.ToString"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... o.ToString')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... o.ToString')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= AddressOf o.ToString')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf o.ToString')
Target:
IMethodReferenceOperation: Function System.Object.ToString() As System.String (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf o.ToString')
Instance Receiver:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = AddressOf Method2'BIND:"Dim a As Action = AddressOf Method2"
End Sub
Sub Method2(i As Integer)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action = AddressOf Method2'BIND:"Dim a As Action = AddressOf Method2"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = AddressOf Method2'BIND:"Dim a As Action(Of String) = AddressOf Method2"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = AddressOf Method2'BIND:"Dim a As Action(Of String) = AddressOf Method2"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = AddressOf Method2 'BIND:"Dim a As Func(Of String) = AddressOf Method2"
End Sub
Function Method2() As Integer
Return 1
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Fu ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Func(O ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Func(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IMethodReferenceOperation: Function M1.Method2() As System.Int32 (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36663: Option Strict On does not allow narrowing in implicit type conversions between method 'Public Function Method2() As Integer' and delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = AddressOf Method2 'BIND:"Dim a As Func(Of String) = AddressOf Method2"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = AddressOf Method2 'BIND:"Dim a As Func(Of String) = AddressOf Method2"
End Sub
Function Method2() As NonExistant
Return New NonExistant
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Fu ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Func(O ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Func(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Function Method2() As NonExistant' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = AddressOf Method2 'BIND:"Dim a As Func(Of String) = AddressOf Method2"
~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Function Method2() As NonExistant
~~~~~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Return New NonExistant
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = AddressOf Method2 'BIND:"Dim a As Action = AddressOf Method2"
End Sub
Function Method2() As Object
Return 1
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IMethodReferenceOperation: Function M1.Method2() As System.Object (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict Off
Imports System
Module M1
Sub Method1()
Dim a As Action(Of Integer) = AddressOf Method2'BIND:"Dim a As Action(Of Integer) = AddressOf Method2"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_ConvertedToNonDelegateType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As String = AddressOf Method2'BIND:"Dim a As String = AddressOf Method2"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
' We don't expect a delegate creation here. This is documenting that we still have a conversion expression when the target type
' isn't a delegate type
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As St ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As String ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30581: 'AddressOf' expression cannot be converted to 'String' because 'String' is not a delegate type.
Dim a As String = AddressOf Method2'BIND:"Dim a As String = AddressOf Method2"
~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim a As Action = CType(AddressOf M1, Action)'BIND:"CType(AddressOf M1, Action)"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Addre ... M1, Action)')
Target:
IMethodReferenceOperation: Sub Program.M1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_WithReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = CType(AddressOf o.ToString, Action)'BIND:"CType(AddressOf o.ToString, Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Addre ... ng, Action)')
Target:
IMethodReferenceOperation: Function System.Object.ToString() As System.String (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf o.ToString')
Instance Receiver:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = CType(AddressOf M2, Action)'BIND:"CType(AddressOf M2, Action)"
End Sub
Sub M2(i As Integer)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'CType(Addre ... M2, Action)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action = CType(AddressOf M2, Action)'BIND:"CType(AddressOf M2, Action)"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = CType(AddressOf Method2, Action(Of String))'BIND:"CType(AddressOf Method2, Action(Of String))"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'CType(Addre ... Of String))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = CType(AddressOf Method2, Action(Of String))'BIND:"CType(AddressOf Method2, Action(Of String))"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_InvalidReturnConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of String) = CType(AddressOf M2, Func(Of String))'BIND:"CType(AddressOf M2, Func(Of String))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(Addre ... Of String))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2()' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = CType(AddressOf M2, Func(Of String))'BIND:"CType(AddressOf M2, Func(Of String))"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action(Of String) = CType(AddressOf M2, Action(Of Integer))'BIND:"CType(AddressOf M2, Action(Of Integer))"
End Sub
Sub M2(i As Integer)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsInvalid) (Syntax: 'CType(Addre ... f Integer))')
Target:
IMethodReferenceOperation: Sub Program.M2(i As System.Int32) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36755: 'Action(Of Integer)' cannot be converted to 'Action(Of String)' because 'String' is not derived from 'Integer', as required for the 'In' generic parameter 'T' in 'Delegate Sub Action(Of In T)(obj As T)'.
Dim a As Action(Of String) = CType(AddressOf M2, Action(Of Integer))'BIND:"CType(AddressOf M2, Action(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = CType(AddressOf M2, Action)'BIND:"CType(AddressOf M2, Action)"
End Sub
Function M2() As Integer
Return 1
End Function
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Addre ... M2, Action)')
Target:
IMethodReferenceOperation: Function Program.M2() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action(Of String) = CType(AddressOf M2, Action(Of String))'BIND:"CType(AddressOf M2, Action(Of String))"
End Sub
Sub M2(o As Object)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String)) (Syntax: 'CType(Addre ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2(o As System.Object) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf M2, Action)'BIND:"DirectCast(AddressOf M2, Action)"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... M2, Action)')
Target:
IMethodReferenceOperation: Sub Program.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_WithReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf o.ToString, Action)'BIND:"DirectCast(AddressOf o.ToString, Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... ng, Action)')
Target:
IMethodReferenceOperation: Function System.Object.ToString() As System.String (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf o.ToString')
Instance Receiver:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of Object) = DirectCast(AddressOf M2, Func(Of Object))'BIND:"DirectCast(AddressOf M2, Func(Of Object))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'DirectCast( ... Of Object))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2()' does not have a signature compatible with delegate 'Delegate Function Func(Of Object)() As Object'.
Dim a As Func(Of Object) = DirectCast(AddressOf M2, Func(Of Object))'BIND:"DirectCast(AddressOf M2, Func(Of Object))"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of Object) = DirectCast(AddressOf M2, Func(Of Object))'BIND:"DirectCast(AddressOf M2, Func(Of Object))"
End Sub
Function M2() As NonExistant
Return New NonExistant
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'DirectCast( ... Of Object))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Function M2() As NonExistant' does not have a signature compatible with delegate 'Delegate Function Func(Of Object)() As Object'.
Dim a As Func(Of Object) = DirectCast(AddressOf M2, Func(Of Object))'BIND:"DirectCast(AddressOf M2, Func(Of Object))"
~~
BC30002: Type 'NonExistant' is not defined.
Function M2() As NonExistant
~~~~~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Return New NonExistant
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf M2, Action)'BIND:"DirectCast(AddressOf M2, Action)"
End Sub
Sub M2(s As Integer)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'DirectCast( ... M2, Action)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2(s As Integer)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action = DirectCast(AddressOf M2, Action)'BIND:"DirectCast(AddressOf M2, Action)"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = DirectCast(AddressOf Method2, Action(Of String))'BIND:"DirectCast(AddressOf Method2, Action(Of String))"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = DirectCast(AddressOf Method2, Action(Of String))'BIND:"DirectCast(AddressOf Method2, Action(Of String))"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf M2, Action(Of String))'BIND:"DirectCast(AddressOf M2, Action(Of String))"
End Sub
Sub M2(s As String)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2(s As System.String) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'Action(Of String)' cannot be converted to 'Action'.
Dim a As Action = DirectCast(AddressOf M2, Action(Of String))'BIND:"DirectCast(AddressOf M2, Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action(Of String) = DirectCast(AddressOf M2, Action(Of String))'BIND:"DirectCast(AddressOf M2, Action(Of String))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String)) (Syntax: 'DirectCast( ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf M2, Action)'BIND:"DirectCast(AddressOf M2, Action)"
End Sub
Function M2() As Integer
Return 1
End Function
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... M2, Action)')
Target:
IMethodReferenceOperation: Function Program.M2() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf M2, Action)'BIND:"TryCast(AddressOf M2, Action)"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Add ... M2, Action)')
Target:
IMethodReferenceOperation: Sub Program.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_WithReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf o.ToString, Action)'BIND:"TryCast(AddressOf o.ToString, Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Add ... ng, Action)')
Target:
IMethodReferenceOperation: Function System.Object.ToString() As System.String (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf o.ToString')
Instance Receiver:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of Object) = TryCast(AddressOf M2, Func(Of Object))'BIND:"TryCast(AddressOf M2, Func(Of Object))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'TryCast(Add ... Of Object))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2()' does not have a signature compatible with delegate 'Delegate Function Func(Of Object)() As Object'.
Dim a As Func(Of Object) = TryCast(AddressOf M2, Func(Of Object))'BIND:"TryCast(AddressOf M2, Func(Of Object))"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of Object) = TryCast(AddressOf M2, Func(Of Object))'BIND:"TryCast(AddressOf M2, Func(Of Object))"
End Sub
Function M2() As NonExistant
Return NonExistant
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'TryCast(Add ... Of Object))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Function M2() As NonExistant' does not have a signature compatible with delegate 'Delegate Function Func(Of Object)() As Object'.
Dim a As Func(Of Object) = TryCast(AddressOf M2, Func(Of Object))'BIND:"TryCast(AddressOf M2, Func(Of Object))"
~~
BC30002: Type 'NonExistant' is not defined.
Function M2() As NonExistant
~~~~~~~~~~~
BC30451: 'NonExistant' is not declared. It may be inaccessible due to its protection level.
Return NonExistant
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf M2, Action)'BIND:"TryCast(AddressOf M2, Action)"
End Sub
Sub M2(s As Integer)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'TryCast(Add ... M2, Action)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2(s As Integer)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action = TryCast(AddressOf M2, Action)'BIND:"TryCast(AddressOf M2, Action)"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = TryCast(AddressOf Method2, Action(Of String))'BIND:"TryCast(AddressOf Method2, Action(Of String))"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'TryCast(Add ... Of String))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = TryCast(AddressOf Method2, Action(Of String))'BIND:"TryCast(AddressOf Method2, Action(Of String))"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf M2, Action(Of String))'BIND:"TryCast(AddressOf M2, Action(Of String))"
End Sub
Sub M2(s As String)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'TryCast(Add ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2(s As System.String) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'Action(Of String)' cannot be converted to 'Action'.
Dim a As Action = TryCast(AddressOf M2, Action(Of String))'BIND:"TryCast(AddressOf M2, Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action(Of String) = TryCast(AddressOf M2, Action(Of String))'BIND:"TryCast(AddressOf M2, Action(Of String))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String)) (Syntax: 'TryCast(Add ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf M2, Action)'BIND:"TryCast(AddressOf M2, Action)"
End Sub
Function M2() As Integer
Return 1
End Function
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Add ... M2, Action)')
Target:
IMethodReferenceOperation: Function Program.M2() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
<WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... Of Method2)')
Target:
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
<WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")>
Public Sub DelegateCreationExpression_DelegateCreationInstanceAddressOfArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Class M1
Sub Method1()
Dim a As Action = New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
End Sub
Sub Method2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... Of Method2)')
Target:
IMethodReferenceOperation: Sub M1.Method2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
<WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")>
Public Sub DelegateCreationExpression_DelegateCreationSharedAddressOfArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Class M1
Sub Method1()
Dim a As Action = New Action(AddressOf Me.Method2)'BIND:"New Action(AddressOf Me.Method2)"
End Sub
Shared Sub Method2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... Me.Method2)')
Target:
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Me.Method2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1) (Syntax: 'Me')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Dim a As Action = New Action(AddressOf Me.Method2)'BIND:"New Action(AddressOf Me.Method2)"
~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_MultipleArgumentsToConstructor()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(AddressOf Method2, 1)'BIND:"Dim a As Action = New Action(AddressOf Method2, 1)"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... Method2, 1)')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... Method2, 1)')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New Actio ... Method2, 1)')
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'New Action( ... Method2, 1)')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32008: Delegate 'Action' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.
Dim a As Action = New Action(AddressOf Method2, 1)'BIND:"Dim a As Action = New Action(AddressOf Method2, 1)"
~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
End Sub
Function Method2() As Object
Return 1
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... Of Method2)')
Target:
IMethodReferenceOperation: Function M1.Method2() As System.Object (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action(Of Integer) = New Action(Of Integer)(AddressOf Method2)'BIND:"New Action(Of Integer)(AddressOf Method2)"
End Sub
Sub Method2(o As Object)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32)) (Syntax: 'New Action( ... Of Method2)')
Target:
IMethodReferenceOperation: Sub M1.Method2(o As System.Object) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action= New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
End Sub
Sub Method2(o As Object)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'New Action( ... Of Method2)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(o As Object)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action= New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = New Action(Of String)(AddressOf Method2)'BIND:"New Action(Of String)(AddressOf Method2)"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'New Action( ... Of Method2)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = New Action(Of String)(AddressOf Method2)'BIND:"New Action(Of String)(AddressOf Method2)"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = New Func(Of String)(AddressOf Method2)'BIND:"New Func(Of String)(AddressOf Method2)"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'New Func(Of ... Of Method2)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2()' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = New Func(Of String)(AddressOf Method2)'BIND:"New Func(Of String)(AddressOf Method2)"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = New Func(Of String)(AddressOf Method2)'BIND:"New Func(Of String)(AddressOf Method2)"
End Sub
Function Method2() As NonExistant
Return New NonExistant()
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'New Func(Of ... Of Method2)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Function Method2() As NonExistant' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = New Func(Of String)(AddressOf Method2)'BIND:"New Func(Of String)(AddressOf Method2)"
~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Function Method2() As NonExistant
~~~~~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Return New NonExistant()
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IDelegateCreation_SharedAddressOfWithInstanceReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Shared Sub S1()
End Sub
Shared Sub S2()
Dim c1Instance As New C1
Dim a As Action = AddressOf c1Instance.S1'BIND:"AddressOf c1Instance.S1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IMethodReferenceOperation: Sub M1.C1.S1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf c1Instance.S1')
Instance Receiver:
ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Dim a As Action = AddressOf c1Instance.S1'BIND:"AddressOf c1Instance.S1"
~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IDelegateCreation_SharedAddressOfAccessOnClass()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Shared Sub S1()
End Sub
Shared Sub S2()
Dim a As Action = AddressOf C1.S1'BIND:"AddressOf C1.S1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IMethodReferenceOperation: Sub M1.C1.S1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf C1.S1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IDelegateCreation_InstanceAddressOfAccessOnClass()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Sub S1()
End Sub
Shared Sub S2()
Dim a As Action = AddressOf C1.S1'BIND:"AddressOf C1.S1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf C1.S1')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'C1.S1')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'C1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30469: Reference to a non-shared member requires an object reference.
Dim a As Action = AddressOf C1.S1'BIND:"AddressOf C1.S1"
~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Action)'BIND:"CType(((AddressOf M2)), Action)"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(((Add ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(AddressOf M2)')
Operand:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_Implicit()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a As Action = ((AddressOf M2))'BIND:"= ((AddressOf M2))"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ((AddressOf M2))')
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(AddressOf M2)')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf M2')
Target:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType_InvalidMethod()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Action)'BIND:"CType(((AddressOf M2)), Action)"
End Sub
Public Sub M2(o As Object)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'CType(((Add ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(AddressOf M2)')
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2(o As Object)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
CType(((AddressOf M2)), Action)'BIND:"CType(((AddressOf M2)), Action)"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType_InvalidMissingParameter()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Action(Of String))'BIND:"CType(((AddressOf M2)), Action(Of String))"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'CType(((Add ... Of String))')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(AddressOf M2)')
Operand:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'obj' of 'Action(Of String)'.
CType(((AddressOf M2)), Action(Of String))'BIND:"CType(((AddressOf M2)), Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType_InvalidCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Func(Of String)) 'BIND:"CType(((AddressOf M2)), Func(Of String))"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(((Add ... Of String))')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(AddressOf M2)')
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2()' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
CType(((AddressOf M2)), Func(Of String)) 'BIND:"CType(((AddressOf M2)), Func(Of String))"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType_InvalidNonDelegateTargetType()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Object)'BIND:"CType(((AddressOf M2)), Object)"
End Sub
Public Sub M2(o As Object)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid) (Syntax: 'CType(((Add ... )), Object)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(AddressOf M2)')
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type.
CType(((AddressOf M2)), Object)'BIND:"CType(((AddressOf M2)), Object)"
~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_DirectCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
DirectCast(((AddressOf M2)), Action)'BIND:"DirectCast(((AddressOf M2)), Action)"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(AddressOf M2)')
Operand:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_TryCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
TryCast(((AddressOf M2)), Action)'BIND:"TryCast(((AddressOf M2)), Action)"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(((A ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(AddressOf M2)')
Operand:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
#End Region
#Region "Anonymous Delegates"
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAnonymousDelegateConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a = Sub()'BIND:"Dim a = Sub()"
End Sub
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a = Sub ... End Sub')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a = Sub()'B ... End Sub')
Declarators:
IVariableDeclaratorOperation (Symbol: a As Sub <generated method>()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Sub()'BIN ... End Sub')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAnonymousDelegateConversion_JustInitializerReturnsOnlyLambda()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a = Sub()'BIND:"Sub()"
End Sub
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of MultiLineLambdaExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAnonymousDelegateConversion_SingleLineLambda()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a = Sub() Console.WriteLine()'BIND:"Dim a = Sub() Console.WriteLine()"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a = Sub ... WriteLine()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a = Sub() C ... WriteLine()')
Declarators:
IVariableDeclaratorOperation (Symbol: a As Sub <generated method>()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Sub() Con ... WriteLine()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
#End Region
#Region "Control Flow"
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub DelegateCreation_NoControlFlow()
Dim source = <![CDATA[
Imports System
Class C
Private Sub M(a1 As Action, a2 As Action, a3 As Action, a4 As Action) 'BIND:"Private Sub M(a1 As Action, a2 As Action, a3 As Action, a4 As Action)"
a1 = Sub()
End Sub
a2 = AddressOf M2
a3 = New Action(AddressOf M3)
End Sub
Private Sub M2()
End Sub
Private Shared Sub M3()
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = Sub() ... End Sub')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'a1 = Sub() ... End Sub')
Left:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'Sub() ... End Sub')
Target:
IFlowAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: 'Sub() ... End Sub')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Exit
Predecessors: [B0#A0]
Statements (0)
}
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a2 = AddressOf M2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'a2 = AddressOf M2')
Left:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a2')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf M2')
Target:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a3 = New Ac ... dressOf M3)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'a3 = New Ac ... dressOf M3)')
Left:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a3')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action(AddressOf M3)')
Target:
IMethodReferenceOperation: Sub C.M3() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M3')
Instance Receiver:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub DelegateCreation_ControlFlowInTarget()
Dim source = <![CDATA[
Imports System
Class C
Private Sub M(a1 As Action, a2 As Action, a3 As Action) 'BIND:"Private Sub M(a1 As Action, a2 As Action, a3 As Action)"
a1 = AddressOf If(a2, a3)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Action, IsInvalid) (Syntax: 'a2')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'a2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'a2')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a2')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'a2')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a3')
Value:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Action, IsInvalid) (Syntax: 'a3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = Addres ... If(a2, a3)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'a1 = Addres ... If(a2, a3)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'AddressOf If(a2, a3)')
Target:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'AddressOf If(a2, a3)')
Children(1):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'If(a2, a3)')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30577: 'AddressOf' operand must be the name of a method (without parentheses).
a1 = AddressOf If(a2, a3)
~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
#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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
#Region "Lambda Expressions"
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = Sub() Console.WriteLine("")'BIND:"Dim a As Action = Sub() Console.WriteLine("")"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... iteLine("")')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... iteLine("")')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Sub() Con ... iteLine("")')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "") (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_JustInitializerReturnsOnlyLambda()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = Sub() Console.WriteLine("")'BIND:"Sub() Console.WriteLine("")"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "") (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of SingleLineLambdaExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = Sub(i As Integer) Console.WriteLine("")'BIND:"Dim a As Action = Sub(i As Integer) Console.WriteLine("")"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... iteLine("")')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... iteLine("")')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Sub(i As ... iteLine("")')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... iteLine("")')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action'.
Dim a As Action = Sub(i As Integer) Console.WriteLine("")'BIND:"Dim a As Action = Sub(i As Integer) Console.WriteLine("")"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = Sub(c1 As C1) Console.WriteLine("")'BIND:"Dim a As Action(Of String) = Sub(c1 As C1) Console.WriteLine("")"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... iteLine("")')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... iteLine("")')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Sub(c1 As ... iteLine("")')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = Sub(c1 As C1) Console.WriteLine("")'BIND:"Dim a As Action(Of String) = Sub(c1 As C1) Console.WriteLine("")"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_InvalidReturnType()
Dim source = <![CDATA[
Option Strict Off
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = Function() New NonExistant()'BIND:"Dim a As Func(Of String) = Function() New NonExistant()"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Fu ... nExistant()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Func(O ... nExistant()')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Func(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Function( ... nExistant()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of String) = Function() New NonExistant()'BIND:"Dim a As Func(Of String) = Function() New NonExistant()"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = Function() 1'BIND:"Dim a As Func(Of String) = Function() 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Fu ... unction() 1')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Func(O ... unction() 1')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Func(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= Function() 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim a As Func(Of String) = Function() 1'BIND:"Dim a As Func(Of String) = Function() 1"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaConversion_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = Function() 1'BIND:"Dim a As Action = Function() 1"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... unction() 1')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... unction() 1')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Function() 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'Function() 1')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Int32) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Int32
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitLambdaExpression_RelaxationOfArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action(Of String) = Sub(o As Object) Console.WriteLine(o)'BIND:"Dim a As Action(Of String) = Sub(o As Object) Console.WriteLine(o)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... riteLine(o)')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... riteLine(o)')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Sub(o As ... riteLine(o)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsImplicit) (Syntax: 'Sub(o As Ob ... riteLine(o)')
Target:
IAnonymousFunctionOperation (Symbol: Sub (o As System.Object)) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub(o As Ob ... riteLine(o)')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub(o As Ob ... riteLine(o)')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine(o)')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.Object)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine(o)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'o')
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
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)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub(o As Ob ... riteLine(o)')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub(o As Ob ... riteLine(o)')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Action = CType(Sub() Console.WriteLine(), Action)'BIND:"CType(Sub() Console.WriteLine(), Action)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Sub() ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Action = CType(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"CType(Sub(i As Integer) Console.WriteLine(), Action)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'CType(Sub(i ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action'.
Dim a As Action = CType(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"CType(Sub(i As Integer) Console.WriteLine(), Action)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = CType(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"CType(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'CType(Sub(c ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = CType(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"CType(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Func(Of String) = CType(Function() 1, Func(Of String))'BIND:"CType(Function() 1, Func(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(Funct ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim a As Func(Of String) = CType(Function() 1, Func(Of String))'BIND:"CType(Function() 1, Func(Of String))"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_InvalidReturnType()
Dim source = <![CDATA[
Option Strict Off
Imports System
Module M1
Sub Main()
Dim a As Func(Of String) = CType(Function() New NonExistant(), Func(Of String)) 'BIND:"CType(Function() New NonExistant(), Func(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(Funct ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of String) = CType(Function() New NonExistant(), Func(Of String)) 'BIND:"CType(Function() New NonExistant(), Func(Of String))"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of Object) = CType(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))'BIND:"Dim a As Action(Of Object) = CType(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... f Integer))')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... f Integer))')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.Object)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= CType(Sub ... f Integer))')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action(Of System.Object), IsInvalid, IsImplicit) (Syntax: 'CType(Sub(i ... f Integer))')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsInvalid) (Syntax: 'CType(Sub(i ... f Integer))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36755: 'Action(Of Integer)' cannot be converted to 'Action(Of Object)' because 'Object' is not derived from 'Integer', as required for the 'In' generic parameter 'T' in 'Delegate Sub Action(Of In T)(obj As T)'.
Dim a As Action(Of Object) = CType(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))'BIND:"Dim a As Action(Of Object) = CType(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Func(Of Object) = CType(Function() 1, Func(Of Object))'BIND:"CType(Function() 1, Func(Of Object))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object)) (Syntax: 'CType(Funct ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Object) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Object
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeLambdaConversion_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Main()
Dim a As Action(Of Object) = CType(Sub() Console.WriteLine(), Action(Of Object))'BIND:"CType(Sub() Console.WriteLine(), Action(Of Object))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Object)) (Syntax: 'CType(Sub() ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeMethodBinding()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = CType(AddressOf M1, Action)'BIND:"CType(AddressOf M1, Action)"
End Sub
Sub M1()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Addre ... M1, Action)')
Target:
IMethodReferenceOperation: Sub Program.M1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeMethodBinding_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of Object) = CType(AddressOf M1, Action(Of Integer))'BIND:"Dim a As Action(Of Object) = CType(AddressOf M1, Action(Of Integer))"
End Sub
Sub M1(i As Integer)
End Sub
End Module
]]>.Value
' Explicitly verifying the entire tree here to ensure that the top level initializer statement is actually an IConversion, and not
' a delegate creation
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... f Integer))')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... f Integer))')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.Object)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= CType(Add ... f Integer))')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action(Of System.Object), IsInvalid, IsImplicit) (Syntax: 'CType(Addre ... f Integer))')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsInvalid) (Syntax: 'CType(Addre ... f Integer))')
Target:
IMethodReferenceOperation: Sub Program.M1(i As System.Int32) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36755: 'Action(Of Integer)' cannot be converted to 'Action(Of Object)' because 'Object' is not derived from 'Integer', as required for the 'In' generic parameter 'T' in 'Delegate Sub Action(Of In T)(obj As T)'.
Dim a As Action(Of Object) = CType(AddressOf M1, Action(Of Integer))'BIND:"Dim a As Action(Of Object) = CType(AddressOf M1, Action(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = DirectCast(Sub() Console.WriteLine(), Action)'BIND:"DirectCast(Sub() Console.WriteLine(), Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = DirectCast(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"DirectCast(Sub(i As Integer) Console.WriteLine(), Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'DirectCast( ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action'.
Dim a As Action = DirectCast(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"DirectCast(Sub(i As Integer) Console.WriteLine(), Action)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = DirectCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"DirectCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = DirectCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"DirectCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of String) = DirectCast(Function() 1, Func(Of String))'BIND:"DirectCast(Function() 1, Func(Of String))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'String'.
Dim a As Func(Of String) = DirectCast(Function() 1, Func(Of String))'BIND:"DirectCast(Function() 1, Func(Of String))"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_InvalidReturnType()
Dim source = <![CDATA[
Option Strict Off
Imports System
Module Program
Sub Main()
Dim a As Func(Of String) = DirectCast(Function() New NonExistant(), Func(Of String)) 'BIND:"DirectCast(Function() New NonExistant(), Func(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.String) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.String
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of String) = DirectCast(Function() New NonExistant(), Func(Of String)) 'BIND:"DirectCast(Function() New NonExistant(), Func(Of String))"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of String) = DirectCast(Function() 1, Func(Of Integer))'BIND:"DirectCast(Function() 1, Func(Of Integer))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsInvalid) (Syntax: 'DirectCast( ... f Integer))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Int32) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Int32
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36754: 'Func(Of Integer)' cannot be converted to 'Func(Of String)' because 'Integer' is not derived from 'String', as required for the 'Out' generic parameter 'TResult' in 'Delegate Function Func(Of Out TResult)() As TResult'.
Dim a As Func(Of String) = DirectCast(Function() 1, Func(Of Integer))'BIND:"DirectCast(Function() 1, Func(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of Object) = DirectCast(Function() 1, Func(Of Object))'BIND:"DirectCast(Function() 1, Func(Of Object))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object)) (Syntax: 'DirectCast( ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Object) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Object
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastLambdaConversion_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of Object) = DirectCast(Sub() Console.WriteLine(), Action(Of Object))'BIND:"DirectCast(Sub() Console.WriteLine(), Action(Of Object))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Object)) (Syntax: 'DirectCast( ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = TryCast(Sub() Console.WriteLine(), Action)'BIND:"TryCast(Sub() Console.WriteLine(), Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Sub ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = TryCast(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"TryCast(Sub(i As Integer) Console.WriteLine(), Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'TryCast(Sub ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action'.
Dim a As Action = TryCast(Sub(i As Integer) Console.WriteLine(), Action)'BIND:"TryCast(Sub(i As Integer) Console.WriteLine(), Action)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = TryCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"TryCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'TryCast(Sub ... Of String))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = TryCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))'BIND:"TryCast(Sub(c1 As C1) Console.WriteLine(""), Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of Object) = TryCast(Sub() Console.WriteLine(), Func(Of Object))'BIND:"TryCast(Sub() Console.WriteLine(), Func(Of Object))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'TryCast(Sub ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of Object)'.
Dim a As Func(Of Object) = TryCast(Sub() Console.WriteLine(), Func(Of Object))'BIND:"TryCast(Sub() Console.WriteLine(), Func(Of Object))"
~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Func(Of Object) = TryCast(Function() New NonExistant(), Func(Of Object)) 'BIND:"TryCast(Function() New NonExistant(), Func(Of Object))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'TryCast(Fun ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Object) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.Object
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of Object) = TryCast(Function() New NonExistant(), Func(Of Object)) 'BIND:"TryCast(Function() New NonExistant(), Func(Of Object))"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of String) = TryCast(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))'BIND:"TryCast(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsInvalid) (Syntax: 'TryCast(Sub ... f Integer))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36755: 'Action(Of Integer)' cannot be converted to 'Action(Of String)' because 'String' is not derived from 'Integer', as required for the 'In' generic parameter 'T' in 'Delegate Sub Action(Of In T)(obj As T)'.
Dim a As Action(Of String) = TryCast(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))'BIND:"TryCast(Sub(i As Integer) Console.WriteLine(), Action(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action(Of Object) = TryCast(Sub() Console.WriteLine(), Action(Of Object))'BIND:"TryCast(Sub() Console.WriteLine(), Action(Of Object))"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Object)) (Syntax: 'TryCast(Sub ... Of Object))')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastLambdaConversion_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub Main()
Dim a As Action = TryCast(Function() 1, Action)'BIND:"TryCast(Function() 1, Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Fun ... 1, Action)')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Int32) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Int32
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(Sub() Console.WriteLine())'BIND:"New Action(Sub() Console.WriteLine())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... riteLine())')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_MultipleArgumentsToConstructor()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(Sub() Console.WriteLine(), 1)'BIND:"Dim a As Action = New Action(Sub() Console.WriteLine(), 1)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... eLine(), 1)')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... eLine(), 1)')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New Actio ... eLine(), 1)')
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'New Action( ... eLine(), 1)')
Children(2):
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32008: Delegate 'Action' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.
Dim a As Action = New Action(Sub() Console.WriteLine(), 1)'BIND:"Dim a As Action = New Action(Sub() Console.WriteLine(), 1)"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action(Of String) = New Action(Of String)(Sub() Console.WriteLine())'BIND:"New Action(Of String)(Sub() Console.WriteLine())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String)) (Syntax: 'New Action( ... riteLine())')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(Function() 1)'BIND:"New Action(Function() 1)"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action(Function() 1)')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Int32) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Function() 1')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Function() 1')
Locals: Local_1: <anonymous local> As System.Int32
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Function() 1')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Function() 1')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'Function() 1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action(Of Object) = New Action(Of Object)(Sub(i As Integer) Console.WriteLine())'BIND:"New Action(Of Object)(Sub(i As Integer) Console.WriteLine())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Object), IsInvalid) (Syntax: 'New Action( ... riteLine())')
Target:
IAnonymousFunctionOperation (Symbol: Sub (i As System.Int32)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(i As In ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(i As In ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'.
Dim a As Action(Of Object) = New Action(Of Object)(Sub(i As Integer) Console.WriteLine())'BIND:"New Action(Of Object)(Sub(i As Integer) Console.WriteLine())"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = New Action(Of String)(Sub(c1 As C1) Console.WriteLine(""))'BIND:"New Action(Of String)(Sub(c1 As C1) Console.WriteLine(""))"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'New Action( ... teLine(""))')
Target:
IAnonymousFunctionOperation (Symbol: Sub (c1 As M1.C1)) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub(c1 As C ... iteLine("")')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine("")')
Expression:
IInvocationOperation (Sub System.Console.WriteLine(value As System.String)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine("")')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '""')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", IsInvalid) (Syntax: '""')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub(c1 As C ... iteLine("")')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Action(Of String)'.
Dim a As Action(Of String) = New Action(Of String)(Sub(c1 As C1) Console.WriteLine(""))'BIND:"New Action(Of String)(Sub(c1 As C1) Console.WriteLine(""))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of Object) = New Func(Of Object)(Sub() Console.WriteLine())'BIND:"New Func(Of Object)(Sub() Console.WriteLine())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'New Func(Of ... riteLine())')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of Object)'.
Dim a As Func(Of Object) = New Func(Of Object)(Sub() Console.WriteLine())'BIND:"New Func(Of Object)(Sub() Console.WriteLine())"
~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationLambdaArgument_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of Object) = New Func(Of Object)(Function() New NonExistant())'BIND:"New Func(Of Object)(Function() New NonExistant())"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'New Func(Of ... Existant())')
Target:
IAnonymousFunctionOperation (Symbol: Function () As System.Object) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Function() ... nExistant()')
IBlockOperation (3 statements, 1 locals) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Locals: Local_1: <anonymous local> As System.Object
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'New NonExistant()')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvalidOperation (OperationKind.Invalid, Type: NonExistant, IsInvalid) (Syntax: 'New NonExistant()')
Children(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
ReturnedValue:
ILocalReferenceOperation: (OperationKind.LocalReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'Function() ... nExistant()')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30002: Type 'NonExistant' is not defined.
Dim a As Func(Of Object) = New Func(Of Object)(Function() New NonExistant())'BIND:"New Func(Of Object)(Function() New NonExistant())"
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((Sub() Console.WriteLine())), Action)'BIND:"CType(((Sub() Console.WriteLine())), Action)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(((Sub ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_Multiline()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((Sub()'BIND:"CType(((Sub()"
End Sub)), Action)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(((Sub ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_Implicit()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a As Action = ((Sub() Console.WriteLine()))'BIND:"= ((Sub() Console.WriteLine()))"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ((Sub() C ... iteLine()))')
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_InvalidMissingParameter()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((Sub()'BIND:"CType(((Sub()"
End Sub)), Action(Of String))
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'CType(((Sub ... Of String))')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'obj' of 'Action(Of String)'.
CType(((Sub()'BIND:"CType(((Sub()"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_InvalidConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((Sub()'BIND:"CType(((Sub()"
End Sub)), Func(Of String))
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(((Sub ... Of String))')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36670: Nested sub does not have a signature that is compatible with delegate 'Func(Of String)'.
CType(((Sub()'BIND:"CType(((Sub()"
~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_NonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = CType(((Sub() Console.WriteLine())), Object)'BIND:"CType(((Sub() Console.WriteLine())), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'CType(((Sub ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_NestedCTypeNonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = CType(((CType(Sub() Console.WriteLine(), Action))), Object)'BIND:"CType(((CType(Sub() Console.WriteLine(), Action))), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'CType(((CTy ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((CType(Sub ... , Action)))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(CType(Sub( ... ), Action))')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Sub() ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_DirectCast_NonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = DirectCast(((Sub() Console.WriteLine())), Object)'BIND:"DirectCast(((Sub() Console.WriteLine())), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'DirectCast( ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_DirectCast_NestedDirectCastNonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = DirectCast(((DirectCast(Sub() Console.WriteLine(), Action))), Object)'BIND:"DirectCast(((DirectCast(Sub() Console.WriteLine(), Action))), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'DirectCast( ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((DirectCas ... , Action)))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(DirectCast ... ), Action))')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_TryCast_NonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = TryCast(((Sub() Console.WriteLine())), Object)'BIND:"TryCast(((Sub() Console.WriteLine())), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'TryCast(((S ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: Sub <generated method>()) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_TryCast_NestedTryCastNonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = TryCast(((TryCast(Sub() Console.WriteLine(), Action))), Object)'BIND:"TryCast(((TryCast(Sub() Console.WriteLine(), Action))), Object)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: True, Unchecked) (OperationKind.Conversion, Type: System.Object) (Syntax: 'TryCast(((T ... )), Object)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((TryCast(S ... , Action)))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(TryCast(Su ... ), Action))')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Sub ... (), Action)')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_Implicit_NonDelegateTargetType_SuccessfulConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a As Object = ((Sub() Console.WriteLine()))'BIND:"= ((Sub() Console.WriteLine()))"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ((Sub() C ... iteLine()))')
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Object) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Object) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_CType_InvalidNonDelegateTargetType_InvalidConversion()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a = CType(((Sub() Console.WriteLine())), String)'BIND:"CType(((Sub() Console.WriteLine())), String)"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid) (Syntax: 'CType(((Sub ... )), String)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((Sub() Con ... iteLine()))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(Sub() Cons ... riteLine())')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36625: Lambda expression cannot be converted to 'String' because 'String' is not a delegate type.
Dim a = CType(((Sub() Console.WriteLine())), String)'BIND:"CType(((Sub() Console.WriteLine())), String)"
~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_DirectCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
DirectCast(((Sub()'BIND:"DirectCast(((Sub()"
End Sub)), Action)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ParenthesizedLambda_TryCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
TryCast(((Sub()'BIND:"TryCast(((Sub()"
End Sub)), Action)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(((S ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((Sub()'BIN ... End Sub))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(Sub()'BIND ... End Sub)')
Operand:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
#End Region
#Region "AddressOf"
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = AddressOf Method2'BIND:"Dim a As Action = AddressOf Method2"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_JustInitializerReturnsOnlyMethodReference()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = AddressOf Method2'BIND:"AddressOf Method2"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_WithReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = AddressOf o.ToString'BIND:"Dim a As Action = AddressOf o.ToString"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... o.ToString')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... o.ToString')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= AddressOf o.ToString')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf o.ToString')
Target:
IMethodReferenceOperation: Function System.Object.ToString() As System.String (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf o.ToString')
Instance Receiver:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = AddressOf Method2'BIND:"Dim a As Action = AddressOf Method2"
End Sub
Sub Method2(i As Integer)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action = AddressOf Method2'BIND:"Dim a As Action = AddressOf Method2"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = AddressOf Method2'BIND:"Dim a As Action(Of String) = AddressOf Method2"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = AddressOf Method2'BIND:"Dim a As Action(Of String) = AddressOf Method2"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = AddressOf Method2 'BIND:"Dim a As Func(Of String) = AddressOf Method2"
End Sub
Function Method2() As Integer
Return 1
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Fu ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Func(O ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Func(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IMethodReferenceOperation: Function M1.Method2() As System.Int32 (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36663: Option Strict On does not allow narrowing in implicit type conversions between method 'Public Function Method2() As Integer' and delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = AddressOf Method2 'BIND:"Dim a As Func(Of String) = AddressOf Method2"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = AddressOf Method2 'BIND:"Dim a As Func(Of String) = AddressOf Method2"
End Sub
Function Method2() As NonExistant
Return New NonExistant
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Fu ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Func(O ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Func(Of System.String)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Function Method2() As NonExistant' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = AddressOf Method2 'BIND:"Dim a As Func(Of String) = AddressOf Method2"
~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Function Method2() As NonExistant
~~~~~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Return New NonExistant
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = AddressOf Method2 'BIND:"Dim a As Action = AddressOf Method2"
End Sub
Function Method2() As Object
Return 1
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IMethodReferenceOperation: Function M1.Method2() As System.Object (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict Off
Imports System
Module M1
Sub Method1()
Dim a As Action(Of Integer) = AddressOf Method2'BIND:"Dim a As Action(Of Integer) = AddressOf Method2"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a As Ac ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a As Action ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action(Of System.Int32)) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= AddressOf Method2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsImplicit) (Syntax: 'AddressOf Method2')
Target:
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAddressOf_ConvertedToNonDelegateType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As String = AddressOf Method2'BIND:"Dim a As String = AddressOf Method2"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
' We don't expect a delegate creation here. This is documenting that we still have a conversion expression when the target type
' isn't a delegate type
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As St ... sOf Method2')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As String ... sOf Method2')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.String) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= AddressOf Method2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30581: 'AddressOf' expression cannot be converted to 'String' because 'String' is not a delegate type.
Dim a As String = AddressOf Method2'BIND:"Dim a As String = AddressOf Method2"
~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim a As Action = CType(AddressOf M1, Action)'BIND:"CType(AddressOf M1, Action)"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Addre ... M1, Action)')
Target:
IMethodReferenceOperation: Sub Program.M1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_WithReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = CType(AddressOf o.ToString, Action)'BIND:"CType(AddressOf o.ToString, Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Addre ... ng, Action)')
Target:
IMethodReferenceOperation: Function System.Object.ToString() As System.String (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf o.ToString')
Instance Receiver:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = CType(AddressOf M2, Action)'BIND:"CType(AddressOf M2, Action)"
End Sub
Sub M2(i As Integer)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'CType(Addre ... M2, Action)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2(i As Integer)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action = CType(AddressOf M2, Action)'BIND:"CType(AddressOf M2, Action)"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = CType(AddressOf Method2, Action(Of String))'BIND:"CType(AddressOf Method2, Action(Of String))"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'CType(Addre ... Of String))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = CType(AddressOf Method2, Action(Of String))'BIND:"CType(AddressOf Method2, Action(Of String))"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_InvalidReturnConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of String) = CType(AddressOf M2, Func(Of String))'BIND:"CType(AddressOf M2, Func(Of String))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(Addre ... Of String))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2()' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = CType(AddressOf M2, Func(Of String))'BIND:"CType(AddressOf M2, Func(Of String))"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action(Of String) = CType(AddressOf M2, Action(Of Integer))'BIND:"CType(AddressOf M2, Action(Of Integer))"
End Sub
Sub M2(i As Integer)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32), IsInvalid) (Syntax: 'CType(Addre ... f Integer))')
Target:
IMethodReferenceOperation: Sub Program.M2(i As System.Int32) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36755: 'Action(Of Integer)' cannot be converted to 'Action(Of String)' because 'String' is not derived from 'Integer', as required for the 'In' generic parameter 'T' in 'Delegate Sub Action(Of In T)(obj As T)'.
Dim a As Action(Of String) = CType(AddressOf M2, Action(Of Integer))'BIND:"CType(AddressOf M2, Action(Of Integer))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = CType(AddressOf M2, Action)'BIND:"CType(AddressOf M2, Action)"
End Sub
Function M2() As Integer
Return 1
End Function
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(Addre ... M2, Action)')
Target:
IMethodReferenceOperation: Function Program.M2() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_CTypeAddressOf_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action(Of String) = CType(AddressOf M2, Action(Of String))'BIND:"CType(AddressOf M2, Action(Of String))"
End Sub
Sub M2(o As Object)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String)) (Syntax: 'CType(Addre ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2(o As System.Object) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf M2, Action)'BIND:"DirectCast(AddressOf M2, Action)"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... M2, Action)')
Target:
IMethodReferenceOperation: Sub Program.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_WithReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf o.ToString, Action)'BIND:"DirectCast(AddressOf o.ToString, Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... ng, Action)')
Target:
IMethodReferenceOperation: Function System.Object.ToString() As System.String (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf o.ToString')
Instance Receiver:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of Object) = DirectCast(AddressOf M2, Func(Of Object))'BIND:"DirectCast(AddressOf M2, Func(Of Object))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'DirectCast( ... Of Object))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2()' does not have a signature compatible with delegate 'Delegate Function Func(Of Object)() As Object'.
Dim a As Func(Of Object) = DirectCast(AddressOf M2, Func(Of Object))'BIND:"DirectCast(AddressOf M2, Func(Of Object))"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of Object) = DirectCast(AddressOf M2, Func(Of Object))'BIND:"DirectCast(AddressOf M2, Func(Of Object))"
End Sub
Function M2() As NonExistant
Return New NonExistant
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'DirectCast( ... Of Object))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Function M2() As NonExistant' does not have a signature compatible with delegate 'Delegate Function Func(Of Object)() As Object'.
Dim a As Func(Of Object) = DirectCast(AddressOf M2, Func(Of Object))'BIND:"DirectCast(AddressOf M2, Func(Of Object))"
~~
BC30002: Type 'NonExistant' is not defined.
Function M2() As NonExistant
~~~~~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Return New NonExistant
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf M2, Action)'BIND:"DirectCast(AddressOf M2, Action)"
End Sub
Sub M2(s As Integer)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'DirectCast( ... M2, Action)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2(s As Integer)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action = DirectCast(AddressOf M2, Action)'BIND:"DirectCast(AddressOf M2, Action)"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = DirectCast(AddressOf Method2, Action(Of String))'BIND:"DirectCast(AddressOf Method2, Action(Of String))"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = DirectCast(AddressOf Method2, Action(Of String))'BIND:"DirectCast(AddressOf Method2, Action(Of String))"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf M2, Action(Of String))'BIND:"DirectCast(AddressOf M2, Action(Of String))"
End Sub
Sub M2(s As String)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'DirectCast( ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2(s As System.String) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'Action(Of String)' cannot be converted to 'Action'.
Dim a As Action = DirectCast(AddressOf M2, Action(Of String))'BIND:"DirectCast(AddressOf M2, Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action(Of String) = DirectCast(AddressOf M2, Action(Of String))'BIND:"DirectCast(AddressOf M2, Action(Of String))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String)) (Syntax: 'DirectCast( ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DirectCastAddressOf_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = DirectCast(AddressOf M2, Action)'BIND:"DirectCast(AddressOf M2, Action)"
End Sub
Function M2() As Integer
Return 1
End Function
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... M2, Action)')
Target:
IMethodReferenceOperation: Function Program.M2() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf M2, Action)'BIND:"TryCast(AddressOf M2, Action)"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Add ... M2, Action)')
Target:
IMethodReferenceOperation: Sub Program.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_WithReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf o.ToString, Action)'BIND:"TryCast(AddressOf o.ToString, Action)"
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Add ... ng, Action)')
Target:
IMethodReferenceOperation: Function System.Object.ToString() As System.String (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf o.ToString')
Instance Receiver:
ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of Object) = TryCast(AddressOf M2, Func(Of Object))'BIND:"TryCast(AddressOf M2, Func(Of Object))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'TryCast(Add ... Of Object))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2()' does not have a signature compatible with delegate 'Delegate Function Func(Of Object)() As Object'.
Dim a As Func(Of Object) = TryCast(AddressOf M2, Func(Of Object))'BIND:"TryCast(AddressOf M2, Func(Of Object))"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Func(Of Object) = TryCast(AddressOf M2, Func(Of Object))'BIND:"TryCast(AddressOf M2, Func(Of Object))"
End Sub
Function M2() As NonExistant
Return NonExistant
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Object), IsInvalid) (Syntax: 'TryCast(Add ... Of Object))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Function M2() As NonExistant' does not have a signature compatible with delegate 'Delegate Function Func(Of Object)() As Object'.
Dim a As Func(Of Object) = TryCast(AddressOf M2, Func(Of Object))'BIND:"TryCast(AddressOf M2, Func(Of Object))"
~~
BC30002: Type 'NonExistant' is not defined.
Function M2() As NonExistant
~~~~~~~~~~~
BC30451: 'NonExistant' is not declared. It may be inaccessible due to its protection level.
Return NonExistant
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf M2, Action)'BIND:"TryCast(AddressOf M2, Action)"
End Sub
Sub M2(s As Integer)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'TryCast(Add ... M2, Action)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2(s As Integer)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action = TryCast(AddressOf M2, Action)'BIND:"TryCast(AddressOf M2, Action)"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = TryCast(AddressOf Method2, Action(Of String))'BIND:"TryCast(AddressOf Method2, Action(Of String))"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'TryCast(Add ... Of String))')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = TryCast(AddressOf Method2, Action(Of String))'BIND:"TryCast(AddressOf Method2, Action(Of String))"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_InvalidVariableType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf M2, Action(Of String))'BIND:"TryCast(AddressOf M2, Action(Of String))"
End Sub
Sub M2(s As String)
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'TryCast(Add ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2(s As System.String) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30311: Value of type 'Action(Of String)' cannot be converted to 'Action'.
Dim a As Action = TryCast(AddressOf M2, Action(Of String))'BIND:"TryCast(AddressOf M2, Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action(Of String) = TryCast(AddressOf M2, Action(Of String))'BIND:"TryCast(AddressOf M2, Action(Of String))"
End Sub
Sub M2()
End Sub
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String)) (Syntax: 'TryCast(Add ... Of String))')
Target:
IMethodReferenceOperation: Sub Program.M2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_TryCastAddressOf_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module Program
Sub M1()
Dim o As New Object
Dim a As Action = TryCast(AddressOf M2, Action)'BIND:"TryCast(AddressOf M2, Action)"
End Sub
Function M2() As Integer
Return 1
End Function
End Module
]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(Add ... M2, Action)')
Target:
IMethodReferenceOperation: Function Program.M2() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
<WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... Of Method2)')
Target:
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
<WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")>
Public Sub DelegateCreationExpression_DelegateCreationInstanceAddressOfArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Class M1
Sub Method1()
Dim a As Action = New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
End Sub
Sub Method2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... Of Method2)')
Target:
IMethodReferenceOperation: Sub M1.Method2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
<WorkItem(15513, "https://github.com/dotnet/roslyn/issues/15513")>
Public Sub DelegateCreationExpression_DelegateCreationSharedAddressOfArgument()
Dim source = <![CDATA[
Option Strict On
Imports System
Class M1
Sub Method1()
Dim a As Action = New Action(AddressOf Me.Method2)'BIND:"New Action(AddressOf Me.Method2)"
End Sub
Shared Sub Method2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... Me.Method2)')
Target:
IMethodReferenceOperation: Sub M1.Method2() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Me.Method2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1) (Syntax: 'Me')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Dim a As Action = New Action(AddressOf Me.Method2)'BIND:"New Action(AddressOf Me.Method2)"
~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_MultipleArgumentsToConstructor()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(AddressOf Method2, 1)'BIND:"Dim a As Action = New Action(AddressOf Method2, 1)"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Dim a As Ac ... Method2, 1)')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'a As Action ... Method2, 1)')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Action) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= New Actio ... Method2, 1)')
IInvalidOperation (OperationKind.Invalid, Type: System.Action, IsInvalid) (Syntax: 'New Action( ... Method2, 1)')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC32008: Delegate 'Action' requires an 'AddressOf' expression or lambda expression as the only argument to its constructor.
Dim a As Action = New Action(AddressOf Method2, 1)'BIND:"Dim a As Action = New Action(AddressOf Method2, 1)"
~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_ReturnRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action = New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
End Sub
Function Method2() As Object
Return 1
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action( ... Of Method2)')
Target:
IMethodReferenceOperation: Function M1.Method2() As System.Object (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_ArgumentRelaxation()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action(Of Integer) = New Action(Of Integer)(AddressOf Method2)'BIND:"New Action(Of Integer)(AddressOf Method2)"
End Sub
Sub Method2(o As Object)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.Int32)) (Syntax: 'New Action( ... Of Method2)')
Target:
IMethodReferenceOperation: Sub M1.Method2(o As System.Object) (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Method2')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_DisallowedArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Action= New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
End Sub
Sub Method2(o As Object)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'New Action( ... Of Method2)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(o As Object)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
Dim a As Action= New Action(AddressOf Method2)'BIND:"New Action(AddressOf Method2)"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_InvalidArgumentType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
End Class
Sub Method1()
Dim a As Action(Of String) = New Action(Of String)(AddressOf Method2)'BIND:"New Action(Of String)(AddressOf Method2)"
End Sub
Sub Method2(i As C1)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'New Action( ... Of Method2)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2(i As M1.C1)' does not have a signature compatible with delegate 'Delegate Sub Action(Of String)(obj As String)'.
Dim a As Action(Of String) = New Action(Of String)(AddressOf Method2)'BIND:"New Action(Of String)(AddressOf Method2)"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_DisallowedReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = New Func(Of String)(AddressOf Method2)'BIND:"New Func(Of String)(AddressOf Method2)"
End Sub
Sub Method2()
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'New Func(Of ... Of Method2)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub Method2()' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = New Func(Of String)(AddressOf Method2)'BIND:"New Func(Of String)(AddressOf Method2)"
~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_DelegateCreationAddressOfArgument_InvalidReturnType()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a As Func(Of String) = New Func(Of String)(AddressOf Method2)'BIND:"New Func(Of String)(AddressOf Method2)"
End Sub
Function Method2() As NonExistant
Return New NonExistant()
End Function
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'New Func(Of ... Of Method2)')
Target:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf Method2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Method2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: M1, IsInvalid, IsImplicit) (Syntax: 'Method2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Function Method2() As NonExistant' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
Dim a As Func(Of String) = New Func(Of String)(AddressOf Method2)'BIND:"New Func(Of String)(AddressOf Method2)"
~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Function Method2() As NonExistant
~~~~~~~~~~~
BC30002: Type 'NonExistant' is not defined.
Return New NonExistant()
~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IDelegateCreation_SharedAddressOfWithInstanceReceiver()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Shared Sub S1()
End Sub
Shared Sub S2()
Dim c1Instance As New C1
Dim a As Action = AddressOf c1Instance.S1'BIND:"AddressOf c1Instance.S1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IMethodReferenceOperation: Sub M1.C1.S1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf c1Instance.S1')
Instance Receiver:
ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Dim a As Action = AddressOf c1Instance.S1'BIND:"AddressOf c1Instance.S1"
~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IDelegateCreation_SharedAddressOfAccessOnClass()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Shared Sub S1()
End Sub
Shared Sub S2()
Dim a As Action = AddressOf C1.S1'BIND:"AddressOf C1.S1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IMethodReferenceOperation: Sub M1.C1.S1() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf C1.S1')
Instance Receiver:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub IDelegateCreation_InstanceAddressOfAccessOnClass()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Class C1
Sub S1()
End Sub
Shared Sub S2()
Dim a As Action = AddressOf C1.S1'BIND:"AddressOf C1.S1"
End Sub
End Class
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf C1.S1')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'C1.S1')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'C1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30469: Reference to a non-shared member requires an object reference.
Dim a As Action = AddressOf C1.S1'BIND:"AddressOf C1.S1"
~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of UnaryExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Action)'BIND:"CType(((AddressOf M2)), Action)"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'CType(((Add ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(AddressOf M2)')
Operand:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_Implicit()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
Dim a As Action = ((AddressOf M2))'BIND:"= ((AddressOf M2))"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ((AddressOf M2))')
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: System.Action) (Syntax: '(AddressOf M2)')
Operand:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf M2')
Target:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType_InvalidMethod()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Action)'BIND:"CType(((AddressOf M2)), Action)"
End Sub
Public Sub M2(o As Object)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid) (Syntax: 'CType(((Add ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(AddressOf M2)')
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2(o As Object)' does not have a signature compatible with delegate 'Delegate Sub Action()'.
CType(((AddressOf M2)), Action)'BIND:"CType(((AddressOf M2)), Action)"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType_InvalidMissingParameter()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Action(Of String))'BIND:"CType(((AddressOf M2)), Action(Of String))"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action(Of System.String), IsInvalid) (Syntax: 'CType(((Add ... Of String))')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(AddressOf M2)')
Operand:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'obj' of 'Action(Of String)'.
CType(((AddressOf M2)), Action(Of String))'BIND:"CType(((AddressOf M2)), Action(Of String))"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType_InvalidCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Func(Of String)) 'BIND:"CType(((AddressOf M2)), Func(Of String))"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.String), IsInvalid) (Syntax: 'CType(((Add ... Of String))')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(AddressOf M2)')
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC31143: Method 'Public Sub M2()' does not have a signature compatible with delegate 'Delegate Function Func(Of String)() As String'.
CType(((AddressOf M2)), Func(Of String)) 'BIND:"CType(((AddressOf M2)), Func(Of String))"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_CType_InvalidNonDelegateTargetType()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
CType(((AddressOf M2)), Object)'BIND:"CType(((AddressOf M2)), Object)"
End Sub
Public Sub M2(o As Object)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid) (Syntax: 'CType(((Add ... )), Object)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null, IsInvalid) (Syntax: '(AddressOf M2)')
Operand:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'AddressOf M2')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type.
CType(((AddressOf M2)), Object)'BIND:"CType(((AddressOf M2)), Object)"
~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of CTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_DirectCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
DirectCast(((AddressOf M2)), Action)'BIND:"DirectCast(((AddressOf M2)), Action)"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'DirectCast( ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(AddressOf M2)')
Operand:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of DirectCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreation_ParenthesizedAddressOf_TryCast()
Dim source = <![CDATA[
Imports System
Public Class C
Public Sub M1()
TryCast(((AddressOf M2)), Action)'BIND:"TryCast(((AddressOf M2)), Action)"
End Sub
Public Sub M2()
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'TryCast(((A ... )), Action)')
Target:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '((AddressOf M2))')
Operand:
IParenthesizedOperation (OperationKind.Parenthesized, Type: null) (Syntax: '(AddressOf M2)')
Operand:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of TryCastExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
#End Region
#Region "Anonymous Delegates"
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAnonymousDelegateConversion()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a = Sub()'BIND:"Dim a = Sub()"
End Sub
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a = Sub ... End Sub')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a = Sub()'B ... End Sub')
Declarators:
IVariableDeclaratorOperation (Symbol: a As Sub <generated method>()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Sub()'BIN ... End Sub')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAnonymousDelegateConversion_JustInitializerReturnsOnlyLambda()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a = Sub()'BIND:"Sub()"
End Sub
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub()'BIND: ... End Sub')
IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub()'BIND: ... End Sub')
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'End Sub')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'End Sub')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of MultiLineLambdaExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DelegateCreationExpression_ImplicitAnonymousDelegateConversion_SingleLineLambda()
Dim source = <![CDATA[
Option Strict On
Imports System
Module M1
Sub Method1()
Dim a = Sub() Console.WriteLine()'BIND:"Dim a = Sub() Console.WriteLine()"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a = Sub ... WriteLine()')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a = Sub() C ... WriteLine()')
Declarators:
IVariableDeclaratorOperation (Symbol: a As Sub <generated method>()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a')
Initializer:
null
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= Sub() Con ... WriteLine()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: Sub <generated method>(), IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Target:
IAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'Sub() Conso ... WriteLine()')
IBlockOperation (3 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'Console.WriteLine()')
Expression:
IInvocationOperation (Sub System.Console.WriteLine()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Console.WriteLine()')
Instance Receiver:
null
Arguments(0)
ILabeledOperation (Label: exit) (OperationKind.Labeled, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
Statement:
null
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Sub() Conso ... WriteLine()')
ReturnedValue:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
#End Region
#Region "Control Flow"
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub DelegateCreation_NoControlFlow()
Dim source = <![CDATA[
Imports System
Class C
Private Sub M(a1 As Action, a2 As Action, a3 As Action, a4 As Action) 'BIND:"Private Sub M(a1 As Action, a2 As Action, a3 As Action, a4 As Action)"
a1 = Sub()
End Sub
a2 = AddressOf M2
a3 = New Action(AddressOf M3)
End Sub
Private Sub M2()
End Sub
Private Shared Sub M3()
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a1 = Sub() ... End Sub')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'a1 = Sub() ... End Sub')
Left:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'Sub() ... End Sub')
Target:
IFlowAnonymousFunctionOperation (Symbol: Sub ()) (OperationKind.FlowAnonymousFunction, Type: null) (Syntax: 'Sub() ... End Sub')
{
Block[B0#A0] - Entry
Statements (0)
Next (Regular) Block[B1#A0]
Block[B1#A0] - Exit
Predecessors: [B0#A0]
Statements (0)
}
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a2 = AddressOf M2')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'a2 = AddressOf M2')
Left:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a2')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: 'AddressOf M2')
Target:
IMethodReferenceOperation: Sub C.M2() (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'M2')
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'a3 = New Ac ... dressOf M3)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsImplicit) (Syntax: 'a3 = New Ac ... dressOf M3)')
Left:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a3')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action) (Syntax: 'New Action(AddressOf M3)')
Target:
IMethodReferenceOperation: Sub C.M3() (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M3')
Instance Receiver:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact()>
Public Sub DelegateCreation_ControlFlowInTarget()
Dim source = <![CDATA[
Imports System
Class C
Private Sub M(a1 As Action, a2 As Action, a3 As Action) 'BIND:"Private Sub M(a1 As Action, a2 As Action, a3 As Action)"
a1 = AddressOf If(a2, a3)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a1')
Value:
IParameterReferenceOperation: a1 (OperationKind.ParameterReference, Type: System.Action) (Syntax: 'a1')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a2')
Value:
IParameterReferenceOperation: a2 (OperationKind.ParameterReference, Type: System.Action, IsInvalid) (Syntax: 'a2')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'a2')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'a2')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a2')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'a2')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'a3')
Value:
IParameterReferenceOperation: a3 (OperationKind.ParameterReference, Type: System.Action, IsInvalid) (Syntax: 'a3')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'a1 = Addres ... If(a2, a3)')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'a1 = Addres ... If(a2, a3)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Action, IsImplicit) (Syntax: 'a1')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'AddressOf If(a2, a3)')
Target:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'AddressOf If(a2, a3)')
Children(1):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Action, IsInvalid, IsImplicit) (Syntax: 'If(a2, a3)')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30577: 'AddressOf' operand must be the name of a method (without parentheses).
a1 = AddressOf If(a2, a3)
~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpInstructionDecoder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CSharpInstructionDecoder : InstructionDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol>
{
// This string was not localized in the old EE. We'll keep it that way
// so as not to break consumers who may have been parsing frame names...
private const string AnonymousMethodName = "AnonymousMethod";
/// <summary>
/// Singleton instance of <see cref="CSharpInstructionDecoder"/> (created using default constructor).
/// </summary>
internal static readonly CSharpInstructionDecoder Instance = new CSharpInstructionDecoder();
private CSharpInstructionDecoder()
{
}
private static readonly SymbolDisplayFormat s_propertyDisplayFormat = DisplayFormat.
AddMemberOptions(SymbolDisplayMemberOptions.IncludeParameters).
WithParameterOptions(SymbolDisplayParameterOptions.IncludeType);
internal override void AppendFullName(StringBuilder builder, MethodSymbol method)
{
var displayFormat = (method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.PropertySet) ?
s_propertyDisplayFormat :
DisplayFormat;
var parts = method.ToDisplayParts(displayFormat);
var numParts = parts.Length;
for (int i = 0; i < numParts; i++)
{
var part = parts[i];
var displayString = part.ToString();
switch (part.Kind)
{
case SymbolDisplayPartKind.ClassName:
if (GeneratedNameParser.GetKind(displayString) != GeneratedNameKind.LambdaDisplayClass)
{
builder.Append(displayString);
}
else
{
// Drop any remaining display class name parts and the subsequent dot...
do
{
i++;
}
while (i < numParts && parts[i].Kind != SymbolDisplayPartKind.MethodName);
i--;
}
break;
case SymbolDisplayPartKind.MethodName:
GeneratedNameKind kind;
int openBracketOffset, closeBracketOffset;
if (GeneratedNameParser.TryParseGeneratedName(displayString, out kind, out openBracketOffset, out closeBracketOffset) &&
(kind == GeneratedNameKind.LambdaMethod || kind == GeneratedNameKind.LocalFunction))
{
builder.Append(displayString, openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); // source method name
builder.Append('.');
if (kind == GeneratedNameKind.LambdaMethod)
{
builder.Append(AnonymousMethodName);
}
// NOTE: Local functions include the local function name inside the suffix ("<Main>__Local1_1")
// NOTE: The old implementation only appended the first ordinal number. Since this is not useful
// in uniquely identifying the lambda, we'll append the entire ordinal suffix (which may contain
// multiple numbers, as well as '-' or '_').
builder.Append(displayString.Substring(closeBracketOffset + 2)); // ordinal suffix (e.g. "__1")
}
else
{
builder.Append(displayString);
}
break;
default:
builder.Append(displayString);
break;
}
}
}
internal override void AppendParameterTypeName(StringBuilder builder, IParameterSymbol parameter)
{
// The old EE only displayed "ref" and "out" modifiers in C# and only when displaying parameter
// types. We will do the same here for compatibility with the old behavior.
switch (parameter.RefKind)
{
case RefKind.Out:
builder.Append("out ");
break;
case RefKind.Ref:
builder.Append("ref ");
break;
}
base.AppendParameterTypeName(builder, parameter);
}
internal override MethodSymbol ConstructMethod(MethodSymbol method, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeSymbol> typeArguments)
{
var methodArity = method.Arity;
var methodArgumentStartIndex = typeParameters.Length - methodArity;
var typeMap = new TypeMap(
ImmutableArray.Create(typeParameters, 0, methodArgumentStartIndex),
ImmutableArray.CreateRange(typeArguments, 0, methodArgumentStartIndex, t => TypeWithAnnotations.Create(t)));
var substitutedType = typeMap.SubstituteNamedType(method.ContainingType);
method = method.AsMember(substitutedType);
if (methodArity > 0)
{
method = method.Construct(ImmutableArray.Create(typeArguments, methodArgumentStartIndex, methodArity));
}
return method;
}
internal override ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(MethodSymbol method)
{
return method.GetAllTypeParameters();
}
internal override CSharpCompilation GetCompilation(DkmClrModuleInstance moduleInstance)
{
var appDomain = moduleInstance.AppDomain;
var moduleVersionId = moduleInstance.Mvid;
var previous = appDomain.GetMetadataContext<CSharpMetadataContext>();
var metadataBlocks = moduleInstance.RuntimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks);
var kind = GetMakeAssemblyReferencesKind();
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var assemblyContexts = previous.Matches(metadataBlocks) ? previous.AssemblyContexts : ImmutableDictionary<MetadataContextId, CSharpMetadataContext>.Empty;
CSharpMetadataContext previousContext;
assemblyContexts.TryGetValue(contextId, out previousContext);
var compilation = previousContext.Compilation;
if (compilation == null)
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
appDomain.SetMetadataContext(
new MetadataContext<CSharpMetadataContext>(
metadataBlocks,
assemblyContexts.SetItem(contextId, new CSharpMetadataContext(compilation))),
report: kind == MakeAssemblyReferencesKind.AllReferences);
}
return compilation;
}
internal override MethodSymbol GetMethod(CSharpCompilation compilation, DkmClrInstructionAddress instructionAddress)
{
var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(instructionAddress.MethodId.Token);
return compilation.GetSourceMethod(instructionAddress.ModuleInstance.Mvid, methodHandle);
}
internal override TypeNameDecoder<PEModuleSymbol, TypeSymbol> GetTypeNameDecoder(CSharpCompilation compilation, MethodSymbol method)
{
Debug.Assert(method is PEMethodSymbol);
return new EETypeNameDecoder(compilation, (PEModuleSymbol)method.ContainingModule);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CSharpInstructionDecoder : InstructionDecoder<CSharpCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol>
{
// This string was not localized in the old EE. We'll keep it that way
// so as not to break consumers who may have been parsing frame names...
private const string AnonymousMethodName = "AnonymousMethod";
/// <summary>
/// Singleton instance of <see cref="CSharpInstructionDecoder"/> (created using default constructor).
/// </summary>
internal static readonly CSharpInstructionDecoder Instance = new CSharpInstructionDecoder();
private CSharpInstructionDecoder()
{
}
private static readonly SymbolDisplayFormat s_propertyDisplayFormat = DisplayFormat.
AddMemberOptions(SymbolDisplayMemberOptions.IncludeParameters).
WithParameterOptions(SymbolDisplayParameterOptions.IncludeType);
internal override void AppendFullName(StringBuilder builder, MethodSymbol method)
{
var displayFormat = (method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.PropertySet) ?
s_propertyDisplayFormat :
DisplayFormat;
var parts = method.ToDisplayParts(displayFormat);
var numParts = parts.Length;
for (int i = 0; i < numParts; i++)
{
var part = parts[i];
var displayString = part.ToString();
switch (part.Kind)
{
case SymbolDisplayPartKind.ClassName:
if (GeneratedNameParser.GetKind(displayString) != GeneratedNameKind.LambdaDisplayClass)
{
builder.Append(displayString);
}
else
{
// Drop any remaining display class name parts and the subsequent dot...
do
{
i++;
}
while (i < numParts && parts[i].Kind != SymbolDisplayPartKind.MethodName);
i--;
}
break;
case SymbolDisplayPartKind.MethodName:
GeneratedNameKind kind;
int openBracketOffset, closeBracketOffset;
if (GeneratedNameParser.TryParseGeneratedName(displayString, out kind, out openBracketOffset, out closeBracketOffset) &&
(kind == GeneratedNameKind.LambdaMethod || kind == GeneratedNameKind.LocalFunction))
{
builder.Append(displayString, openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1); // source method name
builder.Append('.');
if (kind == GeneratedNameKind.LambdaMethod)
{
builder.Append(AnonymousMethodName);
}
// NOTE: Local functions include the local function name inside the suffix ("<Main>__Local1_1")
// NOTE: The old implementation only appended the first ordinal number. Since this is not useful
// in uniquely identifying the lambda, we'll append the entire ordinal suffix (which may contain
// multiple numbers, as well as '-' or '_').
builder.Append(displayString.Substring(closeBracketOffset + 2)); // ordinal suffix (e.g. "__1")
}
else
{
builder.Append(displayString);
}
break;
default:
builder.Append(displayString);
break;
}
}
}
internal override void AppendParameterTypeName(StringBuilder builder, IParameterSymbol parameter)
{
// The old EE only displayed "ref" and "out" modifiers in C# and only when displaying parameter
// types. We will do the same here for compatibility with the old behavior.
switch (parameter.RefKind)
{
case RefKind.Out:
builder.Append("out ");
break;
case RefKind.Ref:
builder.Append("ref ");
break;
}
base.AppendParameterTypeName(builder, parameter);
}
internal override MethodSymbol ConstructMethod(MethodSymbol method, ImmutableArray<TypeParameterSymbol> typeParameters, ImmutableArray<TypeSymbol> typeArguments)
{
var methodArity = method.Arity;
var methodArgumentStartIndex = typeParameters.Length - methodArity;
var typeMap = new TypeMap(
ImmutableArray.Create(typeParameters, 0, methodArgumentStartIndex),
ImmutableArray.CreateRange(typeArguments, 0, methodArgumentStartIndex, t => TypeWithAnnotations.Create(t)));
var substitutedType = typeMap.SubstituteNamedType(method.ContainingType);
method = method.AsMember(substitutedType);
if (methodArity > 0)
{
method = method.Construct(ImmutableArray.Create(typeArguments, methodArgumentStartIndex, methodArity));
}
return method;
}
internal override ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(MethodSymbol method)
{
return method.GetAllTypeParameters();
}
internal override CSharpCompilation GetCompilation(DkmClrModuleInstance moduleInstance)
{
var appDomain = moduleInstance.AppDomain;
var moduleVersionId = moduleInstance.Mvid;
var previous = appDomain.GetMetadataContext<CSharpMetadataContext>();
var metadataBlocks = moduleInstance.RuntimeInstance.GetMetadataBlocks(appDomain, previous.MetadataBlocks);
var kind = GetMakeAssemblyReferencesKind();
var contextId = MetadataContextId.GetContextId(moduleVersionId, kind);
var assemblyContexts = previous.Matches(metadataBlocks) ? previous.AssemblyContexts : ImmutableDictionary<MetadataContextId, CSharpMetadataContext>.Empty;
CSharpMetadataContext previousContext;
assemblyContexts.TryGetValue(contextId, out previousContext);
var compilation = previousContext.Compilation;
if (compilation == null)
{
compilation = metadataBlocks.ToCompilation(moduleVersionId, kind);
appDomain.SetMetadataContext(
new MetadataContext<CSharpMetadataContext>(
metadataBlocks,
assemblyContexts.SetItem(contextId, new CSharpMetadataContext(compilation))),
report: kind == MakeAssemblyReferencesKind.AllReferences);
}
return compilation;
}
internal override MethodSymbol GetMethod(CSharpCompilation compilation, DkmClrInstructionAddress instructionAddress)
{
var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(instructionAddress.MethodId.Token);
return compilation.GetSourceMethod(instructionAddress.ModuleInstance.Mvid, methodHandle);
}
internal override TypeNameDecoder<PEModuleSymbol, TypeSymbol> GetTypeNameDecoder(CSharpCompilation compilation, MethodSymbol method)
{
Debug.Assert(method is PEMethodSymbol);
return new EETypeNameDecoder(compilation, (PEModuleSymbol)method.ContainingModule);
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Test/Perf/Utilities/TestUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Roslyn.Test.Performance.Utilities
{
/// <summary>
/// Global statics shared between the runner and tests.
/// </summary>
public static class RuntimeSettings
{
/// <summary>
/// Used as a pseudo-return value for tests to send test objects
/// back to the runner.
/// </summary>
public static PerfTest[] ResultTests = null;
/// <summary>
/// The logger that is being used by the process.
/// </summary>
public static ILogger Logger = new ConsoleAndFileLogger();
/// <summary>
/// True if the logger should be verbose.
/// </summary>
public static bool IsVerbose = true;
/// <summary>
/// True if a runner is orchestrating the test runs.
/// </summary>
public static bool IsRunnerAttached = false;
}
public static class TestUtilities
{
/// <returns>
/// Returns the path to CPC
/// </returns>
public static string GetCPCDirectoryPath()
{
return Environment.ExpandEnvironmentVariables(@"%SYSTEMDRIVE%\CPC");
}
/// <returns>
/// The path to the ViBenchToJson executable.
/// </returns>
public static string GetViBenchToJsonExeFilePath()
{
return Path.Combine(GetCPCDirectoryPath(), "ViBenchToJson.exe");
}
//
// Process spawning and error handling.
//
/// <summary>
/// The result of a ShellOut completing.
/// </summary>
public class ProcessResult
{
/// <summary>
/// The path to the executable that was run.
/// </summary>
public string ExecutablePath { get; set; }
/// <summary>
/// The arguments that were passed to the process.
/// </summary>
public string Args { get; set; }
/// <summary>
/// The exit code of the process.
/// </summary>
public int Code { get; set; }
/// <summary>
/// The entire standard-out of the process.
/// </summary>
public string StdOut { get; set; }
/// <summary>
/// The entire standard-error of the process.
/// </summary>
public string StdErr { get; set; }
/// <summary>
/// True if the command returned an exit code other
/// than zero.
/// </summary>
public bool Failed => Code != 0;
/// <summary>
/// True if the command returned an exit code of 0.
/// </summary>
public bool Succeeded => !Failed;
}
/// <summary>
/// Shells out, and if the process fails, log the error and quit the script.
/// </summary>
public static void ShellOutVital(
string file,
string args,
string workingDirectory = null,
CancellationToken cancellationToken = default(CancellationToken))
{
var result = ShellOut(file, args, workingDirectory, cancellationToken);
if (result.Failed)
{
LogProcessResult(result);
throw new System.Exception("ShellOutVital Failed");
}
}
/// <summary>
/// Shells out, blocks, and returns the ProcessResult.
/// </summary>
public static ProcessResult ShellOut(
string file,
string args,
string workingDirectory = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (workingDirectory == null)
{
workingDirectory = AppDomain.CurrentDomain.BaseDirectory;
}
var tcs = new TaskCompletionSource<ProcessResult>();
var startInfo = new ProcessStartInfo(file, args);
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = workingDirectory;
var process = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true,
};
if (cancellationToken != default(CancellationToken))
{
cancellationToken.Register(() => process.Kill());
}
if (RuntimeSettings.IsVerbose)
{
Log($"running \"{file}\" with arguments \"{args}\" from directory {workingDirectory}");
}
process.Start();
var output = new StringWriter();
var error = new StringWriter();
process.OutputDataReceived += (s, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
output.WriteLine(e.Data);
}
};
process.ErrorDataReceived += (s, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
error.WriteLine(e.Data);
}
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return new ProcessResult
{
ExecutablePath = file,
Args = args,
Code = process.ExitCode,
StdOut = output.ToString(),
StdErr = error.ToString(),
};
}
/// <summary>
/// Shells out and returns the string gathered from the stdout of the
/// executing process.
///
/// Throws an exception if the process fails.
/// </summary>
public static string StdoutFrom(string program, string args = "", string workingDirectory = null)
{
var result = ShellOut(program, args, workingDirectory);
if (result.Failed)
{
LogProcessResult(result);
throw new Exception("Shelling out failed");
}
return result.StdOut.Trim();
}
/// <summary>
/// Logs a message.
///
/// The actual implementation of this method may change depending on
/// if the script is being run standalone or through the test runner.
/// </summary>
public static void Log(string info)
{
RuntimeSettings.Logger.Log(info);
RuntimeSettings.Logger.Flush();
}
/// <summary>
/// Logs the result of a finished process
/// </summary>
public static void LogProcessResult(ProcessResult result)
{
RuntimeSettings.Logger.Log(String.Format("The process \"{0}\" {1} with code {2}",
$"{result.ExecutablePath} {result.Args}",
result.Failed ? "failed" : "succeeded",
result.Code));
RuntimeSettings.Logger.Log($"Standard Out:\n{result.StdOut}");
RuntimeSettings.Logger.Log($"\nStandard Error:\n{result.StdErr}");
}
/// <summary>
/// Either runs the provided tests, or schedules them to be run by the
/// runner.
/// </summary>
public static void TestThisPlease(params PerfTest[] tests)
{
if (RuntimeSettings.IsRunnerAttached)
{
RuntimeSettings.ResultTests = tests;
}
else
{
foreach (var test in tests)
{
test.Setup();
for (int i = 0; i < test.Iterations; i++)
{
test.Test();
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Roslyn.Test.Performance.Utilities
{
/// <summary>
/// Global statics shared between the runner and tests.
/// </summary>
public static class RuntimeSettings
{
/// <summary>
/// Used as a pseudo-return value for tests to send test objects
/// back to the runner.
/// </summary>
public static PerfTest[] ResultTests = null;
/// <summary>
/// The logger that is being used by the process.
/// </summary>
public static ILogger Logger = new ConsoleAndFileLogger();
/// <summary>
/// True if the logger should be verbose.
/// </summary>
public static bool IsVerbose = true;
/// <summary>
/// True if a runner is orchestrating the test runs.
/// </summary>
public static bool IsRunnerAttached = false;
}
public static class TestUtilities
{
/// <returns>
/// Returns the path to CPC
/// </returns>
public static string GetCPCDirectoryPath()
{
return Environment.ExpandEnvironmentVariables(@"%SYSTEMDRIVE%\CPC");
}
/// <returns>
/// The path to the ViBenchToJson executable.
/// </returns>
public static string GetViBenchToJsonExeFilePath()
{
return Path.Combine(GetCPCDirectoryPath(), "ViBenchToJson.exe");
}
//
// Process spawning and error handling.
//
/// <summary>
/// The result of a ShellOut completing.
/// </summary>
public class ProcessResult
{
/// <summary>
/// The path to the executable that was run.
/// </summary>
public string ExecutablePath { get; set; }
/// <summary>
/// The arguments that were passed to the process.
/// </summary>
public string Args { get; set; }
/// <summary>
/// The exit code of the process.
/// </summary>
public int Code { get; set; }
/// <summary>
/// The entire standard-out of the process.
/// </summary>
public string StdOut { get; set; }
/// <summary>
/// The entire standard-error of the process.
/// </summary>
public string StdErr { get; set; }
/// <summary>
/// True if the command returned an exit code other
/// than zero.
/// </summary>
public bool Failed => Code != 0;
/// <summary>
/// True if the command returned an exit code of 0.
/// </summary>
public bool Succeeded => !Failed;
}
/// <summary>
/// Shells out, and if the process fails, log the error and quit the script.
/// </summary>
public static void ShellOutVital(
string file,
string args,
string workingDirectory = null,
CancellationToken cancellationToken = default(CancellationToken))
{
var result = ShellOut(file, args, workingDirectory, cancellationToken);
if (result.Failed)
{
LogProcessResult(result);
throw new System.Exception("ShellOutVital Failed");
}
}
/// <summary>
/// Shells out, blocks, and returns the ProcessResult.
/// </summary>
public static ProcessResult ShellOut(
string file,
string args,
string workingDirectory = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (workingDirectory == null)
{
workingDirectory = AppDomain.CurrentDomain.BaseDirectory;
}
var tcs = new TaskCompletionSource<ProcessResult>();
var startInfo = new ProcessStartInfo(file, args);
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = workingDirectory;
var process = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true,
};
if (cancellationToken != default(CancellationToken))
{
cancellationToken.Register(() => process.Kill());
}
if (RuntimeSettings.IsVerbose)
{
Log($"running \"{file}\" with arguments \"{args}\" from directory {workingDirectory}");
}
process.Start();
var output = new StringWriter();
var error = new StringWriter();
process.OutputDataReceived += (s, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
output.WriteLine(e.Data);
}
};
process.ErrorDataReceived += (s, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
error.WriteLine(e.Data);
}
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return new ProcessResult
{
ExecutablePath = file,
Args = args,
Code = process.ExitCode,
StdOut = output.ToString(),
StdErr = error.ToString(),
};
}
/// <summary>
/// Shells out and returns the string gathered from the stdout of the
/// executing process.
///
/// Throws an exception if the process fails.
/// </summary>
public static string StdoutFrom(string program, string args = "", string workingDirectory = null)
{
var result = ShellOut(program, args, workingDirectory);
if (result.Failed)
{
LogProcessResult(result);
throw new Exception("Shelling out failed");
}
return result.StdOut.Trim();
}
/// <summary>
/// Logs a message.
///
/// The actual implementation of this method may change depending on
/// if the script is being run standalone or through the test runner.
/// </summary>
public static void Log(string info)
{
RuntimeSettings.Logger.Log(info);
RuntimeSettings.Logger.Flush();
}
/// <summary>
/// Logs the result of a finished process
/// </summary>
public static void LogProcessResult(ProcessResult result)
{
RuntimeSettings.Logger.Log(String.Format("The process \"{0}\" {1} with code {2}",
$"{result.ExecutablePath} {result.Args}",
result.Failed ? "failed" : "succeeded",
result.Code));
RuntimeSettings.Logger.Log($"Standard Out:\n{result.StdOut}");
RuntimeSettings.Logger.Log($"\nStandard Error:\n{result.StdErr}");
}
/// <summary>
/// Either runs the provided tests, or schedules them to be run by the
/// runner.
/// </summary>
public static void TestThisPlease(params PerfTest[] tests)
{
if (RuntimeSettings.IsRunnerAttached)
{
RuntimeSettings.ResultTests = tests;
}
else
{
foreach (var test in tests)
{
test.Setup();
for (int i = 0; i < test.Iterations; i++)
{
test.Test();
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Analyzers/CSharp/CodeFixes/AddAccessibilityModifiers/CSharpAddAccessibilityModifiersService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.AddAccessibilityModifiers;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers
{
[ExportLanguageService(typeof(IAddAccessibilityModifiersService), LanguageNames.CSharp), Shared]
internal class CSharpAddAccessibilityModifiersService : CSharpAddAccessibilityModifiers, IAddAccessibilityModifiersService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpAddAccessibilityModifiersService()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.AddAccessibilityModifiers;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers
{
[ExportLanguageService(typeof(IAddAccessibilityModifiersService), LanguageNames.CSharp), Shared]
internal class CSharpAddAccessibilityModifiersService : CSharpAddAccessibilityModifiers, IAddAccessibilityModifiersService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpAddAccessibilityModifiersService()
{
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/CodeStyle/Core/Analyzers/xlf/CodeStyleResources.ru.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ru" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Для данного параметра невозможно указать имя языка.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Для данного параметра необходимо указать имя языка.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Массивы с несколькими измерениями нельзя сериализовать.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Невозможно сериализовать тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Считыватель десериализации для "{0}" считал неверное количество значений.</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Ошибка</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">Исправить форматирование</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Отступы и интервалы</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Предпочтения для новых строк</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">NONE</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Только рефакторинг</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Слишком длинный поток.</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Рекомендация</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Тип "{0}" не распознан модулем привязки сериализации.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Слишком большое значение для представления в виде 30-разрядного целого числа без знака.</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Предупреждение</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ru" original="../CodeStyleResources.resx">
<body>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Для данного параметра невозможно указать имя языка.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Для данного параметра необходимо указать имя языка.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Массивы с несколькими измерениями нельзя сериализовать.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Невозможно сериализовать тип "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Считыватель десериализации для "{0}" считал неверное количество значений.</target>
<note />
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Ошибка</target>
<note />
</trans-unit>
<trans-unit id="Fix_formatting">
<source>Fix formatting</source>
<target state="translated">Исправить форматирование</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Отступы и интервалы</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Предпочтения для новых строк</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">NONE</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Только рефакторинг</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Слишком длинный поток.</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Рекомендация</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Тип "{0}" не распознан модулем привязки сериализации.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Слишком большое значение для представления в виде 30-разрядного целого числа без знака.</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Предупреждение</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/EditorFeatures/Core.Wpf/Interactive/xlf/InteractiveEditorFeaturesResources.cs.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../InteractiveEditorFeaturesResources.resx">
<body>
<trans-unit id="Building_Project">
<source>Building Project</source>
<target state="translated">Sestavování projektu</target>
<note />
</trans-unit>
<trans-unit id="Copying_selection_to_Interactive_Window">
<source>Copying selection to Interactive Window.</source>
<target state="translated">Výběr se kopíruje do okna Interactive.</target>
<note />
</trans-unit>
<trans-unit id="Executing_selection_in_Interactive_Window">
<source>Executing selection in Interactive Window.</source>
<target state="translated">Výběr se spouští v okně Interactive.</target>
<note />
</trans-unit>
<trans-unit id="Interactive_host_process_platform">
<source>Interactive host process platform</source>
<target state="translated">Interaktivní platforma procesů hostitelů</target>
<note />
</trans-unit>
<trans-unit id="Print_a_list_of_referenced_assemblies">
<source>Print a list of referenced assemblies.</source>
<target state="translated">Vytiskne seznam odkazovaných sestavení.</target>
<note />
</trans-unit>
<trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation">
<source>The references command is not supported in this Interactive Window implementation.</source>
<target state="translated">Příkaz references není v této implementaci okna Interactive podporovaný.</target>
<note />
</trans-unit>
<trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history">
<source>Reset the execution environment to the initial state, keep history.</source>
<target state="translated">Obnoví původní stav spouštěcího prostředí, zachová historii.</target>
<note />
</trans-unit>
<trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script">
<source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source>
<target state="translated">Obnoví čisté prostředí (jenom s odkazem na mscorlib), nespustí inicializační skript.</target>
<note />
</trans-unit>
<trans-unit id="Resetting_execution_engine">
<source>Resetting execution engine.</source>
<target state="translated">Resetuje se prováděcí modul.</target>
<note />
</trans-unit>
<trans-unit id="Resetting_Interactive">
<source>Resetting Interactive</source>
<target state="translated">Znovu se nastavuje interaktivní stav.</target>
<note />
</trans-unit>
<trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once">
<source>The CurrentWindow property may only be assigned once.</source>
<target state="translated">Vlastnost CurrentWindow se dá přiřadit jenom jednou.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="cs" original="../InteractiveEditorFeaturesResources.resx">
<body>
<trans-unit id="Building_Project">
<source>Building Project</source>
<target state="translated">Sestavování projektu</target>
<note />
</trans-unit>
<trans-unit id="Copying_selection_to_Interactive_Window">
<source>Copying selection to Interactive Window.</source>
<target state="translated">Výběr se kopíruje do okna Interactive.</target>
<note />
</trans-unit>
<trans-unit id="Executing_selection_in_Interactive_Window">
<source>Executing selection in Interactive Window.</source>
<target state="translated">Výběr se spouští v okně Interactive.</target>
<note />
</trans-unit>
<trans-unit id="Interactive_host_process_platform">
<source>Interactive host process platform</source>
<target state="translated">Interaktivní platforma procesů hostitelů</target>
<note />
</trans-unit>
<trans-unit id="Print_a_list_of_referenced_assemblies">
<source>Print a list of referenced assemblies.</source>
<target state="translated">Vytiskne seznam odkazovaných sestavení.</target>
<note />
</trans-unit>
<trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation">
<source>The references command is not supported in this Interactive Window implementation.</source>
<target state="translated">Příkaz references není v této implementaci okna Interactive podporovaný.</target>
<note />
</trans-unit>
<trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history">
<source>Reset the execution environment to the initial state, keep history.</source>
<target state="translated">Obnoví původní stav spouštěcího prostředí, zachová historii.</target>
<note />
</trans-unit>
<trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script">
<source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source>
<target state="translated">Obnoví čisté prostředí (jenom s odkazem na mscorlib), nespustí inicializační skript.</target>
<note />
</trans-unit>
<trans-unit id="Resetting_execution_engine">
<source>Resetting execution engine.</source>
<target state="translated">Resetuje se prováděcí modul.</target>
<note />
</trans-unit>
<trans-unit id="Resetting_Interactive">
<source>Resetting Interactive</source>
<target state="translated">Znovu se nastavuje interaktivní stav.</target>
<note />
</trans-unit>
<trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once">
<source>The CurrentWindow property may only be assigned once.</source>
<target state="translated">Vlastnost CurrentWindow se dá přiřadit jenom jednou.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Compilers/CSharp/Test/Semantic/Semantics/NamedAndOptionalTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection;
using System.Reflection.Emit;
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
{
public class NamedAndOptionalTests : CompilingTestBase
{
[Fact]
public void Test13984()
{
string source = @"
using System;
class Program
{
static void Main() { }
static void M(DateTime da = new DateTime(2012, 6, 22),
decimal d = new decimal(5),
int i = new int())
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,33): error CS1736: Default parameter value for 'da' must be a compile-time constant
// static void M(DateTime da = new DateTime(2012, 6, 22),
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new DateTime(2012, 6, 22)").WithArguments("da"),
// (7,31): error CS1736: Default parameter value for 'd' must be a compile-time constant
// decimal d = new decimal(5),
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new decimal(5)").WithArguments("d"));
}
[Fact]
public void Test13861()
{
// * There are two decimal constant attribute constructors; we should honour both of them.
// * Using named arguments to re-order the arguments must not change the value of the constant.
string source = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class Program
{
public static void Goo1([Optional][DecimalConstant(0, 0, low: (uint)100, mid: (uint)0, hi: (uint)0)] decimal i)
{
System.Console.Write(i);
}
public static void Goo2([Optional][DecimalConstant(0, 0, 0, 0, 200)] decimal i)
{
System.Console.Write(i);
}
static void Main(string[] args)
{
Goo1();
Goo2();
}
}";
string expected = "100200";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsInCtors()
{
string source = @"
class Alpha
{
public Alpha(int x = 123) { }
}
class Bravo : Alpha
{ // See bug 7846.
// This should be legal; the generated ctor for Bravo should call base(123)
}
class Charlie : Alpha
{
public Charlie() : base() {}
// This should be legal; should call base(123)
}
class Delta : Alpha
{
public Delta() {}
// This should be legal; should call base(123)
}
abstract class Echo
{
protected Echo(int x = 123) {}
}
abstract class Foxtrot : Echo
{
}
abstract class Hotel : Echo
{
protected Hotel() {}
}
abstract class Golf : Echo
{
protected Golf() : base() {}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void TestNamedAndOptionalParamsErrors()
{
string source = @"
class Base
{
public virtual void Goo(int reqParam1,
int optParam1 = 0,
int optParam2 = default(int),
int optParam3 = new int(),
string optParam4 = null,
double optParam5 = 128L)
{
}
}
class Middle : Base
{
//override and change the parameters names
public override void Goo(int reqChParam1,
int optChParam1 = 0,
int optChParam2 = default(int),
int optChParam3 = new int(),
string optChParam4 = null,
double optChParam5 = 128L)
{
}
}
class C : Middle
{
public void Q(params int[] x) {}
public void M()
{
var c = new C();
// calling child class parameters with base names
// error CS1739: The best overload for 'Goo' does not have a parameter named 'optParam3'
c.Goo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111);
// error CS1738: Named argument specifications must appear after all fixed arguments have been specified
c.Goo(optArg1: 3333, 11111);
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_1).VerifyDiagnostics(
// (37,15): error CS1739: The best overload for 'Goo' does not have a parameter named 'optParam3'
// c.Goo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "optParam3").WithArguments("Goo", "optParam3").WithLocation(37, 15),
// (39,30): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// c.Goo(optArg1: 3333, 11111);
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "11111").WithArguments("7.2").WithLocation(39, 30),
// (39,15): error CS1739: The best overload for 'Goo' does not have a parameter named 'optArg1'
// c.Goo(optArg1: 3333, 11111);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "optArg1").WithArguments("Goo", "optArg1").WithLocation(39, 15)
);
}
[Fact]
public void TestNamedAndOptionalParamsErrors2()
{
string source = @"
class C
{
//error CS1736
public void M(string s = new string('c',5)) {}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,30): error CS1736: Default parameter value for 's' must be a compile-time constant
// public void M(string s = new string('c',5)) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new string('c',5)").WithArguments("s").WithLocation(5, 30));
}
[Fact]
public void TestNamedAndOptionalParamsErrors3()
{
// Here we cannot report that "no overload of M takes two arguments" because of course
// M(1, 2) is legal. We cannot report that any argument does not correspond to a formal;
// all of them do. We cannot report that named arguments precede positional arguments.
// We cannot report that any argument is not convertible to its corresponding formal;
// all of them are convertible. The only error we can report here is that a formal
// parameter has no corresponding argument.
string source = @"
class C
{
// CS7036 (ERR_NoCorrespondingArgument)
delegate void F(int fx, int fg, int fz = 123);
C(int cx, int cy, int cz = 123) {}
public static void M(int mx, int my, int mz = 123)
{
F f = null;
f(0, fz : 456);
M(0, mz : 456);
new C(0, cz : 456);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (10,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'fg' of 'C.F'
// f(0, fz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "f").WithArguments("fg", "C.F").WithLocation(10, 9),
// (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'my' of 'C.M(int, int, int)'
// M(0, mz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("my", "C.M(int, int, int)").WithLocation(11, 9),
// (12,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'cy' of 'C.C(int, int, int)'
// new C(0, cz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("cy", "C.C(int, int, int)").WithLocation(12, 13));
}
[Fact]
public void TestNamedAndOptionalParamsCrazy()
{
// This was never supposed to work and the spec does not require it, but
// nevertheless, the native compiler allows this:
const string source = @"
class C
{
static void C(int q = 10, params int[] x) {}
static int X() { return 123; }
static int Q() { return 345; }
static void M()
{
C(x:X(), q:Q());
}
}";
// and so Roslyn does too. It seems likely that someone has taken a dependency
// on the bad pattern.
CreateCompilation(source).VerifyDiagnostics(
// (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type
// static void C(int q = 10, params int[] x) {}
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15));
}
[Fact]
public void TestNamedAndOptionalParamsCrazyError()
{
// Fortunately, however, this is still illegal:
const string source = @"
class C
{
static void C(int q = 10, params int[] x) {}
static void M()
{
C(1, 2, 3, x:4);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type
// static void C(int q = 10, params int[] x) {}
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15),
// (7,16): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given
// C(1, 2, 3, x:4);
Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(7, 16));
}
[Fact]
public void TestNamedAndOptionalParamsBasic()
{
string source = @"
using System;
public enum E
{
zero,
one,
two,
three
}
public enum ELong : long
{
zero,
one,
two,
three
}
public class EnumDefaultValues
{
public static void Run()
{
var x = new EnumDefaultValues();
x.M();
}
void M(
E e1 = 0,
E e2 = default(E),
E e3 = E.zero,
E e4 = E.one,
E? ne1 = 0,
E? ne2 = default(E),
E? ne3 = E.zero,
E? ne4 = E.one,
E? ne5 = null,
E? ne6 = default(E?),
ELong el1 = 0,
ELong el2 = default(ELong),
ELong el3 = ELong.zero,
ELong el4 = ELong.one,
ELong? nel1 = 0,
ELong? nel2 = default(ELong),
ELong? nel3 = ELong.zero,
ELong? nel4 = ELong.one,
ELong? nel5 = null,
ELong? nel6 = default(ELong?)
)
{
Show(e1);
Show(e2);
Show(e3);
Show(e4);
Show(ne1);
Show(ne2);
Show(ne3);
Show(ne4);
Show(ne5);
Show(ne6);
Show(el1);
Show(el2);
Show(el3);
Show(el4);
Show(nel1);
Show(nel2);
Show(nel3);
Show(nel4);
Show(nel5);
Show(nel6);
}
static void Show<T>(T t)
{
object o = t;
Console.WriteLine(""{0}: {1}"", typeof(T), o != null ? o : ""<null>"");
}
}
struct Sierra
{
public Alpha alpha;
public Bravo bravo;
public int i;
public Sierra(Alpha alpha, Bravo bravo, int i)
{
this.alpha = alpha;
this.bravo = bravo;
this.i = i;
}
}
class Alpha
{
public virtual int Mike(int xray)
{
return xray;
}
}
class Bravo : Alpha
{
public override int Mike(int yankee)
{
return yankee;
}
}
class Charlie : Bravo
{
void Foxtrot(
int xray = 10,
string yankee = ""sam"")
{
Console.WriteLine(""Foxtrot: xray={0} yankee={1}"", xray, yankee);
}
void Quebec(
int xray,
int yankee = 10,
int zulu = 11)
{
Console.WriteLine(""Quebec: xray={0} yankee={1} zulu={2}"", xray, yankee, zulu);
}
void OutRef(
out int xray,
ref int yankee)
{
xray = 0;
yankee = 0;
}
void ParamArray(params int[] xray)
{
Console.WriteLine(""ParamArray: xray={0}"", string.Join<int>("","", xray));
}
void ParamArray2(
int yankee = 10,
params int[] xray)
{
Console.WriteLine(""ParamArray2: yankee={0} xray={1}"", yankee, string.Join<int>("","", xray));
}
void Zeros(
int xray = 0,
int? yankee = 0,
int? zulu = null,
Charlie charlie = null)
{
Console.WriteLine(""Zeros: xray={0} yankee={1} zulu={2} charlie={3}"",
xray,
yankee == null ? ""null"" : yankee.ToString(),
zulu == null ? ""null"" : zulu.ToString(),
charlie == null ? ""null"" : charlie.ToString() );
}
void OtherDefaults(
string str = default(string),
Alpha alpha = default(Alpha),
Bravo bravo = default(Bravo),
int i = default(int),
Sierra sierra = default(Sierra))
{
Console.WriteLine(""OtherDefaults: str={0} alpha={1} bravo={2} i={3} sierra={4}"",
str == null ? ""null"" : str,
alpha == null ? ""null"" : alpha.ToString(),
bravo == null ? ""null"" : bravo.ToString(),
i,
sierra.alpha == null && sierra.bravo == null && sierra.i == 0 ? ""default(Sierra)"" : sierra.ToString());
}
int Bar()
{
Console.WriteLine(""Bar"");
return 96;
}
string Baz()
{
Console.WriteLine(""Baz"");
return ""Baz"";
}
void BasicOptionalTests()
{
Console.WriteLine(""BasicOptional"");
Foxtrot(0);
Foxtrot();
ParamArray(1, 2, 3);
Zeros();
OtherDefaults();
}
void BasicNamedTests()
{
Console.WriteLine(""BasicNamed"");
// Basic named test.
Foxtrot(yankee: ""test"", xray: 1);
Foxtrot(xray: 1, yankee: ""test"");
// Test to see which execution comes first.
Foxtrot(yankee: Baz(), xray: Bar());
int y = 100;
int x = 100;
OutRef(yankee: ref y, xray: out x);
Console.WriteLine(x);
Console.WriteLine(y);
Charlie c = new Charlie();
ParamArray(xray: 1);
ParamArray(xray: new int[] { 1, 2, 3 });
ParamArray2(xray: 1);
ParamArray2(xray: new int[] { 1, 2, 3 });
ParamArray2(xray: 1, yankee: 20);
ParamArray2(xray: new int[] { 1, 2, 3 }, yankee: 20);
ParamArray2();
}
void BasicNamedAndOptionalTests()
{
Console.WriteLine(""BasicNamedAndOptional"");
Foxtrot(yankee: ""test"");
Foxtrot(xray: 0);
Quebec(1, yankee: 1);
Quebec(1, zulu: 10);
}
void OverrideTest()
{
Console.WriteLine(Mike(yankee: 10));
}
void TypeParamTest<T>() where T : Bravo, new()
{
T t = new T();
Console.WriteLine(t.Mike(yankee: 4));
}
static void Main()
{
Charlie c = new Charlie();
c.BasicOptionalTests();
c.BasicNamedTests();
c.BasicNamedAndOptionalTests();
c.OverrideTest();
c.TypeParamTest<Bravo>();
EnumDefaultValues.Run();
}
}
";
string expected = @"BasicOptional
Foxtrot: xray=0 yankee=sam
Foxtrot: xray=10 yankee=sam
ParamArray: xray=1,2,3
Zeros: xray=0 yankee=0 zulu=null charlie=null
OtherDefaults: str=null alpha=null bravo=null i=0 sierra=default(Sierra)
BasicNamed
Foxtrot: xray=1 yankee=test
Foxtrot: xray=1 yankee=test
Baz
Bar
Foxtrot: xray=96 yankee=Baz
0
0
ParamArray: xray=1
ParamArray: xray=1,2,3
ParamArray2: yankee=10 xray=1
ParamArray2: yankee=10 xray=1,2,3
ParamArray2: yankee=20 xray=1
ParamArray2: yankee=20 xray=1,2,3
ParamArray2: yankee=10 xray=
BasicNamedAndOptional
Foxtrot: xray=10 yankee=test
Foxtrot: xray=0 yankee=sam
Quebec: xray=1 yankee=1 zulu=11
Quebec: xray=1 yankee=10 zulu=10
10
4
E: zero
E: zero
E: zero
E: one
System.Nullable`1[E]: zero
System.Nullable`1[E]: zero
System.Nullable`1[E]: zero
System.Nullable`1[E]: one
System.Nullable`1[E]: <null>
System.Nullable`1[E]: <null>
ELong: zero
ELong: zero
ELong: zero
ELong: one
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: one
System.Nullable`1[ELong]: <null>
System.Nullable`1[ELong]: <null>";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnAttributes()
{
string source = @"
using System;
class MyAttribute : Attribute
{
public MyAttribute(int a = 1, int b = 2, int c = 3)
{
A = a;
B = b;
C = c;
}
public int X;
public int A;
public int B;
public int C;
}
[MyAttribute(4, c:5, X=6)]
class C
{
static void Main()
{
MyAttribute m1 = new MyAttribute();
Console.Write(m1.A); // 1
Console.Write(m1.B); // 2
Console.Write(m1.C); // 3
Console.Write(m1.X); // 0
MyAttribute m2 = new MyAttribute(c: 7);
Console.Write(m2.A); // 1
Console.Write(m2.B); // 2
Console.Write(m2.C); // 7
Console.Write(m2.X); // 0
Type t = typeof(C);
foreach (MyAttribute attr in t.GetCustomAttributes(false))
{
Console.Write(attr.A); // 4
Console.Write(attr.B); // 2
Console.Write(attr.C); // 5
Console.Write(attr.X); // 6
}
}
}";
CompileAndVerify(source, expectedOutput: "123012704256");
}
[Fact]
public void TestNamedAndOptionalParamsOnIndexers()
{
string source = @"
using System;
class D
{
public int this[string s = ""four""] { get { return s.Length; } set { } }
public int this[int x = 2, int y = 5] { get { return x + y; } set { } }
public int this[string str = ""goo"", int i = 13]
{
get { Console.WriteLine(""D.this[str: '{0}', i: {1}].get"", str, i); return i;}
set { Console.WriteLine(""D.this[str: '{0}', i: {1}].set"", str, i); }
}
}
class C
{
int this[int x, int y] { get { return x + y; } set { } }
static void Main()
{
C c = new C();
Console.WriteLine(c[y:10, x:10]);
D d = new D();
Console.WriteLine(d[1]);
Console.WriteLine(d[0,2]);
Console.WriteLine(d[x:2]);
Console.WriteLine(d[x:3, y:0]);
Console.WriteLine(d[y:3, x:2]);
Console.WriteLine(d[""abc""]);
Console.WriteLine(d[s:""12345""]);
d[i:1] = 0;
d[str:""bar""] = 0;
d[i:2, str:""baz""] = 0;
d[str:""bah"", i:3] = 0;
}
}";
string expected = @"20
6
2
7
3
5
3
5
D.this[str: 'goo', i: 1].set
D.this[str: 'bar', i: 13].set
D.this[str: 'baz', i: 2].set
D.this[str: 'bah', i: 3].set";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnPartialMethods()
{
string source = @"
using System;
partial class C
{
static partial void PartialMethod(int x);
}
partial class C
{
static partial void PartialMethod(int y) { Console.WriteLine(y); }
static void Main()
{
// Declaring partial wins.
PartialMethod(x:123);
}
}";
string expected = "123";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnPartialMethodsErrors()
{
string source = @"
using System;
partial class C
{
static partial void PartialMethod(int x);
}
partial class C
{
static partial void PartialMethod(int y) { Console.WriteLine(y); }
static void Main()
{
// Implementing partial loses.
PartialMethod(y:123);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,25): warning CS8826: Partial method declarations 'void C.PartialMethod(int x)' and 'void C.PartialMethod(int y)' have signature differences.
// static partial void PartialMethod(int y) { Console.WriteLine(y); }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "PartialMethod").WithArguments("void C.PartialMethod(int x)", "void C.PartialMethod(int y)").WithLocation(9, 25),
// (13,23): error CS1739: The best overload for 'PartialMethod' does not have a parameter named 'y'
// PartialMethod(y:123);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "y").WithArguments("PartialMethod", "y").WithLocation(13, 23)
);
}
[Fact]
public void TestNamedAndOptionalParametersUnsafe()
{
string source = @"
using System;
unsafe class C
{
static void M(
int* x1 = default(int*),
IntPtr x2 = default(IntPtr),
UIntPtr x3 = default(UIntPtr),
int x4 = default(int))
{
}
static void Main()
{
M();
}
}";
// We make an improvement on the native compiler here; we generate default(UIntPtr) and
// default(IntPtr) as "load zero, convert to type", rather than making a stack slot and calling
// init on it.
var c = CompileAndVerify(source, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
c.VerifyIL("C.Main", @"{
// Code size 13 (0xd)
.maxstack 4
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: ldc.i4.0
IL_0003: conv.i
IL_0004: ldc.i4.0
IL_0005: conv.u
IL_0006: ldc.i4.0
IL_0007: call ""void C.M(int*, System.IntPtr, System.UIntPtr, int)""
IL_000c: ret
}");
}
[WorkItem(528783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528783")]
[Fact]
public void TestNamedAndOptionalParametersArgumentName()
{
const string text = @"
using System;
namespace NS
{
class Test
{
static void M(sbyte sb = 0, string ss = null) {}
static void Main()
{
M(/*<bind>*/ss/*</bind>*/: ""QC"");
}
}
}
";
var comp = CreateCompilation(text);
var nodeAndModel = GetBindingNodeAndModel<IdentifierNameSyntax>(comp);
var typeInfo = nodeAndModel.Item2.GetTypeInfo(nodeAndModel.Item1);
// parameter name has no type
Assert.Null(typeInfo.Type);
var symInfo = nodeAndModel.Item2.GetSymbolInfo(nodeAndModel.Item1);
Assert.NotNull(symInfo.Symbol);
Assert.Equal(SymbolKind.Parameter, symInfo.Symbol.Kind);
Assert.Equal("ss", symInfo.Symbol.Name);
}
[WorkItem(542418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542418")]
[Fact]
public void OptionalValueInvokesInstanceMethod()
{
var source =
@"class C
{
object F() { return null; }
void M1(object value = F()) { }
object M2(object value = M2()) { return null; }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,28): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 28),
// (5,30): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 30));
}
[Fact]
public void OptionalValueInvokesStaticMethod()
{
var source =
@"class C
{
static object F() { return null; }
static void M1(object value = F()) { }
static object M2(object value = M2()) { return null; }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,35): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 35),
// (5,37): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 37));
}
[WorkItem(11638, "https://github.com/dotnet/roslyn/issues/11638")]
[Fact]
public void OptionalValueHasObjectInitializer()
{
var source =
@"class C
{
static void Test(Vector3 vector = new Vector3() { X = 1f, Y = 1f, Z = 1f}) { }
}
public struct Vector3
{
public float X;
public float Y;
public float Z;
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,39): error CS1736: Default parameter value for 'vector' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new Vector3() { X = 1f, Y = 1f, Z = 1f}").WithArguments("vector").WithLocation(3, 39));
}
[WorkItem(542411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542411")]
[WorkItem(542365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542365")]
[Fact]
public void GenericOptionalParameters()
{
var source =
@"class C
{
static void Goo<T>(T t = default(T)) {}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(542458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542458")]
[Fact]
public void OptionalValueTypeFromReferencedAssembly()
{
// public struct S{}
// public class C
// {
// public static void Goo(string s, S t = default(S)) {}
// }
string ilSource = @"
// =============== CLASS MEMBERS DECLARATION ===================
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
} // end of class S
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig static void Goo(string s,
[opt] valuetype S t) cil managed
{
.param [2] = nullref
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::Goo
} // end of class C
";
var source =
@"
public class D
{
public static void Caller()
{
C.Goo("""");
}
}";
CompileWithCustomILSource(source, ilSource);
}
[WorkItem(542867, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542867")]
[Fact]
public void OptionalParameterDeclaredWithAttributes()
{
string source = @"
using System.Runtime.InteropServices;
public class Parent{
public int Goo([Optional]object i = null) {
return 1;
}
public int Bar([DefaultParameterValue(1)]int i = 2) {
return 1;
}
}
class Test{
public static int Main(){
Parent p = new Parent();
return p.Goo();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
// public int Bar([DefaultParameterValue(1)]int i = 2) {
Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "DefaultParameterValue").WithLocation(9, 21),
// (9,54): error CS8017: The parameter has multiple distinct default values.
// public int Bar([DefaultParameterValue(1)]int i = 2) {
Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "2").WithLocation(9, 54),
// (5,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
// public int Goo([Optional]object i = null) {
Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "Optional").WithLocation(5, 21)
);
}
[WorkItem(10290, "DevDiv_Projects/Roslyn")]
[Fact]
public void OptionalParamOfTypeObject()
{
string source = @"
public class Test
{
public static int M1(object p1 = null) { if (p1 == null) return 0; else return 1; }
public static void Main()
{
System.Console.WriteLine(M1());
}
}
";
CompileAndVerify(source, expectedOutput: "0");
}
[WorkItem(543871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543871")]
[Fact]
public void RefParameterDeclaredWithOptionalAttribute()
{
// The native compiler produces "CS1501: No overload for method 'Goo' takes 0 arguments."
// Roslyn produces a slightly more informative error message.
string source = @"
using System.Runtime.InteropServices;
public class Parent
{
public static void Goo([Optional] ref int x) {}
static void Main()
{
Goo();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Parent.Goo(ref int)'
// Goo();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Goo").WithArguments("x", "Parent.Goo(ref int)"));
}
[Fact, WorkItem(544491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544491")]
public void EnumAsDefaultParameterValue()
{
string source = @"
using System.Runtime.InteropServices;
public enum MyEnum { one, two, three }
public interface IOptionalRef
{
MyEnum MethodRef([In, Out, Optional, DefaultParameterValue(MyEnum.three)] ref MyEnum v);
}
";
CompileAndVerify(source).VerifyDiagnostics();
}
[Fact]
public void DefaultParameterValueErrors()
{
string source = @"
using System.Runtime.InteropServices;
public enum I8 : sbyte { v = 1 }
public enum U8 : byte { v = 1 }
public enum I16 : short { v = 1 }
public enum U16 : ushort { v = 1 }
public enum I32 : int { v = 1 }
public enum U32 : uint { v = 1 }
public enum I64 : long { v = 1 }
public enum U64 : ulong { v = 1 }
public class C { }
public delegate void D();
public interface I { }
public struct S {
}
public static class ErrorCases
{
public static void M(
// bool
[Optional][DefaultParameterValue(0)] bool b1,
[Optional][DefaultParameterValue(""hello"")] bool b2,
// integral
[Optional][DefaultParameterValue(12)] sbyte sb1,
[Optional][DefaultParameterValue(""hello"")] byte by1,
// char
[Optional][DefaultParameterValue(""c"")] char ch1,
// float
[Optional][DefaultParameterValue(1.0)] float fl1,
[Optional][DefaultParameterValue(1)] double dbl1,
// enum
[Optional][DefaultParameterValue(0)] I8 i8,
[Optional][DefaultParameterValue(12)] U8 u8,
[Optional][DefaultParameterValue(""hello"")] I16 i16,
// string
[Optional][DefaultParameterValue(5)] string str1,
[Optional][DefaultParameterValue(new int[] { 12 })] string str2,
// reference types
[Optional][DefaultParameterValue(2)] C c1,
[Optional][DefaultParameterValue(""hello"")] C c2,
[DefaultParameterValue(new int[] { 1, 2 })] int[] arr1,
[DefaultParameterValue(null)] int[] arr2,
[DefaultParameterValue(new int[] { 1, 2 })] object arr3,
[DefaultParameterValue(typeof(object))] System.Type type1,
[DefaultParameterValue(null)] System.Type type2,
[DefaultParameterValue(typeof(object))] object type3,
// user defined struct
[DefaultParameterValue(null)] S userStruct1,
[DefaultParameterValue(0)] S userStruct2,
[DefaultParameterValue(""hel"")] S userStruct3,
// null value to non-ref type
[Optional][DefaultParameterValue(null)] bool b3,
// integral
[Optional][DefaultParameterValue(null)] int i2,
// char
[Optional][DefaultParameterValue(null)] char ch2,
// float
[Optional][DefaultParameterValue(null)] float fl2,
// enum
[Optional][DefaultParameterValue(null)] I8 i82
)
{
}
}
";
// NOTE: anywhere dev10 reported CS1909, roslyn reports CS1910.
CreateCompilation(source).VerifyDiagnostics(
// (27,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(0)] bool b1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (28,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] bool b2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (31,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(12)] sbyte sb1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (32,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] byte by1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (35,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("c")] char ch1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (38,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(1.0)] float fl1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (42,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(0)] I8 i8,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (43,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(12)] U8 u8,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (44,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] I16 i16,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (47,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(5)] string str1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (48,20): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [Optional][DefaultParameterValue(new int[] { 12 })] string str2,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// (51,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(2)] C c1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (52,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] C c2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (54,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(new int[] { 1, 2 })] int[] arr1,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// NOTE: Roslyn specifically allows this usage (illegal in dev10).
//// (55,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'int[]', unless the default value is null
//// [DefaultParameterValue(null)] int[] arr2,
//Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("int[]"),
// (56,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(new int[] { 1, 2 })] object arr3,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// (58,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(typeof(object))] System.Type type1,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"),
// NOTE: Roslyn specifically allows this usage (illegal in dev10).
//// (59,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'System.Type', unless the default value is null
//// [DefaultParameterValue(null)] System.Type type2,
//Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("System.Type"),
// (60,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(typeof(object))] object type3,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"),
// (63,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue(null)] S userStruct1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (64,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue(0)] S userStruct2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (65,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue("hel")] S userStruct3,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (68,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] bool b3,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (71,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] int i2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (74,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] char ch2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (77,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] float fl2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (80,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] I8 i82
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"));
}
[WorkItem(544440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544440")]
[ConditionalFact(typeof(DesktopOnly))]
public void TestBug12768()
{
string sourceDefinitions = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public class C
{
public static void M1(object x = null)
{
Console.WriteLine(x ?? 1);
}
public static void M2([Optional] object x)
{
Console.WriteLine(x ?? 2);
}
public static void M3([MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 3);
}
public static void M4([MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 4);
}
public static void M5([IDispatchConstant] object x = null)
{
Console.WriteLine(x ?? 5);
}
public static void M6([IDispatchConstant] [Optional] object x)
{
Console.WriteLine(x ?? 6);
}
public static void M7([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 7);
}
public static void M8([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 8);
}
public static void M9([IUnknownConstant]object x = null)
{
Console.WriteLine(x ?? 9);
}
public static void M10([IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 10);
}
public static void M11([IUnknownConstant][MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 11);
}
public static void M12([IUnknownConstant][MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 12);
}
public static void M13([IUnknownConstant][IDispatchConstant] object x = null)
{
Console.WriteLine(x ?? 13);
}
public static void M14([IDispatchConstant][IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 14);
}
public static void M15([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 15);
}
public static void M16([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 16);
}
public static void M17([MarshalAs(UnmanagedType.Interface)][IDispatchConstant][Optional] object x)
{
Console.WriteLine(x ?? 17);
}
public static void M18([MarshalAs(UnmanagedType.Interface)][IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 18);
}
}
";
string sourceCalls = @"
internal class D
{
static void Main()
{
C.M1(); // null
C.M2(); // Missing
C.M3(); // null
C.M4(); // null
C.M5(); // null
C.M6(); // DispatchWrapper
C.M7(); // null
C.M8(); // null
C.M9(); // null
C.M10(); // UnknownWrapper
C.M11(); // null
C.M12(); // null
C.M13(); // null
C.M14(); // UnknownWrapper
C.M15(); // null
C.M16(); // null
C.M17(); // null
C.M18(); // null
}
}";
string expected = @"1
System.Reflection.Missing
3
4
5
System.Runtime.InteropServices.DispatchWrapper
7
8
9
System.Runtime.InteropServices.UnknownWrapper
11
12
13
System.Runtime.InteropServices.UnknownWrapper
15
16
17
18";
// definitions in source:
var verifier = CompileAndVerify(new[] { sourceDefinitions, sourceCalls }, expectedOutput: expected);
// definitions in metadata:
using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData))
{
CompileAndVerify(new[] { sourceCalls }, new[] { assembly.GetReference() }, expectedOutput: expected);
}
}
[ConditionalFact(typeof(DesktopOnly))]
public void IUnknownConstant_MissingType()
{
var source = @"
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
class C
{
static void M0([Optional, MarshalAs(UnmanagedType.Interface)] object param) { }
static void M1([Optional, IUnknownConstant] object param) { }
static void M2([Optional, IDispatchConstant] object param) { }
static void M3([Optional] object param) { }
static void M()
{
M0();
M1();
M2();
M3();
}
}
";
CompileAndVerify(source).VerifyDiagnostics();
var comp = CreateCompilation(source);
comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor);
comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor);
comp.MakeMemberMissing(WellKnownMember.System_Type__Missing);
comp.VerifyDiagnostics(
// (15,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.UnknownWrapper..ctor'
// M1();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M1()").WithArguments("System.Runtime.InteropServices.UnknownWrapper", ".ctor").WithLocation(15, 9),
// (16,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.DispatchWrapper..ctor'
// M2();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M2()").WithArguments("System.Runtime.InteropServices.DispatchWrapper", ".ctor").WithLocation(16, 9),
// (17,9): error CS0656: Missing compiler required member 'System.Type.Missing'
// M3();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M3()").WithArguments("System.Type", "Missing").WithLocation(17, 9));
}
[WorkItem(545329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545329")]
[Fact()]
public void ComOptionalRefParameter()
{
string source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020813-0000-0000-c000-000000000046"")]
interface ComClass
{
void M([Optional]ref object o);
}
class D : ComClass
{
public void M(ref object o)
{
}
}
class C
{
static void Main()
{
D d = new D();
ComClass c = d;
c.M(); //fine
d.M(); //CS1501
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (25,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'D.M(ref object)'
// d.M(); //CS1501
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "D.M(ref object)").WithLocation(25, 11));
}
[WorkItem(545337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545337")]
[ClrOnlyFact]
public void TestVbDecimalAndDateTimeDefaultParameters()
{
var vb = @"
Imports System
public Module VBModule
Sub I(Optional ByVal x As System.Int32 = 456)
Console.WriteLine(x)
End Sub
Sub NI(Optional ByVal x As System.Int32? = 457)
Console.WriteLine(x)
End Sub
Sub OI(Optional ByVal x As Object = 458 )
Console.WriteLine(x)
End Sub
Sub DA(Optional ByVal x As DateTime = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub NDT(Optional ByVal x As DateTime? = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub ODT(Optional ByVal x As Object = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub Dec(Optional ByVal x as Decimal = 12.3D)
Console.WriteLine(x.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub NDec(Optional ByVal x as Decimal? = 12.4D)
Console.WriteLine(x.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub ODec(Optional ByVal x as Object = 12.5D)
Console.WriteLine(DirectCast(x, Decimal).ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
";
var csharp = @"
using System;
public class D
{
static void Main()
{
// Ensure suites run in invariant culture across machines
System.Threading.Thread.CurrentThread.CurrentCulture
= System.Globalization.CultureInfo.InvariantCulture;
// Possible in both C# and VB:
VBModule.I();
VBModule.NI();
VBModule.Dec();
VBModule.NDec();
// Not possible in C#, possible in VB, but C# honours the parameter:
VBModule.OI();
VBModule.ODec();
VBModule.DA();
VBModule.NDT();
VBModule.ODT();
}
}
";
string expected = @"456
457
12.3
12.4
458
12.5
True
True
True";
string il = @"{
// Code size 181 (0xb5)
.maxstack 5
IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get""
IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get""
IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set""
IL_000f: ldc.i4 0x1c8
IL_0014: call ""void VBModule.I(int)""
IL_0019: ldc.i4 0x1c9
IL_001e: newobj ""int?..ctor(int)""
IL_0023: call ""void VBModule.NI(int?)""
IL_0028: ldc.i4.s 123
IL_002a: ldc.i4.0
IL_002b: ldc.i4.0
IL_002c: ldc.i4.0
IL_002d: ldc.i4.1
IL_002e: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0033: call ""void VBModule.Dec(decimal)""
IL_0038: ldc.i4.s 124
IL_003a: ldc.i4.0
IL_003b: ldc.i4.0
IL_003c: ldc.i4.0
IL_003d: ldc.i4.1
IL_003e: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0043: newobj ""decimal?..ctor(decimal)""
IL_0048: call ""void VBModule.NDec(decimal?)""
IL_004d: ldc.i4 0x1ca
IL_0052: box ""int""
IL_0057: call ""void VBModule.OI(object)""
IL_005c: ldc.i4.s 125
IL_005e: ldc.i4.0
IL_005f: ldc.i4.0
IL_0060: ldc.i4.0
IL_0061: ldc.i4.1
IL_0062: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0067: box ""decimal""
IL_006c: call ""void VBModule.ODec(object)""
IL_0071: ldc.i8 0x8c8fc181490c000
IL_007a: newobj ""System.DateTime..ctor(long)""
IL_007f: call ""void VBModule.DA(System.DateTime)""
IL_0084: ldc.i8 0x8c8fc181490c000
IL_008d: newobj ""System.DateTime..ctor(long)""
IL_0092: newobj ""System.DateTime?..ctor(System.DateTime)""
IL_0097: call ""void VBModule.NDT(System.DateTime?)""
IL_009c: ldc.i8 0x8c8fc181490c000
IL_00a5: newobj ""System.DateTime..ctor(long)""
IL_00aa: box ""System.DateTime""
IL_00af: call ""void VBModule.ODT(object)""
IL_00b4: ret
}";
var vbCompilation = CreateVisualBasicCompilation("VB", vb,
compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
vbCompilation.VerifyDiagnostics();
var csharpCompilation = CreateCSharpCompilation("CS", csharp,
compilationOptions: TestOptions.ReleaseExe,
referencedCompilations: new[] { vbCompilation });
var verifier = CompileAndVerify(csharpCompilation, expectedOutput: expected);
verifier.VerifyIL("D.Main", il);
}
[WorkItem(545337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545337")]
[Fact]
public void TestCSharpDecimalAndDateTimeDefaultParameters()
{
var library = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public enum E
{
one,
two,
three
}
public class C
{
public void Goo(
[Optional][DateTimeConstant(100000)]DateTime dateTime,
decimal dec = 12345678901234567890m,
int? x = 0,
int? q = null,
short y = 10,
int z = default(int),
S? s = null)
//S? s2 = default(S))
{
if (dateTime == new DateTime(100000))
{
Console.WriteLine(""DatesMatch"");
}
else
{
Console.WriteLine(""Dates dont match!!"");
}
Write(dec);
Write(x);
Write(q);
Write(y);
Write(z);
Write(s);
//Write(s2);
}
public void Bar(S? s1, S? s2, S? s3)
{
}
public void Baz(E? e1 = E.one, long? x = 0)
{
if (e1.HasValue)
{
Console.WriteLine(e1);
}
else
{
Console.WriteLine(""null"");
}
Console.WriteLine(x);
}
public void Write(object o)
{
if (o == null)
{
Console.WriteLine(""null"");
}
else
{
Console.WriteLine(o);
}
}
}
public struct S
{
}
";
var main = @"
using System;
public class D
{
static void Main()
{
// Ensure suites run in invariant culture across machines
System.Threading.Thread.CurrentThread.CurrentCulture
= System.Globalization.CultureInfo.InvariantCulture;
C c = new C();
c.Goo();
c.Baz();
}
}
";
var libComp = CreateCompilation(library, options: TestOptions.ReleaseDll, assemblyName: "Library");
libComp.VerifyDiagnostics();
var exeComp = CreateCompilation(main, new[] { new CSharpCompilationReference(libComp) }, options: TestOptions.ReleaseExe, assemblyName: "Main");
var verifier = CompileAndVerify(exeComp, expectedOutput: @"DatesMatch
12345678901234567890
0
null
10
0
null
one
0");
verifier.VerifyIL("D.Main", @"{
// Code size 97 (0x61)
.maxstack 9
.locals init (int? V_0,
S? V_1)
IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get""
IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get""
IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set""
IL_000f: newobj ""C..ctor()""
IL_0014: dup
IL_0015: ldc.i4 0x186a0
IL_001a: conv.i8
IL_001b: newobj ""System.DateTime..ctor(long)""
IL_0020: ldc.i8 0xab54a98ceb1f0ad2
IL_0029: newobj ""decimal..ctor(ulong)""
IL_002e: ldc.i4.0
IL_002f: newobj ""int?..ctor(int)""
IL_0034: ldloca.s V_0
IL_0036: initobj ""int?""
IL_003c: ldloc.0
IL_003d: ldc.i4.s 10
IL_003f: ldc.i4.0
IL_0040: ldloca.s V_1
IL_0042: initobj ""S?""
IL_0048: ldloc.1
IL_0049: callvirt ""void C.Goo(System.DateTime, decimal, int?, int?, short, int, S?)""
IL_004e: ldc.i4.0
IL_004f: newobj ""E?..ctor(E)""
IL_0054: ldc.i4.0
IL_0055: conv.i8
IL_0056: newobj ""long?..ctor(long)""
IL_005b: callvirt ""void C.Baz(E?, long?)""
IL_0060: ret
}");
}
[Fact]
public void OmittedComOutParameter()
{
// We allow omitting optional ref arguments but not optional out arguments.
var source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""989FE455-5A6D-4D05-A349-1A221DA05FDA"")]
interface I
{
void M([Optional]out object o);
}
class P
{
static void Q(I i) { i.M(); }
}
";
// Note that the native compiler gives a slightly less informative error message here.
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,26): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'I.M(out object)'
// static void Q(I i) { i.M(); }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "I.M(out object)")
);
}
[Fact]
public void OmittedComRefParameter()
{
var source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""A8FAF53B-F502-4465-9429-CAB2A19B47BE"")]
interface ICom
{
void M(out int w, int x, [Optional]ref object o, int z = 0);
}
class Com : ICom
{
public void M(out int w, int x, ref object o, int z)
{
w = 123;
Console.WriteLine(x);
if (o != null)
{
Console.WriteLine(o.GetType());
}
else
{
Console.WriteLine(""null"");
}
Console.WriteLine(z);
}
static void Main()
{
ICom c = new Com();
int q;
c.M(w: out q, z: 10, x: 100);
Console.WriteLine(q);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"
100
System.Reflection.Missing
10
123");
verifier.VerifyIL("Com.Main", @"
{
// Code size 31 (0x1f)
.maxstack 5
.locals init (int V_0, //q
object V_1)
IL_0000: newobj ""Com..ctor()""
IL_0005: ldloca.s V_0
IL_0007: ldc.i4.s 100
IL_0009: ldsfld ""object System.Type.Missing""
IL_000e: stloc.1
IL_000f: ldloca.s V_1
IL_0011: ldc.i4.s 10
IL_0013: callvirt ""void ICom.M(out int, int, ref object, int)""
IL_0018: ldloc.0
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ret
}");
}
[Fact]
public void ArrayElementComRefParameter()
{
var source =
@"using System;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")]
interface IA
{
void M(ref int i);
}
class A : IA
{
void IA.M(ref int i)
{
i += 2;
}
}
class B
{
static void M(IA a)
{
a.M(F()[0]);
}
static void MByRef(IA a)
{
a.M(ref F()[0]);
}
static int[] i = { 0 };
static int[] F()
{
Console.WriteLine(""F()"");
return i;
}
static void Main()
{
IA a = new A();
M(a);
ReportAndReset();
MByRef(a);
ReportAndReset();
}
static void ReportAndReset()
{
Console.WriteLine(""{0}"", i[0]);
i = new[] { 0 };
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"F()
0
F()
2");
verifier.VerifyIL("B.M(IA)",
@"{
// Code size 17 (0x11)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: call ""int[] B.F()""
IL_0006: ldc.i4.0
IL_0007: ldelem.i4
IL_0008: stloc.0
IL_0009: ldloca.s V_0
IL_000b: callvirt ""void IA.M(ref int)""
IL_0010: ret
}");
verifier.VerifyIL("B.MByRef(IA)",
@"{
// Code size 18 (0x12)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int[] B.F()""
IL_0006: ldc.i4.0
IL_0007: ldelema ""int""
IL_000c: callvirt ""void IA.M(ref int)""
IL_0011: ret
}");
}
[Fact]
public void ArrayElementComRefParametersReordered()
{
var source =
@"using System;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")]
interface IA
{
void M(ref int x, ref int y);
}
class A : IA
{
void IA.M(ref int x, ref int y)
{
x += 2;
y += 3;
}
}
class B
{
static void M(IA a)
{
a.M(y: ref F2()[0], x: ref F1()[0]);
}
static int[] i1 = { 0 };
static int[] i2 = { 0 };
static int[] F1()
{
Console.WriteLine(""F1()"");
return i1;
}
static int[] F2()
{
Console.WriteLine(""F2()"");
return i2;
}
static void Main()
{
IA a = new A();
M(a);
Console.WriteLine(""{0}, {1}"", i1[0], i2[0]);
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"F2()
F1()
2, 3
");
verifier.VerifyIL("B.M(IA)",
@"{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int& V_0)
IL_0000: ldarg.0
IL_0001: call ""int[] B.F2()""
IL_0006: ldc.i4.0
IL_0007: ldelema ""int""
IL_000c: stloc.0
IL_000d: call ""int[] B.F1()""
IL_0012: ldc.i4.0
IL_0013: ldelema ""int""
IL_0018: ldloc.0
IL_0019: callvirt ""void IA.M(ref int, ref int)""
IL_001e: ret
}");
}
[Fact]
[WorkItem(546713, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546713")]
public void Test16631()
{
var source =
@"
public abstract class B
{
protected abstract void E<T>();
}
public class D : B
{
void M()
{
// There are two possible methods to choose here. The static method
// is better because it is declared in a more derived class; the
// virtual method is better because it has exactly the right number
// of parameters. In this case, the static method wins. The virtual
// method is to be treated as though it was a method of the base class,
// and therefore automatically loses. (The bug we are regressing here
// is that Roslyn did not correctly identify the originally-defining
// type B when the method E was generic. The original repro scenario in
// bug 16631 was much more complicated than this, but it boiled down to
// overload resolution choosing the wrong method.)
E<int>();
}
protected override void E<T>()
{
System.Console.WriteLine(1);
}
static void E<T>(int x = 0xBEEF)
{
System.Console.WriteLine(2);
}
static void Main()
{
(new D()).M();
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "2");
verifier.VerifyIL("D.M()",
@"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldc.i4 0xbeef
IL_0005: call ""void D.E<int>(int)""
IL_000a: ret
}");
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_PrimitiveStruct()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(int p) { }
public void M1(int p = 0) { } // default of type
public void M2(int p = 1) { } // not default of type
public void M3([Optional]int p) { } // no default specified (would be illegal)
public void M4([DefaultParameterValue(0)]int p) { } // default of type, not optional
public void M5([DefaultParameterValue(1)]int p) { } // not default of type, not optional
public void M6([Optional][DefaultParameterValue(0)]int p) { } // default of type, optional
public void M7([Optional][DefaultParameterValue(1)]int p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Equal(0, parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0), parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal(1, parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.True(parameters[4].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create(0), parameters[4].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length);
Assert.False(parameters[5].IsOptional);
Assert.False(parameters[5].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue);
Assert.True(parameters[5].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create(1), parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[5].GetAttributes().Length);
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(0, parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length);
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal(1, parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1), parameters[7].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length);
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_UserDefinedStruct()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(S p) { }
public void M1(S p = default(S)) { }
public void M2([Optional]S p) { } // no default specified (would be illegal)
}
public struct S
{
public int x;
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(3, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.False(parameters[2].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue);
Assert.Null(parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length);
};
// TODO: RefEmit doesn't emit the default value of M1's parameter.
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_String()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(string p) { }
public void M1(string p = null) { }
public void M2(string p = ""A"") { }
public void M3([Optional]string p) { } // no default specified (would be illegal)
public void M4([DefaultParameterValue(null)]string p) { }
public void M5([Optional][DefaultParameterValue(null)]string p) { }
public void M6([DefaultParameterValue(""A"")]string p) { }
public void M7([Optional][DefaultParameterValue(""A"")]string p) { }
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal("A", parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create("A"), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.True(parameters[4].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Null, parameters[4].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length);
Assert.True(parameters[5].IsOptional);
Assert.True(parameters[5].HasExplicitDefaultValue);
Assert.Null(parameters[5].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length);
Assert.False(parameters[6].IsOptional);
Assert.False(parameters[6].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[6].ExplicitDefaultValue);
Assert.True(parameters[6].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create("A"), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[6].GetAttributes().Length);
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal("A", parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create("A"), parameters[7].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length);
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_Decimal()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
public void M0(decimal p) { }
public void M1(decimal p = 0) { } // default of type
public void M2(decimal p = 1) { } // not default of type
public void M3([Optional]decimal p) { } // no default specified (would be illegal)
public void M4([DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, not optional
public void M5([DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, not optional
public void M6([Optional][DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, optional
public void M7([Optional][DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Equal(0M, parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0M), parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal(1M, parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1M), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.False(parameters[4].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(0M) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[4].GetAttributes().Length); // DecimalConstantAttribute
Assert.False(parameters[5].IsOptional);
Assert.False(parameters[5].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue);
Assert.False(parameters[5].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(1M) : null, parameters[5].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[5].GetAttributes().Length); // DecimalConstantAttribute
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(0M, parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0M), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal(1M, parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1M), parameters[7].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_DateTime()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
public void M0(DateTime p) { }
public void M1(DateTime p = default(DateTime)) { }
public void M2([Optional]DateTime p) { } // no default specified (would be illegal)
public void M3([DateTimeConstant(0)]DateTime p) { } // default of type, not optional
public void M4([DateTimeConstant(1)]DateTime p) { } // not default of type, not optional
public void M5([Optional][DateTimeConstant(0)]DateTime p) { } // default of type, optional
public void M6([Optional][DateTimeConstant(1)]DateTime p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(7, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length); // As in dev11, [DateTimeConstant] is not emitted in this case.
Assert.True(parameters[2].IsOptional);
Assert.False(parameters[2].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue);
Assert.Null(parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length);
Assert.False(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.False(parameters[3].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(0)) : null, parameters[3].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[3].GetAttributes().Length); // DateTimeConstant
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.False(parameters[4].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(1)) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[4].GetAttributes().Length); // DateTimeConstant
Assert.True(parameters[5].IsOptional);
Assert.True(parameters[5].HasExplicitDefaultValue);
Assert.Equal(new DateTime(0), parameters[5].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(new DateTime(0)), parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(new DateTime(1), parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(new DateTime(1)), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant
};
// TODO: Guess - RefEmit doesn't like DateTime constants.
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void InvalidConversionForDefaultArgument_InIL()
{
var il = @"
.class public auto ansi beforefieldinit P
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method P::.ctor
.method public hidebysig instance int32 M1([opt] int32 s) cil managed
{
.param [1] = ""abc""
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldarg.1
IL_0001: ret
} // end of method P::M1
} // end of class P
";
var csharp = @"
class C
{
public static void Main()
{
P p = new P();
System.Console.Write(p.M1());
}
}
";
var comp = CreateCompilationWithIL(csharp, il, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,31): error CS0029: Cannot implicitly convert type 'string' to 'int'
// System.Console.Write(p.M1());
Diagnostic(ErrorCode.ERR_NoImplicitConv, "p.M1()").WithArguments("string", "int").WithLocation(7, 31));
}
[Fact]
public void DefaultArgument_LoopInUsage()
{
var csharp = @"
class C
{
static object F(object param = F()) => param; // 1
}
";
var comp = CreateCompilation(csharp);
comp.VerifyDiagnostics(
// (4,36): error CS1736: Default parameter value for 'param' must be a compile-time constant
// static object F(object param = F()) => param; // 1
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("param").WithLocation(4, 36));
var method = comp.GetMember<MethodSymbol>("C.F");
var param = method.Parameters.Single();
Assert.Equal(ConstantValue.Bad, param.ExplicitDefaultConstantValue);
}
[Fact]
public void DefaultValue_Boxing()
{
var csharp = @"
class C
{
void M1(object obj = 1) // 1
{
}
C(object obj = System.DayOfWeek.Monday) // 2
{
}
}
";
var comp = CreateCompilation(csharp);
comp.VerifyDiagnostics(
// (4,20): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null
// void M1(object obj = 1) // 1
Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(4, 20),
// (8,14): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null
// C(object obj = System.DayOfWeek.Monday) // 2
Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(8, 14));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection;
using System.Reflection.Emit;
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
{
public class NamedAndOptionalTests : CompilingTestBase
{
[Fact]
public void Test13984()
{
string source = @"
using System;
class Program
{
static void Main() { }
static void M(DateTime da = new DateTime(2012, 6, 22),
decimal d = new decimal(5),
int i = new int())
{
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,33): error CS1736: Default parameter value for 'da' must be a compile-time constant
// static void M(DateTime da = new DateTime(2012, 6, 22),
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new DateTime(2012, 6, 22)").WithArguments("da"),
// (7,31): error CS1736: Default parameter value for 'd' must be a compile-time constant
// decimal d = new decimal(5),
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new decimal(5)").WithArguments("d"));
}
[Fact]
public void Test13861()
{
// * There are two decimal constant attribute constructors; we should honour both of them.
// * Using named arguments to re-order the arguments must not change the value of the constant.
string source = @"
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
class Program
{
public static void Goo1([Optional][DecimalConstant(0, 0, low: (uint)100, mid: (uint)0, hi: (uint)0)] decimal i)
{
System.Console.Write(i);
}
public static void Goo2([Optional][DecimalConstant(0, 0, 0, 0, 200)] decimal i)
{
System.Console.Write(i);
}
static void Main(string[] args)
{
Goo1();
Goo2();
}
}";
string expected = "100200";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsInCtors()
{
string source = @"
class Alpha
{
public Alpha(int x = 123) { }
}
class Bravo : Alpha
{ // See bug 7846.
// This should be legal; the generated ctor for Bravo should call base(123)
}
class Charlie : Alpha
{
public Charlie() : base() {}
// This should be legal; should call base(123)
}
class Delta : Alpha
{
public Delta() {}
// This should be legal; should call base(123)
}
abstract class Echo
{
protected Echo(int x = 123) {}
}
abstract class Foxtrot : Echo
{
}
abstract class Hotel : Echo
{
protected Hotel() {}
}
abstract class Golf : Echo
{
protected Golf() : base() {}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void TestNamedAndOptionalParamsErrors()
{
string source = @"
class Base
{
public virtual void Goo(int reqParam1,
int optParam1 = 0,
int optParam2 = default(int),
int optParam3 = new int(),
string optParam4 = null,
double optParam5 = 128L)
{
}
}
class Middle : Base
{
//override and change the parameters names
public override void Goo(int reqChParam1,
int optChParam1 = 0,
int optChParam2 = default(int),
int optChParam3 = new int(),
string optChParam4 = null,
double optChParam5 = 128L)
{
}
}
class C : Middle
{
public void Q(params int[] x) {}
public void M()
{
var c = new C();
// calling child class parameters with base names
// error CS1739: The best overload for 'Goo' does not have a parameter named 'optParam3'
c.Goo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111);
// error CS1738: Named argument specifications must appear after all fixed arguments have been specified
c.Goo(optArg1: 3333, 11111);
}
}";
CreateCompilation(source, parseOptions: TestOptions.Regular7_1).VerifyDiagnostics(
// (37,15): error CS1739: The best overload for 'Goo' does not have a parameter named 'optParam3'
// c.Goo(optParam3: 333, reqParam1: 111 , optParam2: 222, optParam1: 1111);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "optParam3").WithArguments("Goo", "optParam3").WithLocation(37, 15),
// (39,30): error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments.
// c.Goo(optArg1: 3333, 11111);
Diagnostic(ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, "11111").WithArguments("7.2").WithLocation(39, 30),
// (39,15): error CS1739: The best overload for 'Goo' does not have a parameter named 'optArg1'
// c.Goo(optArg1: 3333, 11111);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "optArg1").WithArguments("Goo", "optArg1").WithLocation(39, 15)
);
}
[Fact]
public void TestNamedAndOptionalParamsErrors2()
{
string source = @"
class C
{
//error CS1736
public void M(string s = new string('c',5)) {}
}";
CreateCompilation(source).VerifyDiagnostics(
// (5,30): error CS1736: Default parameter value for 's' must be a compile-time constant
// public void M(string s = new string('c',5)) {}
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new string('c',5)").WithArguments("s").WithLocation(5, 30));
}
[Fact]
public void TestNamedAndOptionalParamsErrors3()
{
// Here we cannot report that "no overload of M takes two arguments" because of course
// M(1, 2) is legal. We cannot report that any argument does not correspond to a formal;
// all of them do. We cannot report that named arguments precede positional arguments.
// We cannot report that any argument is not convertible to its corresponding formal;
// all of them are convertible. The only error we can report here is that a formal
// parameter has no corresponding argument.
string source = @"
class C
{
// CS7036 (ERR_NoCorrespondingArgument)
delegate void F(int fx, int fg, int fz = 123);
C(int cx, int cy, int cz = 123) {}
public static void M(int mx, int my, int mz = 123)
{
F f = null;
f(0, fz : 456);
M(0, mz : 456);
new C(0, cz : 456);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (10,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'fg' of 'C.F'
// f(0, fz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "f").WithArguments("fg", "C.F").WithLocation(10, 9),
// (11,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'my' of 'C.M(int, int, int)'
// M(0, mz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("my", "C.M(int, int, int)").WithLocation(11, 9),
// (12,13): error CS7036: There is no argument given that corresponds to the required formal parameter 'cy' of 'C.C(int, int, int)'
// new C(0, cz : 456);
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("cy", "C.C(int, int, int)").WithLocation(12, 13));
}
[Fact]
public void TestNamedAndOptionalParamsCrazy()
{
// This was never supposed to work and the spec does not require it, but
// nevertheless, the native compiler allows this:
const string source = @"
class C
{
static void C(int q = 10, params int[] x) {}
static int X() { return 123; }
static int Q() { return 345; }
static void M()
{
C(x:X(), q:Q());
}
}";
// and so Roslyn does too. It seems likely that someone has taken a dependency
// on the bad pattern.
CreateCompilation(source).VerifyDiagnostics(
// (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type
// static void C(int q = 10, params int[] x) {}
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15));
}
[Fact]
public void TestNamedAndOptionalParamsCrazyError()
{
// Fortunately, however, this is still illegal:
const string source = @"
class C
{
static void C(int q = 10, params int[] x) {}
static void M()
{
C(1, 2, 3, x:4);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,15): error CS0542: 'C': member names cannot be the same as their enclosing type
// static void C(int q = 10, params int[] x) {}
Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C").WithLocation(4, 15),
// (7,16): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given
// C(1, 2, 3, x:4);
Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(7, 16));
}
[Fact]
public void TestNamedAndOptionalParamsBasic()
{
string source = @"
using System;
public enum E
{
zero,
one,
two,
three
}
public enum ELong : long
{
zero,
one,
two,
three
}
public class EnumDefaultValues
{
public static void Run()
{
var x = new EnumDefaultValues();
x.M();
}
void M(
E e1 = 0,
E e2 = default(E),
E e3 = E.zero,
E e4 = E.one,
E? ne1 = 0,
E? ne2 = default(E),
E? ne3 = E.zero,
E? ne4 = E.one,
E? ne5 = null,
E? ne6 = default(E?),
ELong el1 = 0,
ELong el2 = default(ELong),
ELong el3 = ELong.zero,
ELong el4 = ELong.one,
ELong? nel1 = 0,
ELong? nel2 = default(ELong),
ELong? nel3 = ELong.zero,
ELong? nel4 = ELong.one,
ELong? nel5 = null,
ELong? nel6 = default(ELong?)
)
{
Show(e1);
Show(e2);
Show(e3);
Show(e4);
Show(ne1);
Show(ne2);
Show(ne3);
Show(ne4);
Show(ne5);
Show(ne6);
Show(el1);
Show(el2);
Show(el3);
Show(el4);
Show(nel1);
Show(nel2);
Show(nel3);
Show(nel4);
Show(nel5);
Show(nel6);
}
static void Show<T>(T t)
{
object o = t;
Console.WriteLine(""{0}: {1}"", typeof(T), o != null ? o : ""<null>"");
}
}
struct Sierra
{
public Alpha alpha;
public Bravo bravo;
public int i;
public Sierra(Alpha alpha, Bravo bravo, int i)
{
this.alpha = alpha;
this.bravo = bravo;
this.i = i;
}
}
class Alpha
{
public virtual int Mike(int xray)
{
return xray;
}
}
class Bravo : Alpha
{
public override int Mike(int yankee)
{
return yankee;
}
}
class Charlie : Bravo
{
void Foxtrot(
int xray = 10,
string yankee = ""sam"")
{
Console.WriteLine(""Foxtrot: xray={0} yankee={1}"", xray, yankee);
}
void Quebec(
int xray,
int yankee = 10,
int zulu = 11)
{
Console.WriteLine(""Quebec: xray={0} yankee={1} zulu={2}"", xray, yankee, zulu);
}
void OutRef(
out int xray,
ref int yankee)
{
xray = 0;
yankee = 0;
}
void ParamArray(params int[] xray)
{
Console.WriteLine(""ParamArray: xray={0}"", string.Join<int>("","", xray));
}
void ParamArray2(
int yankee = 10,
params int[] xray)
{
Console.WriteLine(""ParamArray2: yankee={0} xray={1}"", yankee, string.Join<int>("","", xray));
}
void Zeros(
int xray = 0,
int? yankee = 0,
int? zulu = null,
Charlie charlie = null)
{
Console.WriteLine(""Zeros: xray={0} yankee={1} zulu={2} charlie={3}"",
xray,
yankee == null ? ""null"" : yankee.ToString(),
zulu == null ? ""null"" : zulu.ToString(),
charlie == null ? ""null"" : charlie.ToString() );
}
void OtherDefaults(
string str = default(string),
Alpha alpha = default(Alpha),
Bravo bravo = default(Bravo),
int i = default(int),
Sierra sierra = default(Sierra))
{
Console.WriteLine(""OtherDefaults: str={0} alpha={1} bravo={2} i={3} sierra={4}"",
str == null ? ""null"" : str,
alpha == null ? ""null"" : alpha.ToString(),
bravo == null ? ""null"" : bravo.ToString(),
i,
sierra.alpha == null && sierra.bravo == null && sierra.i == 0 ? ""default(Sierra)"" : sierra.ToString());
}
int Bar()
{
Console.WriteLine(""Bar"");
return 96;
}
string Baz()
{
Console.WriteLine(""Baz"");
return ""Baz"";
}
void BasicOptionalTests()
{
Console.WriteLine(""BasicOptional"");
Foxtrot(0);
Foxtrot();
ParamArray(1, 2, 3);
Zeros();
OtherDefaults();
}
void BasicNamedTests()
{
Console.WriteLine(""BasicNamed"");
// Basic named test.
Foxtrot(yankee: ""test"", xray: 1);
Foxtrot(xray: 1, yankee: ""test"");
// Test to see which execution comes first.
Foxtrot(yankee: Baz(), xray: Bar());
int y = 100;
int x = 100;
OutRef(yankee: ref y, xray: out x);
Console.WriteLine(x);
Console.WriteLine(y);
Charlie c = new Charlie();
ParamArray(xray: 1);
ParamArray(xray: new int[] { 1, 2, 3 });
ParamArray2(xray: 1);
ParamArray2(xray: new int[] { 1, 2, 3 });
ParamArray2(xray: 1, yankee: 20);
ParamArray2(xray: new int[] { 1, 2, 3 }, yankee: 20);
ParamArray2();
}
void BasicNamedAndOptionalTests()
{
Console.WriteLine(""BasicNamedAndOptional"");
Foxtrot(yankee: ""test"");
Foxtrot(xray: 0);
Quebec(1, yankee: 1);
Quebec(1, zulu: 10);
}
void OverrideTest()
{
Console.WriteLine(Mike(yankee: 10));
}
void TypeParamTest<T>() where T : Bravo, new()
{
T t = new T();
Console.WriteLine(t.Mike(yankee: 4));
}
static void Main()
{
Charlie c = new Charlie();
c.BasicOptionalTests();
c.BasicNamedTests();
c.BasicNamedAndOptionalTests();
c.OverrideTest();
c.TypeParamTest<Bravo>();
EnumDefaultValues.Run();
}
}
";
string expected = @"BasicOptional
Foxtrot: xray=0 yankee=sam
Foxtrot: xray=10 yankee=sam
ParamArray: xray=1,2,3
Zeros: xray=0 yankee=0 zulu=null charlie=null
OtherDefaults: str=null alpha=null bravo=null i=0 sierra=default(Sierra)
BasicNamed
Foxtrot: xray=1 yankee=test
Foxtrot: xray=1 yankee=test
Baz
Bar
Foxtrot: xray=96 yankee=Baz
0
0
ParamArray: xray=1
ParamArray: xray=1,2,3
ParamArray2: yankee=10 xray=1
ParamArray2: yankee=10 xray=1,2,3
ParamArray2: yankee=20 xray=1
ParamArray2: yankee=20 xray=1,2,3
ParamArray2: yankee=10 xray=
BasicNamedAndOptional
Foxtrot: xray=10 yankee=test
Foxtrot: xray=0 yankee=sam
Quebec: xray=1 yankee=1 zulu=11
Quebec: xray=1 yankee=10 zulu=10
10
4
E: zero
E: zero
E: zero
E: one
System.Nullable`1[E]: zero
System.Nullable`1[E]: zero
System.Nullable`1[E]: zero
System.Nullable`1[E]: one
System.Nullable`1[E]: <null>
System.Nullable`1[E]: <null>
ELong: zero
ELong: zero
ELong: zero
ELong: one
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: zero
System.Nullable`1[ELong]: one
System.Nullable`1[ELong]: <null>
System.Nullable`1[ELong]: <null>";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnAttributes()
{
string source = @"
using System;
class MyAttribute : Attribute
{
public MyAttribute(int a = 1, int b = 2, int c = 3)
{
A = a;
B = b;
C = c;
}
public int X;
public int A;
public int B;
public int C;
}
[MyAttribute(4, c:5, X=6)]
class C
{
static void Main()
{
MyAttribute m1 = new MyAttribute();
Console.Write(m1.A); // 1
Console.Write(m1.B); // 2
Console.Write(m1.C); // 3
Console.Write(m1.X); // 0
MyAttribute m2 = new MyAttribute(c: 7);
Console.Write(m2.A); // 1
Console.Write(m2.B); // 2
Console.Write(m2.C); // 7
Console.Write(m2.X); // 0
Type t = typeof(C);
foreach (MyAttribute attr in t.GetCustomAttributes(false))
{
Console.Write(attr.A); // 4
Console.Write(attr.B); // 2
Console.Write(attr.C); // 5
Console.Write(attr.X); // 6
}
}
}";
CompileAndVerify(source, expectedOutput: "123012704256");
}
[Fact]
public void TestNamedAndOptionalParamsOnIndexers()
{
string source = @"
using System;
class D
{
public int this[string s = ""four""] { get { return s.Length; } set { } }
public int this[int x = 2, int y = 5] { get { return x + y; } set { } }
public int this[string str = ""goo"", int i = 13]
{
get { Console.WriteLine(""D.this[str: '{0}', i: {1}].get"", str, i); return i;}
set { Console.WriteLine(""D.this[str: '{0}', i: {1}].set"", str, i); }
}
}
class C
{
int this[int x, int y] { get { return x + y; } set { } }
static void Main()
{
C c = new C();
Console.WriteLine(c[y:10, x:10]);
D d = new D();
Console.WriteLine(d[1]);
Console.WriteLine(d[0,2]);
Console.WriteLine(d[x:2]);
Console.WriteLine(d[x:3, y:0]);
Console.WriteLine(d[y:3, x:2]);
Console.WriteLine(d[""abc""]);
Console.WriteLine(d[s:""12345""]);
d[i:1] = 0;
d[str:""bar""] = 0;
d[i:2, str:""baz""] = 0;
d[str:""bah"", i:3] = 0;
}
}";
string expected = @"20
6
2
7
3
5
3
5
D.this[str: 'goo', i: 1].set
D.this[str: 'bar', i: 13].set
D.this[str: 'baz', i: 2].set
D.this[str: 'bah', i: 3].set";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnPartialMethods()
{
string source = @"
using System;
partial class C
{
static partial void PartialMethod(int x);
}
partial class C
{
static partial void PartialMethod(int y) { Console.WriteLine(y); }
static void Main()
{
// Declaring partial wins.
PartialMethod(x:123);
}
}";
string expected = "123";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void TestNamedAndOptionalParamsOnPartialMethodsErrors()
{
string source = @"
using System;
partial class C
{
static partial void PartialMethod(int x);
}
partial class C
{
static partial void PartialMethod(int y) { Console.WriteLine(y); }
static void Main()
{
// Implementing partial loses.
PartialMethod(y:123);
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (9,25): warning CS8826: Partial method declarations 'void C.PartialMethod(int x)' and 'void C.PartialMethod(int y)' have signature differences.
// static partial void PartialMethod(int y) { Console.WriteLine(y); }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "PartialMethod").WithArguments("void C.PartialMethod(int x)", "void C.PartialMethod(int y)").WithLocation(9, 25),
// (13,23): error CS1739: The best overload for 'PartialMethod' does not have a parameter named 'y'
// PartialMethod(y:123);
Diagnostic(ErrorCode.ERR_BadNamedArgument, "y").WithArguments("PartialMethod", "y").WithLocation(13, 23)
);
}
[Fact]
public void TestNamedAndOptionalParametersUnsafe()
{
string source = @"
using System;
unsafe class C
{
static void M(
int* x1 = default(int*),
IntPtr x2 = default(IntPtr),
UIntPtr x3 = default(UIntPtr),
int x4 = default(int))
{
}
static void Main()
{
M();
}
}";
// We make an improvement on the native compiler here; we generate default(UIntPtr) and
// default(IntPtr) as "load zero, convert to type", rather than making a stack slot and calling
// init on it.
var c = CompileAndVerify(source, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
c.VerifyIL("C.Main", @"{
// Code size 13 (0xd)
.maxstack 4
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: ldc.i4.0
IL_0003: conv.i
IL_0004: ldc.i4.0
IL_0005: conv.u
IL_0006: ldc.i4.0
IL_0007: call ""void C.M(int*, System.IntPtr, System.UIntPtr, int)""
IL_000c: ret
}");
}
[WorkItem(528783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528783")]
[Fact]
public void TestNamedAndOptionalParametersArgumentName()
{
const string text = @"
using System;
namespace NS
{
class Test
{
static void M(sbyte sb = 0, string ss = null) {}
static void Main()
{
M(/*<bind>*/ss/*</bind>*/: ""QC"");
}
}
}
";
var comp = CreateCompilation(text);
var nodeAndModel = GetBindingNodeAndModel<IdentifierNameSyntax>(comp);
var typeInfo = nodeAndModel.Item2.GetTypeInfo(nodeAndModel.Item1);
// parameter name has no type
Assert.Null(typeInfo.Type);
var symInfo = nodeAndModel.Item2.GetSymbolInfo(nodeAndModel.Item1);
Assert.NotNull(symInfo.Symbol);
Assert.Equal(SymbolKind.Parameter, symInfo.Symbol.Kind);
Assert.Equal("ss", symInfo.Symbol.Name);
}
[WorkItem(542418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542418")]
[Fact]
public void OptionalValueInvokesInstanceMethod()
{
var source =
@"class C
{
object F() { return null; }
void M1(object value = F()) { }
object M2(object value = M2()) { return null; }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,28): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 28),
// (5,30): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 30));
}
[Fact]
public void OptionalValueInvokesStaticMethod()
{
var source =
@"class C
{
static object F() { return null; }
static void M1(object value = F()) { }
static object M2(object value = M2()) { return null; }
}";
CreateCompilation(source).VerifyDiagnostics(
// (4,35): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("value").WithLocation(4, 35),
// (5,37): error CS1736: Default parameter value for 'value' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M2()").WithArguments("value").WithLocation(5, 37));
}
[WorkItem(11638, "https://github.com/dotnet/roslyn/issues/11638")]
[Fact]
public void OptionalValueHasObjectInitializer()
{
var source =
@"class C
{
static void Test(Vector3 vector = new Vector3() { X = 1f, Y = 1f, Z = 1f}) { }
}
public struct Vector3
{
public float X;
public float Y;
public float Z;
}";
CreateCompilation(source).VerifyDiagnostics(
// (3,39): error CS1736: Default parameter value for 'vector' must be a compile-time constant
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new Vector3() { X = 1f, Y = 1f, Z = 1f}").WithArguments("vector").WithLocation(3, 39));
}
[WorkItem(542411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542411")]
[WorkItem(542365, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542365")]
[Fact]
public void GenericOptionalParameters()
{
var source =
@"class C
{
static void Goo<T>(T t = default(T)) {}
}";
CreateCompilation(source).VerifyDiagnostics();
}
[WorkItem(542458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542458")]
[Fact]
public void OptionalValueTypeFromReferencedAssembly()
{
// public struct S{}
// public class C
// {
// public static void Goo(string s, S t = default(S)) {}
// }
string ilSource = @"
// =============== CLASS MEMBERS DECLARATION ===================
.class public sequential ansi sealed beforefieldinit S
extends [mscorlib]System.ValueType
{
.pack 0
.size 1
} // end of class S
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig static void Goo(string s,
[opt] valuetype S t) cil managed
{
.param [2] = nullref
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::Goo
} // end of class C
";
var source =
@"
public class D
{
public static void Caller()
{
C.Goo("""");
}
}";
CompileWithCustomILSource(source, ilSource);
}
[WorkItem(542867, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542867")]
[Fact]
public void OptionalParameterDeclaredWithAttributes()
{
string source = @"
using System.Runtime.InteropServices;
public class Parent{
public int Goo([Optional]object i = null) {
return 1;
}
public int Bar([DefaultParameterValue(1)]int i = 2) {
return 1;
}
}
class Test{
public static int Main(){
Parent p = new Parent();
return p.Goo();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
// public int Bar([DefaultParameterValue(1)]int i = 2) {
Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "DefaultParameterValue").WithLocation(9, 21),
// (9,54): error CS8017: The parameter has multiple distinct default values.
// public int Bar([DefaultParameterValue(1)]int i = 2) {
Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "2").WithLocation(9, 54),
// (5,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute
// public int Goo([Optional]object i = null) {
Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "Optional").WithLocation(5, 21)
);
}
[WorkItem(10290, "DevDiv_Projects/Roslyn")]
[Fact]
public void OptionalParamOfTypeObject()
{
string source = @"
public class Test
{
public static int M1(object p1 = null) { if (p1 == null) return 0; else return 1; }
public static void Main()
{
System.Console.WriteLine(M1());
}
}
";
CompileAndVerify(source, expectedOutput: "0");
}
[WorkItem(543871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543871")]
[Fact]
public void RefParameterDeclaredWithOptionalAttribute()
{
// The native compiler produces "CS1501: No overload for method 'Goo' takes 0 arguments."
// Roslyn produces a slightly more informative error message.
string source = @"
using System.Runtime.InteropServices;
public class Parent
{
public static void Goo([Optional] ref int x) {}
static void Main()
{
Goo();
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,10): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'Parent.Goo(ref int)'
// Goo();
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "Goo").WithArguments("x", "Parent.Goo(ref int)"));
}
[Fact, WorkItem(544491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544491")]
public void EnumAsDefaultParameterValue()
{
string source = @"
using System.Runtime.InteropServices;
public enum MyEnum { one, two, three }
public interface IOptionalRef
{
MyEnum MethodRef([In, Out, Optional, DefaultParameterValue(MyEnum.three)] ref MyEnum v);
}
";
CompileAndVerify(source).VerifyDiagnostics();
}
[Fact]
public void DefaultParameterValueErrors()
{
string source = @"
using System.Runtime.InteropServices;
public enum I8 : sbyte { v = 1 }
public enum U8 : byte { v = 1 }
public enum I16 : short { v = 1 }
public enum U16 : ushort { v = 1 }
public enum I32 : int { v = 1 }
public enum U32 : uint { v = 1 }
public enum I64 : long { v = 1 }
public enum U64 : ulong { v = 1 }
public class C { }
public delegate void D();
public interface I { }
public struct S {
}
public static class ErrorCases
{
public static void M(
// bool
[Optional][DefaultParameterValue(0)] bool b1,
[Optional][DefaultParameterValue(""hello"")] bool b2,
// integral
[Optional][DefaultParameterValue(12)] sbyte sb1,
[Optional][DefaultParameterValue(""hello"")] byte by1,
// char
[Optional][DefaultParameterValue(""c"")] char ch1,
// float
[Optional][DefaultParameterValue(1.0)] float fl1,
[Optional][DefaultParameterValue(1)] double dbl1,
// enum
[Optional][DefaultParameterValue(0)] I8 i8,
[Optional][DefaultParameterValue(12)] U8 u8,
[Optional][DefaultParameterValue(""hello"")] I16 i16,
// string
[Optional][DefaultParameterValue(5)] string str1,
[Optional][DefaultParameterValue(new int[] { 12 })] string str2,
// reference types
[Optional][DefaultParameterValue(2)] C c1,
[Optional][DefaultParameterValue(""hello"")] C c2,
[DefaultParameterValue(new int[] { 1, 2 })] int[] arr1,
[DefaultParameterValue(null)] int[] arr2,
[DefaultParameterValue(new int[] { 1, 2 })] object arr3,
[DefaultParameterValue(typeof(object))] System.Type type1,
[DefaultParameterValue(null)] System.Type type2,
[DefaultParameterValue(typeof(object))] object type3,
// user defined struct
[DefaultParameterValue(null)] S userStruct1,
[DefaultParameterValue(0)] S userStruct2,
[DefaultParameterValue(""hel"")] S userStruct3,
// null value to non-ref type
[Optional][DefaultParameterValue(null)] bool b3,
// integral
[Optional][DefaultParameterValue(null)] int i2,
// char
[Optional][DefaultParameterValue(null)] char ch2,
// float
[Optional][DefaultParameterValue(null)] float fl2,
// enum
[Optional][DefaultParameterValue(null)] I8 i82
)
{
}
}
";
// NOTE: anywhere dev10 reported CS1909, roslyn reports CS1910.
CreateCompilation(source).VerifyDiagnostics(
// (27,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(0)] bool b1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (28,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] bool b2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (31,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(12)] sbyte sb1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (32,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] byte by1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (35,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("c")] char ch1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (38,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(1.0)] float fl1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (42,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(0)] I8 i8,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (43,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(12)] U8 u8,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (44,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] I16 i16,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (47,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(5)] string str1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (48,20): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [Optional][DefaultParameterValue(new int[] { 12 })] string str2,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// (51,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(2)] C c1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (52,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue("hello")] C c2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (54,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(new int[] { 1, 2 })] int[] arr1,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// NOTE: Roslyn specifically allows this usage (illegal in dev10).
//// (55,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'int[]', unless the default value is null
//// [DefaultParameterValue(null)] int[] arr2,
//Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("int[]"),
// (56,10): error CS1910: Argument of type 'int[]' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(new int[] { 1, 2 })] object arr3,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"),
// (58,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(typeof(object))] System.Type type1,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"),
// NOTE: Roslyn specifically allows this usage (illegal in dev10).
//// (59,10): error CS1909: The DefaultParameterValue attribute is not applicable on parameters of type 'System.Type', unless the default value is null
//// [DefaultParameterValue(null)] System.Type type2,
//Diagnostic(ErrorCode.ERR_DefaultValueBadParamType, "DefaultParameterValue").WithArguments("System.Type"),
// (60,10): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultParameterValue attribute
// [DefaultParameterValue(typeof(object))] object type3,
Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type"),
// (63,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue(null)] S userStruct1,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (64,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue(0)] S userStruct2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (65,10): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [DefaultParameterValue("hel")] S userStruct3,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (68,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] bool b3,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (71,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] int i2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (74,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] char ch2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (77,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] float fl2,
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"),
// (80,20): error CS1908: The type of the argument to the DefaultParameterValue attribute must match the parameter type
// [Optional][DefaultParameterValue(null)] I8 i82
Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"));
}
[WorkItem(544440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544440")]
[ConditionalFact(typeof(DesktopOnly))]
public void TestBug12768()
{
string sourceDefinitions = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public class C
{
public static void M1(object x = null)
{
Console.WriteLine(x ?? 1);
}
public static void M2([Optional] object x)
{
Console.WriteLine(x ?? 2);
}
public static void M3([MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 3);
}
public static void M4([MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 4);
}
public static void M5([IDispatchConstant] object x = null)
{
Console.WriteLine(x ?? 5);
}
public static void M6([IDispatchConstant] [Optional] object x)
{
Console.WriteLine(x ?? 6);
}
public static void M7([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 7);
}
public static void M8([IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 8);
}
public static void M9([IUnknownConstant]object x = null)
{
Console.WriteLine(x ?? 9);
}
public static void M10([IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 10);
}
public static void M11([IUnknownConstant][MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 11);
}
public static void M12([IUnknownConstant][MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 12);
}
public static void M13([IUnknownConstant][IDispatchConstant] object x = null)
{
Console.WriteLine(x ?? 13);
}
public static void M14([IDispatchConstant][IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 14);
}
public static void M15([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)] object x = null)
{
Console.WriteLine(x ?? 15);
}
public static void M16([IUnknownConstant][IDispatchConstant] [MarshalAs(UnmanagedType.Interface)][Optional] object x)
{
Console.WriteLine(x ?? 16);
}
public static void M17([MarshalAs(UnmanagedType.Interface)][IDispatchConstant][Optional] object x)
{
Console.WriteLine(x ?? 17);
}
public static void M18([MarshalAs(UnmanagedType.Interface)][IUnknownConstant][Optional] object x)
{
Console.WriteLine(x ?? 18);
}
}
";
string sourceCalls = @"
internal class D
{
static void Main()
{
C.M1(); // null
C.M2(); // Missing
C.M3(); // null
C.M4(); // null
C.M5(); // null
C.M6(); // DispatchWrapper
C.M7(); // null
C.M8(); // null
C.M9(); // null
C.M10(); // UnknownWrapper
C.M11(); // null
C.M12(); // null
C.M13(); // null
C.M14(); // UnknownWrapper
C.M15(); // null
C.M16(); // null
C.M17(); // null
C.M18(); // null
}
}";
string expected = @"1
System.Reflection.Missing
3
4
5
System.Runtime.InteropServices.DispatchWrapper
7
8
9
System.Runtime.InteropServices.UnknownWrapper
11
12
13
System.Runtime.InteropServices.UnknownWrapper
15
16
17
18";
// definitions in source:
var verifier = CompileAndVerify(new[] { sourceDefinitions, sourceCalls }, expectedOutput: expected);
// definitions in metadata:
using (var assembly = AssemblyMetadata.CreateFromImage(verifier.EmittedAssemblyData))
{
CompileAndVerify(new[] { sourceCalls }, new[] { assembly.GetReference() }, expectedOutput: expected);
}
}
[ConditionalFact(typeof(DesktopOnly))]
public void IUnknownConstant_MissingType()
{
var source = @"
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
class C
{
static void M0([Optional, MarshalAs(UnmanagedType.Interface)] object param) { }
static void M1([Optional, IUnknownConstant] object param) { }
static void M2([Optional, IDispatchConstant] object param) { }
static void M3([Optional] object param) { }
static void M()
{
M0();
M1();
M2();
M3();
}
}
";
CompileAndVerify(source).VerifyDiagnostics();
var comp = CreateCompilation(source);
comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor);
comp.MakeMemberMissing(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor);
comp.MakeMemberMissing(WellKnownMember.System_Type__Missing);
comp.VerifyDiagnostics(
// (15,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.UnknownWrapper..ctor'
// M1();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M1()").WithArguments("System.Runtime.InteropServices.UnknownWrapper", ".ctor").WithLocation(15, 9),
// (16,9): error CS0656: Missing compiler required member 'System.Runtime.InteropServices.DispatchWrapper..ctor'
// M2();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M2()").WithArguments("System.Runtime.InteropServices.DispatchWrapper", ".ctor").WithLocation(16, 9),
// (17,9): error CS0656: Missing compiler required member 'System.Type.Missing'
// M3();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "M3()").WithArguments("System.Type", "Missing").WithLocation(17, 9));
}
[WorkItem(545329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545329")]
[Fact()]
public void ComOptionalRefParameter()
{
string source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""00020813-0000-0000-c000-000000000046"")]
interface ComClass
{
void M([Optional]ref object o);
}
class D : ComClass
{
public void M(ref object o)
{
}
}
class C
{
static void Main()
{
D d = new D();
ComClass c = d;
c.M(); //fine
d.M(); //CS1501
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (25,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'D.M(ref object)'
// d.M(); //CS1501
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "D.M(ref object)").WithLocation(25, 11));
}
[WorkItem(545337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545337")]
[ClrOnlyFact]
public void TestVbDecimalAndDateTimeDefaultParameters()
{
var vb = @"
Imports System
public Module VBModule
Sub I(Optional ByVal x As System.Int32 = 456)
Console.WriteLine(x)
End Sub
Sub NI(Optional ByVal x As System.Int32? = 457)
Console.WriteLine(x)
End Sub
Sub OI(Optional ByVal x As Object = 458 )
Console.WriteLine(x)
End Sub
Sub DA(Optional ByVal x As DateTime = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub NDT(Optional ByVal x As DateTime? = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub ODT(Optional ByVal x As Object = #1/2/2007#)
Console.WriteLine(x = #1/2/2007#)
End Sub
Sub Dec(Optional ByVal x as Decimal = 12.3D)
Console.WriteLine(x.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub NDec(Optional ByVal x as Decimal? = 12.4D)
Console.WriteLine(x.Value.ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub ODec(Optional ByVal x as Object = 12.5D)
Console.WriteLine(DirectCast(x, Decimal).ToString(System.Globalization.CultureInfo.InvariantCulture))
End Sub
End Module
";
var csharp = @"
using System;
public class D
{
static void Main()
{
// Ensure suites run in invariant culture across machines
System.Threading.Thread.CurrentThread.CurrentCulture
= System.Globalization.CultureInfo.InvariantCulture;
// Possible in both C# and VB:
VBModule.I();
VBModule.NI();
VBModule.Dec();
VBModule.NDec();
// Not possible in C#, possible in VB, but C# honours the parameter:
VBModule.OI();
VBModule.ODec();
VBModule.DA();
VBModule.NDT();
VBModule.ODT();
}
}
";
string expected = @"456
457
12.3
12.4
458
12.5
True
True
True";
string il = @"{
// Code size 181 (0xb5)
.maxstack 5
IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get""
IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get""
IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set""
IL_000f: ldc.i4 0x1c8
IL_0014: call ""void VBModule.I(int)""
IL_0019: ldc.i4 0x1c9
IL_001e: newobj ""int?..ctor(int)""
IL_0023: call ""void VBModule.NI(int?)""
IL_0028: ldc.i4.s 123
IL_002a: ldc.i4.0
IL_002b: ldc.i4.0
IL_002c: ldc.i4.0
IL_002d: ldc.i4.1
IL_002e: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0033: call ""void VBModule.Dec(decimal)""
IL_0038: ldc.i4.s 124
IL_003a: ldc.i4.0
IL_003b: ldc.i4.0
IL_003c: ldc.i4.0
IL_003d: ldc.i4.1
IL_003e: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0043: newobj ""decimal?..ctor(decimal)""
IL_0048: call ""void VBModule.NDec(decimal?)""
IL_004d: ldc.i4 0x1ca
IL_0052: box ""int""
IL_0057: call ""void VBModule.OI(object)""
IL_005c: ldc.i4.s 125
IL_005e: ldc.i4.0
IL_005f: ldc.i4.0
IL_0060: ldc.i4.0
IL_0061: ldc.i4.1
IL_0062: newobj ""decimal..ctor(int, int, int, bool, byte)""
IL_0067: box ""decimal""
IL_006c: call ""void VBModule.ODec(object)""
IL_0071: ldc.i8 0x8c8fc181490c000
IL_007a: newobj ""System.DateTime..ctor(long)""
IL_007f: call ""void VBModule.DA(System.DateTime)""
IL_0084: ldc.i8 0x8c8fc181490c000
IL_008d: newobj ""System.DateTime..ctor(long)""
IL_0092: newobj ""System.DateTime?..ctor(System.DateTime)""
IL_0097: call ""void VBModule.NDT(System.DateTime?)""
IL_009c: ldc.i8 0x8c8fc181490c000
IL_00a5: newobj ""System.DateTime..ctor(long)""
IL_00aa: box ""System.DateTime""
IL_00af: call ""void VBModule.ODT(object)""
IL_00b4: ret
}";
var vbCompilation = CreateVisualBasicCompilation("VB", vb,
compilationOptions: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
vbCompilation.VerifyDiagnostics();
var csharpCompilation = CreateCSharpCompilation("CS", csharp,
compilationOptions: TestOptions.ReleaseExe,
referencedCompilations: new[] { vbCompilation });
var verifier = CompileAndVerify(csharpCompilation, expectedOutput: expected);
verifier.VerifyIL("D.Main", il);
}
[WorkItem(545337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545337")]
[Fact]
public void TestCSharpDecimalAndDateTimeDefaultParameters()
{
var library = @"
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public enum E
{
one,
two,
three
}
public class C
{
public void Goo(
[Optional][DateTimeConstant(100000)]DateTime dateTime,
decimal dec = 12345678901234567890m,
int? x = 0,
int? q = null,
short y = 10,
int z = default(int),
S? s = null)
//S? s2 = default(S))
{
if (dateTime == new DateTime(100000))
{
Console.WriteLine(""DatesMatch"");
}
else
{
Console.WriteLine(""Dates dont match!!"");
}
Write(dec);
Write(x);
Write(q);
Write(y);
Write(z);
Write(s);
//Write(s2);
}
public void Bar(S? s1, S? s2, S? s3)
{
}
public void Baz(E? e1 = E.one, long? x = 0)
{
if (e1.HasValue)
{
Console.WriteLine(e1);
}
else
{
Console.WriteLine(""null"");
}
Console.WriteLine(x);
}
public void Write(object o)
{
if (o == null)
{
Console.WriteLine(""null"");
}
else
{
Console.WriteLine(o);
}
}
}
public struct S
{
}
";
var main = @"
using System;
public class D
{
static void Main()
{
// Ensure suites run in invariant culture across machines
System.Threading.Thread.CurrentThread.CurrentCulture
= System.Globalization.CultureInfo.InvariantCulture;
C c = new C();
c.Goo();
c.Baz();
}
}
";
var libComp = CreateCompilation(library, options: TestOptions.ReleaseDll, assemblyName: "Library");
libComp.VerifyDiagnostics();
var exeComp = CreateCompilation(main, new[] { new CSharpCompilationReference(libComp) }, options: TestOptions.ReleaseExe, assemblyName: "Main");
var verifier = CompileAndVerify(exeComp, expectedOutput: @"DatesMatch
12345678901234567890
0
null
10
0
null
one
0");
verifier.VerifyIL("D.Main", @"{
// Code size 97 (0x61)
.maxstack 9
.locals init (int? V_0,
S? V_1)
IL_0000: call ""System.Threading.Thread System.Threading.Thread.CurrentThread.get""
IL_0005: call ""System.Globalization.CultureInfo System.Globalization.CultureInfo.InvariantCulture.get""
IL_000a: callvirt ""void System.Threading.Thread.CurrentCulture.set""
IL_000f: newobj ""C..ctor()""
IL_0014: dup
IL_0015: ldc.i4 0x186a0
IL_001a: conv.i8
IL_001b: newobj ""System.DateTime..ctor(long)""
IL_0020: ldc.i8 0xab54a98ceb1f0ad2
IL_0029: newobj ""decimal..ctor(ulong)""
IL_002e: ldc.i4.0
IL_002f: newobj ""int?..ctor(int)""
IL_0034: ldloca.s V_0
IL_0036: initobj ""int?""
IL_003c: ldloc.0
IL_003d: ldc.i4.s 10
IL_003f: ldc.i4.0
IL_0040: ldloca.s V_1
IL_0042: initobj ""S?""
IL_0048: ldloc.1
IL_0049: callvirt ""void C.Goo(System.DateTime, decimal, int?, int?, short, int, S?)""
IL_004e: ldc.i4.0
IL_004f: newobj ""E?..ctor(E)""
IL_0054: ldc.i4.0
IL_0055: conv.i8
IL_0056: newobj ""long?..ctor(long)""
IL_005b: callvirt ""void C.Baz(E?, long?)""
IL_0060: ret
}");
}
[Fact]
public void OmittedComOutParameter()
{
// We allow omitting optional ref arguments but not optional out arguments.
var source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""989FE455-5A6D-4D05-A349-1A221DA05FDA"")]
interface I
{
void M([Optional]out object o);
}
class P
{
static void Q(I i) { i.M(); }
}
";
// Note that the native compiler gives a slightly less informative error message here.
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,26): error CS7036: There is no argument given that corresponds to the required formal parameter 'o' of 'I.M(out object)'
// static void Q(I i) { i.M(); }
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M").WithArguments("o", "I.M(out object)")
);
}
[Fact]
public void OmittedComRefParameter()
{
var source = @"
using System;
using System.Runtime.InteropServices;
[ComImport, Guid(""A8FAF53B-F502-4465-9429-CAB2A19B47BE"")]
interface ICom
{
void M(out int w, int x, [Optional]ref object o, int z = 0);
}
class Com : ICom
{
public void M(out int w, int x, ref object o, int z)
{
w = 123;
Console.WriteLine(x);
if (o != null)
{
Console.WriteLine(o.GetType());
}
else
{
Console.WriteLine(""null"");
}
Console.WriteLine(z);
}
static void Main()
{
ICom c = new Com();
int q;
c.M(w: out q, z: 10, x: 100);
Console.WriteLine(q);
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: @"
100
System.Reflection.Missing
10
123");
verifier.VerifyIL("Com.Main", @"
{
// Code size 31 (0x1f)
.maxstack 5
.locals init (int V_0, //q
object V_1)
IL_0000: newobj ""Com..ctor()""
IL_0005: ldloca.s V_0
IL_0007: ldc.i4.s 100
IL_0009: ldsfld ""object System.Type.Missing""
IL_000e: stloc.1
IL_000f: ldloca.s V_1
IL_0011: ldc.i4.s 10
IL_0013: callvirt ""void ICom.M(out int, int, ref object, int)""
IL_0018: ldloc.0
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ret
}");
}
[Fact]
public void ArrayElementComRefParameter()
{
var source =
@"using System;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")]
interface IA
{
void M(ref int i);
}
class A : IA
{
void IA.M(ref int i)
{
i += 2;
}
}
class B
{
static void M(IA a)
{
a.M(F()[0]);
}
static void MByRef(IA a)
{
a.M(ref F()[0]);
}
static int[] i = { 0 };
static int[] F()
{
Console.WriteLine(""F()"");
return i;
}
static void Main()
{
IA a = new A();
M(a);
ReportAndReset();
MByRef(a);
ReportAndReset();
}
static void ReportAndReset()
{
Console.WriteLine(""{0}"", i[0]);
i = new[] { 0 };
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"F()
0
F()
2");
verifier.VerifyIL("B.M(IA)",
@"{
// Code size 17 (0x11)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: call ""int[] B.F()""
IL_0006: ldc.i4.0
IL_0007: ldelem.i4
IL_0008: stloc.0
IL_0009: ldloca.s V_0
IL_000b: callvirt ""void IA.M(ref int)""
IL_0010: ret
}");
verifier.VerifyIL("B.MByRef(IA)",
@"{
// Code size 18 (0x12)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call ""int[] B.F()""
IL_0006: ldc.i4.0
IL_0007: ldelema ""int""
IL_000c: callvirt ""void IA.M(ref int)""
IL_0011: ret
}");
}
[Fact]
public void ArrayElementComRefParametersReordered()
{
var source =
@"using System;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""B107A073-4ACE-4057-B4BA-837891E3C274"")]
interface IA
{
void M(ref int x, ref int y);
}
class A : IA
{
void IA.M(ref int x, ref int y)
{
x += 2;
y += 3;
}
}
class B
{
static void M(IA a)
{
a.M(y: ref F2()[0], x: ref F1()[0]);
}
static int[] i1 = { 0 };
static int[] i2 = { 0 };
static int[] F1()
{
Console.WriteLine(""F1()"");
return i1;
}
static int[] F2()
{
Console.WriteLine(""F2()"");
return i2;
}
static void Main()
{
IA a = new A();
M(a);
Console.WriteLine(""{0}, {1}"", i1[0], i2[0]);
}
}";
var verifier = CompileAndVerify(source, expectedOutput:
@"F2()
F1()
2, 3
");
verifier.VerifyIL("B.M(IA)",
@"{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int& V_0)
IL_0000: ldarg.0
IL_0001: call ""int[] B.F2()""
IL_0006: ldc.i4.0
IL_0007: ldelema ""int""
IL_000c: stloc.0
IL_000d: call ""int[] B.F1()""
IL_0012: ldc.i4.0
IL_0013: ldelema ""int""
IL_0018: ldloc.0
IL_0019: callvirt ""void IA.M(ref int, ref int)""
IL_001e: ret
}");
}
[Fact]
[WorkItem(546713, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546713")]
public void Test16631()
{
var source =
@"
public abstract class B
{
protected abstract void E<T>();
}
public class D : B
{
void M()
{
// There are two possible methods to choose here. The static method
// is better because it is declared in a more derived class; the
// virtual method is better because it has exactly the right number
// of parameters. In this case, the static method wins. The virtual
// method is to be treated as though it was a method of the base class,
// and therefore automatically loses. (The bug we are regressing here
// is that Roslyn did not correctly identify the originally-defining
// type B when the method E was generic. The original repro scenario in
// bug 16631 was much more complicated than this, but it boiled down to
// overload resolution choosing the wrong method.)
E<int>();
}
protected override void E<T>()
{
System.Console.WriteLine(1);
}
static void E<T>(int x = 0xBEEF)
{
System.Console.WriteLine(2);
}
static void Main()
{
(new D()).M();
}
}
";
var verifier = CompileAndVerify(source, expectedOutput: "2");
verifier.VerifyIL("D.M()",
@"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldc.i4 0xbeef
IL_0005: call ""void D.E<int>(int)""
IL_000a: ret
}");
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_PrimitiveStruct()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(int p) { }
public void M1(int p = 0) { } // default of type
public void M2(int p = 1) { } // not default of type
public void M3([Optional]int p) { } // no default specified (would be illegal)
public void M4([DefaultParameterValue(0)]int p) { } // default of type, not optional
public void M5([DefaultParameterValue(1)]int p) { } // not default of type, not optional
public void M6([Optional][DefaultParameterValue(0)]int p) { } // default of type, optional
public void M7([Optional][DefaultParameterValue(1)]int p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Equal(0, parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0), parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal(1, parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.True(parameters[4].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create(0), parameters[4].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length);
Assert.False(parameters[5].IsOptional);
Assert.False(parameters[5].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue);
Assert.True(parameters[5].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create(1), parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[5].GetAttributes().Length);
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(0, parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length);
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal(1, parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1), parameters[7].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length);
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_UserDefinedStruct()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(S p) { }
public void M1(S p = default(S)) { }
public void M2([Optional]S p) { } // no default specified (would be illegal)
}
public struct S
{
public int x;
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(3, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.False(parameters[2].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue);
Assert.Null(parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length);
};
// TODO: RefEmit doesn't emit the default value of M1's parameter.
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_String()
{
var source = @"
using System;
using System.Runtime.InteropServices;
public class C
{
public void M0(string p) { }
public void M1(string p = null) { }
public void M2(string p = ""A"") { }
public void M3([Optional]string p) { } // no default specified (would be illegal)
public void M4([DefaultParameterValue(null)]string p) { }
public void M5([Optional][DefaultParameterValue(null)]string p) { }
public void M6([DefaultParameterValue(""A"")]string p) { }
public void M7([Optional][DefaultParameterValue(""A"")]string p) { }
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal("A", parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create("A"), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.True(parameters[4].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Null, parameters[4].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[4].GetAttributes().Length);
Assert.True(parameters[5].IsOptional);
Assert.True(parameters[5].HasExplicitDefaultValue);
Assert.Null(parameters[5].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length);
Assert.False(parameters[6].IsOptional);
Assert.False(parameters[6].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[6].ExplicitDefaultValue);
Assert.True(parameters[6].HasMetadataConstantValue);
Assert.Equal(ConstantValue.Create("A"), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[6].GetAttributes().Length);
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal("A", parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create("A"), parameters[7].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length);
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_Decimal()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
public void M0(decimal p) { }
public void M1(decimal p = 0) { } // default of type
public void M2(decimal p = 1) { } // not default of type
public void M3([Optional]decimal p) { } // no default specified (would be illegal)
public void M4([DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, not optional
public void M5([DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, not optional
public void M6([Optional][DecimalConstant(0,0,0,0,0)]decimal p) { } // default of type, optional
public void M7([Optional][DecimalConstant(0,0,0,0,1)]decimal p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(8, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Equal(0M, parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0M), parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length);
Assert.True(parameters[2].IsOptional);
Assert.True(parameters[2].HasExplicitDefaultValue);
Assert.Equal(1M, parameters[2].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1M), parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[2].GetAttributes().Length);
Assert.True(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.Null(parameters[3].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[3].GetAttributes().Length);
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.False(parameters[4].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(0M) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[4].GetAttributes().Length); // DecimalConstantAttribute
Assert.False(parameters[5].IsOptional);
Assert.False(parameters[5].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[5].ExplicitDefaultValue);
Assert.False(parameters[5].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(1M) : null, parameters[5].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[5].GetAttributes().Length); // DecimalConstantAttribute
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(0M, parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(0M), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute
Assert.True(parameters[7].IsOptional);
Assert.True(parameters[7].HasExplicitDefaultValue);
Assert.Equal(1M, parameters[7].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(1M), parameters[7].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[7].GetAttributes().Length); // Optional+DecimalConstantAttribute / DecimalConstantAttribute
};
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
[WorkItem(529775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529775")]
public void IsOptionalVsHasDefaultValue_DateTime()
{
var source = @"
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C
{
public void M0(DateTime p) { }
public void M1(DateTime p = default(DateTime)) { }
public void M2([Optional]DateTime p) { } // no default specified (would be illegal)
public void M3([DateTimeConstant(0)]DateTime p) { } // default of type, not optional
public void M4([DateTimeConstant(1)]DateTime p) { } // not default of type, not optional
public void M5([Optional][DateTimeConstant(0)]DateTime p) { } // default of type, optional
public void M6([Optional][DateTimeConstant(1)]DateTime p) { } // not default of type, optional
}
";
Func<bool, Action<ModuleSymbol>> validator = isFromSource => module =>
{
var methods = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray();
Assert.Equal(7, methods.Length);
var parameters = methods.Select(m => m.Parameters.Single()).ToArray();
Assert.False(parameters[0].IsOptional);
Assert.False(parameters[0].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[0].ExplicitDefaultValue);
Assert.Null(parameters[0].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[0].GetAttributes().Length);
Assert.True(parameters[1].IsOptional);
Assert.True(parameters[1].HasExplicitDefaultValue);
Assert.Null(parameters[1].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Null, parameters[1].ExplicitDefaultConstantValue);
Assert.Equal(0, parameters[1].GetAttributes().Length); // As in dev11, [DateTimeConstant] is not emitted in this case.
Assert.True(parameters[2].IsOptional);
Assert.False(parameters[2].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[2].ExplicitDefaultValue);
Assert.Null(parameters[2].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 1 : 0, parameters[2].GetAttributes().Length);
Assert.False(parameters[3].IsOptional);
Assert.False(parameters[3].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[3].ExplicitDefaultValue);
Assert.False(parameters[3].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(0)) : null, parameters[3].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[3].GetAttributes().Length); // DateTimeConstant
Assert.False(parameters[4].IsOptional);
Assert.False(parameters[4].HasExplicitDefaultValue);
Assert.Throws<InvalidOperationException>(() => parameters[4].ExplicitDefaultValue);
Assert.False(parameters[4].HasMetadataConstantValue);
Assert.Equal(isFromSource ? ConstantValue.Create(new DateTime(1)) : null, parameters[4].ExplicitDefaultConstantValue); // not imported for non-optional parameter
Assert.Equal(1, parameters[4].GetAttributes().Length); // DateTimeConstant
Assert.True(parameters[5].IsOptional);
Assert.True(parameters[5].HasExplicitDefaultValue);
Assert.Equal(new DateTime(0), parameters[5].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(new DateTime(0)), parameters[5].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[5].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant
Assert.True(parameters[6].IsOptional);
Assert.True(parameters[6].HasExplicitDefaultValue);
Assert.Equal(new DateTime(1), parameters[6].ExplicitDefaultValue);
Assert.Equal(ConstantValue.Create(new DateTime(1)), parameters[6].ExplicitDefaultConstantValue);
Assert.Equal(isFromSource ? 2 : 0, parameters[6].GetAttributes().Length); // Optional+DateTimeConstant / DateTimeConstant
};
// TODO: Guess - RefEmit doesn't like DateTime constants.
CompileAndVerify(source, sourceSymbolValidator: validator(true), symbolValidator: validator(false));
}
[Fact]
public void InvalidConversionForDefaultArgument_InIL()
{
var il = @"
.class public auto ansi beforefieldinit P
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method P::.ctor
.method public hidebysig instance int32 M1([opt] int32 s) cil managed
{
.param [1] = ""abc""
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldarg.1
IL_0001: ret
} // end of method P::M1
} // end of class P
";
var csharp = @"
class C
{
public static void Main()
{
P p = new P();
System.Console.Write(p.M1());
}
}
";
var comp = CreateCompilationWithIL(csharp, il, options: TestOptions.DebugExe);
comp.VerifyDiagnostics(
// (7,31): error CS0029: Cannot implicitly convert type 'string' to 'int'
// System.Console.Write(p.M1());
Diagnostic(ErrorCode.ERR_NoImplicitConv, "p.M1()").WithArguments("string", "int").WithLocation(7, 31));
}
[Fact]
public void DefaultArgument_LoopInUsage()
{
var csharp = @"
class C
{
static object F(object param = F()) => param; // 1
}
";
var comp = CreateCompilation(csharp);
comp.VerifyDiagnostics(
// (4,36): error CS1736: Default parameter value for 'param' must be a compile-time constant
// static object F(object param = F()) => param; // 1
Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("param").WithLocation(4, 36));
var method = comp.GetMember<MethodSymbol>("C.F");
var param = method.Parameters.Single();
Assert.Equal(ConstantValue.Bad, param.ExplicitDefaultConstantValue);
}
[Fact]
public void DefaultValue_Boxing()
{
var csharp = @"
class C
{
void M1(object obj = 1) // 1
{
}
C(object obj = System.DayOfWeek.Monday) // 2
{
}
}
";
var comp = CreateCompilation(csharp);
comp.VerifyDiagnostics(
// (4,20): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null
// void M1(object obj = 1) // 1
Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(4, 20),
// (8,14): error CS1763: 'obj' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null
// C(object obj = System.DayOfWeek.Monday) // 2
Diagnostic(ErrorCode.ERR_NotNullRefDefaultParameter, "obj").WithArguments("obj", "object").WithLocation(8, 14));
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Features/CSharp/Portable/ReplacePropertyWithMethods/CSharpReplacePropertyWithMethodsService.ConvertValueToParamRewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.ReplacePropertyWithMethods
{
internal partial class CSharpReplacePropertyWithMethodsService
{
private class ConvertValueToParamRewriter : CSharpSyntaxRewriter
{
public static readonly CSharpSyntaxRewriter Instance = new ConvertValueToParamRewriter();
private ConvertValueToParamRewriter()
{
}
private static XmlNameSyntax ConvertToParam(XmlNameSyntax name)
=> name.ReplaceToken(name.LocalName, SyntaxFactory.Identifier("param"));
public override SyntaxNode VisitXmlElementStartTag(XmlElementStartTagSyntax node)
{
if (!IsValueName(node.Name))
return base.VisitXmlElementStartTag(node);
return node.ReplaceNode(node.Name, ConvertToParam(node.Name))
.AddAttributes(SyntaxFactory.XmlNameAttribute("value"));
}
public override SyntaxNode VisitXmlElementEndTag(XmlElementEndTagSyntax node)
=> IsValueName(node.Name)
? node.ReplaceNode(node.Name, ConvertToParam(node.Name))
: base.VisitXmlElementEndTag(node);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.ReplacePropertyWithMethods
{
internal partial class CSharpReplacePropertyWithMethodsService
{
private class ConvertValueToParamRewriter : CSharpSyntaxRewriter
{
public static readonly CSharpSyntaxRewriter Instance = new ConvertValueToParamRewriter();
private ConvertValueToParamRewriter()
{
}
private static XmlNameSyntax ConvertToParam(XmlNameSyntax name)
=> name.ReplaceToken(name.LocalName, SyntaxFactory.Identifier("param"));
public override SyntaxNode VisitXmlElementStartTag(XmlElementStartTagSyntax node)
{
if (!IsValueName(node.Name))
return base.VisitXmlElementStartTag(node);
return node.ReplaceNode(node.Name, ConvertToParam(node.Name))
.AddAttributes(SyntaxFactory.XmlNameAttribute("value"));
}
public override SyntaxNode VisitXmlElementEndTag(XmlElementEndTagSyntax node)
=> IsValueName(node.Name)
? node.ReplaceNode(node.Name, ConvertToParam(node.Name))
: base.VisitXmlElementEndTag(node);
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Simplification;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Rename
{
[ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared]
internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRenameConflictLanguageService()
{
}
#region "Annotation"
public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters)
{
var renameAnnotationRewriter = new RenameRewriter(parameters);
return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!;
}
private class RenameRewriter : CSharpSyntaxRewriter
{
private readonly DocumentId _documentId;
private readonly RenameAnnotation _renameRenamableSymbolDeclaration;
private readonly Solution _solution;
private readonly string _replacementText;
private readonly string _originalText;
private readonly ICollection<string> _possibleNameConflicts;
private readonly Dictionary<TextSpan, RenameLocation> _renameLocations;
private readonly ISet<TextSpan> _conflictLocations;
private readonly SemanticModel _semanticModel;
private readonly CancellationToken _cancellationToken;
private readonly ISymbol _renamedSymbol;
private readonly IAliasSymbol? _aliasSymbol;
private readonly Location? _renamableDeclarationLocation;
private readonly RenamedSpansTracker _renameSpansTracker;
private readonly bool _isVerbatim;
private readonly bool _replacementTextValid;
private readonly ISimplificationService _simplificationService;
private readonly ISemanticFactsService _semanticFactsService;
private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = new();
private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = new();
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
/// <summary>
/// Flag indicating if we should perform a rename inside string literals.
/// </summary>
private readonly bool _isRenamingInStrings;
/// <summary>
/// Flag indicating if we should perform a rename inside comment trivia.
/// </summary>
private readonly bool _isRenamingInComments;
/// <summary>
/// A map from spans of tokens needing rename within strings or comments to an optional
/// set of specific sub-spans within the token span that
/// have <see cref="_originalText"/> matches and should be renamed.
/// If this sorted set is null, it indicates that sub-spans to rename within the token span
/// are not available, and a regex match should be performed to rename
/// all <see cref="_originalText"/> matches within the span.
/// </summary>
private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans;
public bool AnnotateForComplexification
{
get
{
return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans;
}
}
private int _skipRenameForComplexification;
private bool _isProcessingComplexifiedSpans;
private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans;
private SemanticModel? _speculativeModel;
private int _isProcessingTrivia;
private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan)
{
newSpan = new TextSpan(oldSpan.Start, newSpan.Length);
if (!_isProcessingComplexifiedSpans)
{
_renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan);
}
else
{
RoslynDebug.Assert(_modifiedSubSpans != null);
_modifiedSubSpans.Add((oldSpan, newSpan));
}
}
public RenameRewriter(RenameRewriterParameters parameters)
: base(visitIntoStructuredTrivia: true)
{
_documentId = parameters.Document.Id;
_renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation;
_solution = parameters.OriginalSolution;
_replacementText = parameters.ReplacementText;
_originalText = parameters.OriginalText;
_possibleNameConflicts = parameters.PossibleNameConflicts;
_renameLocations = parameters.RenameLocations;
_conflictLocations = parameters.ConflictLocationSpans;
_cancellationToken = parameters.CancellationToken;
_semanticModel = parameters.SemanticModel;
_renamedSymbol = parameters.RenameSymbol;
_replacementTextValid = parameters.ReplacementTextValid;
_renameSpansTracker = parameters.RenameSpansTracker;
_isRenamingInStrings = parameters.OptionSet.RenameInStrings;
_isRenamingInComments = parameters.OptionSet.RenameInComments;
_stringAndCommentTextSpans = parameters.StringAndCommentTextSpans;
_renameAnnotations = parameters.RenameAnnotations;
_aliasSymbol = _renamedSymbol as IAliasSymbol;
_renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree);
_isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal);
_simplificationService = parameters.Document.Project.LanguageServices.GetRequiredService<ISimplificationService>();
_semanticFactsService = parameters.Document.Project.LanguageServices.GetRequiredService<ISemanticFactsService>();
}
public override SyntaxNode? Visit(SyntaxNode? node)
{
if (node == null)
{
return node;
}
var isInConflictLambdaBody = false;
var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax);
if (lambdas.Count() != 0)
{
foreach (var lambda in lambdas)
{
if (_conflictLocations.Any(cf => cf.Contains(lambda.Span)))
{
isInConflictLambdaBody = true;
break;
}
}
}
var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody);
SyntaxNode result;
// in case the current node was identified as being a complexification target of
// a previous node, we'll handle it accordingly.
if (shouldComplexifyNode)
{
_skipRenameForComplexification++;
result = base.Visit(node)!;
_skipRenameForComplexification--;
result = Complexify(node, result);
}
else
{
result = base.Visit(node)!;
}
return result;
}
private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody)
{
return !isInConflictLambdaBody &&
_skipRenameForComplexification == 0 &&
!_isProcessingComplexifiedSpans &&
_conflictLocations.Contains(node.Span) &&
(node is AttributeSyntax ||
node is AttributeArgumentSyntax ||
node is ConstructorInitializerSyntax ||
node is ExpressionSyntax ||
node is FieldDeclarationSyntax ||
node is StatementSyntax ||
node is CrefSyntax ||
node is XmlNameAttributeSyntax ||
node is TypeConstraintSyntax ||
node is BaseTypeSyntax);
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span);
_isProcessingTrivia += shouldCheckTrivia ? 1 : 0;
var newToken = base.VisitToken(token);
_isProcessingTrivia -= shouldCheckTrivia ? 1 : 0;
// Handle Alias annotations
newToken = UpdateAliasAnnotation(newToken);
// Rename matches in strings and comments
newToken = RenameWithinToken(token, newToken);
// We don't want to annotate XmlName with RenameActionAnnotation
if (newToken.Parent.IsKind(SyntaxKind.XmlName))
{
return newToken;
}
var isRenameLocation = IsRenameLocation(token);
// if this is a reference location, or the identifier token's name could possibly
// be a conflict, we need to process this token
var isOldText = token.ValueText == _originalText;
var tokenNeedsConflictCheck =
isRenameLocation ||
token.ValueText == _replacementText ||
isOldText ||
_possibleNameConflicts.Contains(token.ValueText) ||
IsPossiblyDestructorConflict(token) ||
IsPropertyAccessorNameConflict(token);
if (tokenNeedsConflictCheck)
{
newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken);
if (!_isProcessingComplexifiedSpans)
{
_invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>());
}
}
return newToken;
}
private bool IsPropertyAccessorNameConflict(SyntaxToken token)
=> IsGetPropertyAccessorNameConflict(token)
|| IsSetPropertyAccessorNameConflict(token)
|| IsInitPropertyAccessorNameConflict(token);
private bool IsGetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.GetKeyword)
&& IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax);
private bool IsSetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.SetKeyword)
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsInitPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.InitKeyword)
// using "set" here is intentional. The compiler generates set_PropName for both set and init accessors.
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor)
=> accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration
&& _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal);
private bool IsPossiblyDestructorConflict(SyntaxToken token)
{
return _replacementText == "Finalize" &&
token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.IsKind(SyntaxKind.DestructorDeclaration);
}
private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode)
{
_isProcessingComplexifiedSpans = true;
_modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>();
var annotation = new SyntaxAnnotation();
newNode = newNode.WithAdditionalAnnotations(annotation);
var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?");
var oldSpan = originalNode.Span;
var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0;
newNode = _simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier: null,
expandInsideNode: null,
expandParameter: expandParameter,
cancellationToken: _cancellationToken);
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
newNode = base.Visit(newNode)!;
var newSpan = newNode.Span;
newNode = newNode.WithoutAnnotations(annotation);
newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan });
_renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans);
_modifiedSubSpans = null;
_isProcessingComplexifiedSpans = false;
_speculativeModel = null;
return newNode;
}
private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText)
{
try
{
if (_isProcessingComplexifiedSpans)
{
// Rename Token
if (isRenameLocation)
{
var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault();
if (annotation != null)
{
newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix);
AddModifiedSpan(annotation.OriginalSpan, newToken.Span);
}
else
{
newToken = RenameToken(token, newToken, prefix: null, suffix: null);
}
}
return newToken;
}
var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Workspace, _cancellationToken);
string? suffix = null;
var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor
? newToken.ValueText.Substring(0, newToken.ValueText.IndexOf('_') + 1)
: null;
if (symbols.Length == 1)
{
var symbol = symbols[0];
if (symbol.IsConstructor())
{
symbol = symbol.ContainingSymbol;
}
var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false);
symbol = sourceDefinition ?? symbol;
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.IsImplicitlyDeclared &&
namedTypeSymbol.IsDelegateType() &&
namedTypeSymbol.AssociatedSymbol != null)
{
suffix = "EventHandler";
}
}
// This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace
// conflict is not shown for the namespace so we are tracking this token
if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
return newToken;
}
}
// Rename Token
if (isRenameLocation && !this.AnnotateForComplexification)
{
var oldSpan = token.Span;
newToken = RenameToken(token, newToken, prefix, suffix);
AddModifiedSpan(oldSpan, newToken.Span);
}
var renameDeclarationLocations = await
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false);
var isNamespaceDeclarationReference = false;
if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
isNamespaceDeclarationReference = true;
}
var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken);
var renameAnnotation =
new RenameActionAnnotation(
token.Span,
isRenameLocation,
prefix,
suffix,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: isOldText,
isNamespaceDeclarationReference: isNamespaceDeclarationReference,
isInvocationExpression: false,
isMemberGroupReference: isMemberGroupReference);
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span });
_annotatedIdentifierTokens.Add(token);
if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation())
{
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration);
}
return newToken;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression)
{
var identifierToken = default(SyntaxToken);
var expressionOfInvocation = invocationExpression.Expression;
while (expressionOfInvocation != null)
{
switch (expressionOfInvocation.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier;
break;
case SyntaxKind.SimpleMemberAccessExpression:
identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.QualifiedName:
identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier;
break;
case SyntaxKind.AliasQualifiedName:
identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.ParenthesizedExpression:
expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression;
continue;
}
break;
}
if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken))
{
var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken);
IEnumerable<ISymbol> symbols;
if (symbolInfo.Symbol == null)
{
return null;
}
else
{
symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol);
}
var renameDeclarationLocations =
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(
_solution,
symbols,
_cancellationToken)
.WaitAndGetResult_CanCallOnBackground(_cancellationToken);
var renameAnnotation = new RenameActionAnnotation(
identifierToken.Span,
isRenameLocation: false,
prefix: null,
suffix: null,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: false,
isNamespaceDeclarationReference: false,
isInvocationExpression: true,
isMemberGroupReference: false);
return renameAnnotation;
}
return null;
}
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var result = base.VisitInvocationExpression(node);
RoslynDebug.AssertNotNull(result);
if (_invocationExpressionsNeedingConflictChecks.Contains(node))
{
var renameAnnotation = GetAnnotationForInvocationExpression(node);
if (renameAnnotation != null)
{
result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation);
}
}
return result;
}
private bool IsRenameLocation(SyntaxToken token)
{
if (!_isProcessingComplexifiedSpans)
{
return _renameLocations.ContainsKey(token.Span);
}
else
{
RoslynDebug.Assert(_speculativeModel != null);
if (token.HasAnnotations(AliasAnnotation.Kind))
{
return false;
}
if (token.HasAnnotations(RenameAnnotation.Kind))
{
return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation;
}
if (token.Parent is SimpleNameSyntax && !token.IsKind(SyntaxKind.GlobalKeyword) && token.Parent.Parent.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedCref, SyntaxKind.QualifiedName))
{
var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol;
if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable &&
(Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey())))
{
return true;
}
}
return false;
}
}
private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken)
{
if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind))
{
newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText);
}
return newToken;
}
private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix)
{
var parent = oldToken.Parent!;
var currentNewIdentifier = _isVerbatim ? _replacementText.Substring(1) : _replacementText;
var oldIdentifier = newToken.ValueText;
var isAttributeName = SyntaxFacts.IsAttributeName(parent);
if (isAttributeName)
{
if (oldIdentifier != _renamedSymbol.Name)
{
if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix))
{
currentNewIdentifier = withoutSuffix;
}
}
}
else
{
if (!string.IsNullOrEmpty(prefix))
{
currentNewIdentifier = prefix + currentNewIdentifier;
}
if (!string.IsNullOrEmpty(suffix))
{
currentNewIdentifier += suffix;
}
}
// determine the canonical identifier name (unescaped, no unicode escaping, ...)
var valueText = currentNewIdentifier;
var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier);
if (parsedIdentifier.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName))
{
valueText = identifierName.Identifier.ValueText;
}
}
// TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well.
// <param name="\u... is invalid.
// if it's an attribute name we don't mess with the escaping because it might change overload resolution
newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier())
? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia))
: newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia));
if (_replacementTextValid)
{
if (newToken.IsVerbatimIdentifier())
{
// a reference location should always be tried to be unescaped, whether it was escaped before rename
// or the replacement itself is escaped.
newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation);
}
else
{
newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent);
}
}
return newToken;
}
private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral)
{
var originalString = newToken.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace);
if (replacedString != originalString)
{
var oldSpan = oldToken.Span;
newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia);
AddModifiedSpan(oldSpan, newToken.Span);
return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return newToken;
}
private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList)
{
return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) =>
{
if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment())
{
return RenameInCommentTrivia(newTrivia);
}
return newTrivia;
});
}
private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia)
{
var originalString = trivia.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText);
if (replacedString != originalString)
{
var oldSpan = trivia.Span;
var newTrivia = SyntaxFactory.Comment(replacedString);
AddModifiedSpan(oldSpan, newTrivia.Span);
return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return trivia;
}
private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken)
{
ImmutableSortedSet<TextSpan>? subSpansToReplace = null;
if (_isProcessingComplexifiedSpans ||
(_isProcessingTrivia == 0 &&
!_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace)))
{
return newToken;
}
if (_isRenamingInStrings || subSpansToReplace?.Count > 0)
{
if (newToken.IsKind(SyntaxKind.StringLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal);
}
else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) =>
SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia));
}
}
if (_isRenamingInComments)
{
if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral);
}
else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText)
{
var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia);
newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span }));
AddModifiedSpan(oldToken.Span, newToken.Span);
}
if (newToken.HasLeadingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia);
}
}
if (newToken.HasTrailingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia);
}
}
}
return newToken;
}
}
#endregion
#region "Declaration Conflicts"
public override bool LocalVariableConflict(
SyntaxToken token,
IEnumerable<ISymbol> newReferencedSymbols)
{
if (token.Parent.IsKind(SyntaxKind.IdentifierName, out ExpressionSyntax? expression) &&
token.Parent.IsParentKind(SyntaxKind.InvocationExpression) &&
token.GetPreviousToken().Kind() != SyntaxKind.DotToken &&
token.GetNextToken().Kind() != SyntaxKind.DotToken)
{
var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (enclosingMemberDeclaration != null)
{
var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText];
if (locals.Length > 0)
{
// This unqualified invocation name matches the name of an existing local
// or parameter. Report a conflict if the matching local/parameter is not
// a delegate type.
var relevantLocals = newReferencedSymbols
.Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText);
if (relevantLocals.Count() != 1)
{
return true;
}
var matchingLocal = relevantLocals.Single();
var invocationTargetsLocalOfDelegateType =
(matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) ||
(matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType());
return !invocationTargetsLocalOfDelegateType;
}
}
}
return false;
}
public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync(
string replacementText,
ISymbol renamedSymbol,
ISymbol renameSymbol,
IEnumerable<ISymbol> referencedSymbols,
Solution baseSolution,
Solution newSolution,
IDictionary<Location, Location> reverseMappedLocations,
CancellationToken cancellationToken)
{
try
{
using var _ = ArrayBuilder<Location>.GetInstance(out var conflicts);
// If we're renaming a named type, we can conflict with members w/ our same name. Note:
// this doesn't apply to enums.
if (renamedSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } namedType)
AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations);
// If we're contained in a named type (we may be a named type ourself!) then we have a
// conflict. NOTE(cyrusn): This does not apply to enums.
if (renamedSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } containingNamedType &&
containingNamedType.Name == renamedSymbol.Name)
{
AddSymbolSourceSpans(conflicts, SpecializedCollections.SingletonEnumerable(containingNamedType), reverseMappedLocations);
}
if (renamedSymbol.Kind == SymbolKind.Parameter ||
renamedSymbol.Kind == SymbolKind.Local ||
renamedSymbol.Kind == SymbolKind.RangeVariable)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
// If this is a parameter symbol for a partial method definition, be sure we visited
// the implementation part's body.
if (renamedSymbol is IParameterSymbol renamedParameterSymbol &&
renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.PartialImplementationPart != null)
{
var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal];
token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken);
memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
}
else if (renamedSymbol.Kind == SymbolKind.Label)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LabelConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
else if (renamedSymbol.Kind == SymbolKind.Method)
{
conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t]));
// we allow renaming overrides of VB property accessors with parameters in C#.
// VB has a special rule that properties are not allowed to have the same name as any of the parameters.
// Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#.
var properties = new List<ISymbol>();
foreach (var referencedSymbol in referencedSymbols)
{
var property = await RenameLocations.ReferenceProcessing.TryGetPropertyFromAccessorOrAnOverrideAsync(
referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false);
if (property != null)
properties.Add(property);
}
AddConflictingParametersOfProperties(properties.Distinct(), replacementText, conflicts);
}
else if (renamedSymbol.Kind == SymbolKind.Alias)
{
// in C# there can only be one using with the same alias name in the same block (top of file of namespace).
// It's ok to redefine the alias in different blocks.
var location = renamedSymbol.Locations.Single();
var tree = location.SourceTree;
Contract.ThrowIfNull(tree);
var token = await tree.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!;
var namespaceDecl = token.Parent.Ancestors().OfType<BaseNamespaceDeclarationSyntax>().FirstOrDefault();
SyntaxList<UsingDirectiveSyntax> usings;
if (namespaceDecl != null)
{
usings = namespaceDecl.Usings;
}
else
{
var compilationUnit = (CompilationUnitSyntax)await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
usings = compilationUnit.Usings;
}
foreach (var usingDirective in usings)
{
if (usingDirective.Alias != null && usingDirective != currentUsing)
{
if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]);
}
}
}
else if (renamedSymbol.Kind == SymbolKind.TypeParameter)
{
foreach (var location in renamedSymbol.Locations)
{
var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentTypeParameter = token.Parent!;
foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters)
{
if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]);
}
}
}
// if the renamed symbol is a type member, it's name should not conflict with a type parameter
if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol))
{
var conflictingLocations = renamedSymbol.ContainingType.TypeParameters
.Where(t => t.Name == renamedSymbol.Name)
.SelectMany(t => t.Locations);
foreach (var location in conflictingLocations)
{
var typeParameterToken = location.FindToken(cancellationToken);
conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]);
}
}
return conflicts.ToImmutable();
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
try
{
if (symbol.IsPropertyAccessor())
{
var property = ((IMethodSymbol)symbol).AssociatedSymbol!;
return property.Language == LanguageNames.VisualBasic ? property : null;
}
if (symbol.IsOverride && symbol.GetOverriddenMember() != null)
{
var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false);
if (originalSourceSymbol != null)
{
return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false);
}
}
return null;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static void AddSymbolSourceSpans(
ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols,
IDictionary<Location, Location> reverseMappedLocations)
{
foreach (var symbol in symbols)
{
foreach (var location in symbol.Locations)
{
// reverseMappedLocations may not contain the location if the location's token
// does not contain the text of it's name (e.g. the getter of "int X { get; }"
// does not contain the text "get_X" so conflicting renames to "get_X" will not
// have added the getter to reverseMappedLocations).
if (location.IsInSource && reverseMappedLocations.ContainsKey(location))
{
conflicts.Add(reverseMappedLocations[location]);
}
}
}
}
public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync(
ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken)
{
// Handle renaming of symbols used for foreach
var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property &&
string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0;
implicitReferencesMightConflict =
implicitReferencesMightConflict ||
(renameSymbol.Kind == SymbolKind.Method &&
(string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0));
// TODO: handle Dispose for using statement and Add methods for collection initializers.
if (implicitReferencesMightConflict)
{
if (renamedSymbol.Name != renameSymbol.Name)
{
foreach (var implicitReferenceLocation in implicitReferenceLocations)
{
var token = await implicitReferenceLocation.Location.SourceTree!.GetTouchingTokenAsync(
implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia: false).ConfigureAwait(false);
switch (token.Kind())
{
case SyntaxKind.ForEachKeyword:
return ImmutableArray.Create(((CommonForEachStatementSyntax)token.Parent!).Expression.GetLocation());
case SyntaxKind.AwaitKeyword:
return ImmutableArray.Create(token.GetLocation());
}
if (token.Parent.IsInDeconstructionLeft(out var deconstructionLeft))
{
return ImmutableArray.Create(deconstructionLeft.GetLocation());
}
}
}
}
return ImmutableArray<Location>.Empty;
}
public override ImmutableArray<Location> ComputePossibleImplicitUsageConflicts(
ISymbol renamedSymbol,
SemanticModel semanticModel,
Location originalDeclarationLocation,
int newDeclarationLocationStartingPosition,
CancellationToken cancellationToken)
{
// TODO: support other implicitly used methods like dispose
if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0)
{
// TODO: partial methods currently only show the location where the rename happens as a conflict.
// Consider showing both locations as a conflict.
var baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault();
if (baseType != null)
{
var implicitSymbols = semanticModel.LookupSymbols(
newDeclarationLocationStartingPosition,
baseType,
renamedSymbol.Name)
.Where(sym => !sym.Equals(renamedSymbol));
foreach (var symbol in implicitSymbols)
{
if (symbol.GetAllTypeArguments().Length != 0)
{
continue;
}
if (symbol.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)symbol;
if (symbol.Name == "MoveNext")
{
if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
else if (symbol.Name == "GetEnumerator")
{
// we are a bit pessimistic here.
// To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach
if (!method.ReturnsVoid &&
!method.Parameters.Any())
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current")
{
var property = (IPropertySymbol)symbol;
if (!property.Parameters.Any() && !property.IsWriteOnly)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
}
}
return ImmutableArray<Location>.Empty;
}
#endregion
public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacementText, ICollection<string> possibleNameConflicts)
{
if (replacementText.EndsWith("Attribute", StringComparison.Ordinal) && replacementText.Length > 9)
{
var conflict = replacementText.Substring(0, replacementText.Length - 9);
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
if (symbol.Kind == SymbolKind.Property)
{
foreach (var conflict in new string[] { "_" + replacementText, "get_" + replacementText, "set_" + replacementText })
{
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
}
// in C# we also need to add the valueText because it can be different from the text in source
// e.g. it can contain escaped unicode characters. Otherwise conflicts would be detected for
// v\u0061r and var or similar.
var valueText = replacementText;
var kind = SyntaxFacts.GetKeywordKind(replacementText);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var name = SyntaxFactory.ParseName(replacementText);
if (name.Kind() == SyntaxKind.IdentifierName)
{
valueText = ((IdentifierNameSyntax)name).Identifier.ValueText;
}
}
// this also covers the case of an escaped replacementText
if (valueText != replacementText)
{
possibleNameConflicts.Add(valueText);
}
}
/// <summary>
/// Gets the top most enclosing statement or CrefSyntax as target to call MakeExplicit on.
/// It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing
/// statement of this lambda.
/// </summary>
/// <param name="token">The token to get the complexification target for.</param>
/// <returns></returns>
public override SyntaxNode? GetExpansionTargetForLocation(SyntaxToken token)
=> GetExpansionTarget(token);
private static SyntaxNode? GetExpansionTarget(SyntaxToken token)
{
// get the directly enclosing statement
var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault();
// System.Func<int, int> myFunc = arg => X;
var possibleLambdaExpression = enclosingStatement == null
? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).FirstOrDefault()
: null;
if (possibleLambdaExpression != null)
{
var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression);
if (lambdaExpression.Body is ExpressionSyntax)
{
return lambdaExpression.Body;
}
}
// int M() => X;
var possibleArrowExpressionClause = enclosingStatement == null
? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault()
: null;
if (possibleArrowExpressionClause != null)
{
return possibleArrowExpressionClause.Expression;
}
var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault();
if (enclosingNameMemberCrefOrnull != null)
{
if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax)
{
enclosingNameMemberCrefOrnull = null;
}
}
var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault();
if (enclosingXmlNameAttr != null)
{
return null;
}
var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault();
if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax)
{
return enclosingInitializer.Value;
}
var attributeSyntax = token.GetAncestor<AttributeSyntax>();
if (attributeSyntax != null)
{
return attributeSyntax;
}
// there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax
return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault();
}
#region "Helper Methods"
public override bool IsIdentifierValid(string replacementText, ISyntaxFactsService syntaxFactsService)
{
// Identifiers we never consider valid to rename to.
switch (replacementText)
{
case "var":
case "dynamic":
case "unmanaged":
case "notnull":
return false;
}
var escapedIdentifier = replacementText.StartsWith("@", StringComparison.Ordinal)
? replacementText : "@" + replacementText;
// Make sure we got an identifier.
if (!syntaxFactsService.IsValidIdentifier(escapedIdentifier))
{
// We still don't have an identifier, so let's fail
return false;
}
return true;
}
/// <summary>
/// Gets the semantic model for the given node.
/// If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel.
/// Otherwise, returns a speculative model.
/// The assumption for the later case is that span start position of the given node in it's syntax tree is same as
/// the span start of the original node in the original syntax tree.
/// </summary>
public static SemanticModel? GetSemanticModelForNode(SyntaxNode node, SemanticModel originalSemanticModel)
{
if (node.SyntaxTree == originalSemanticModel.SyntaxTree)
{
// This is possible if the previous rename phase didn't rewrite any nodes in this tree.
return originalSemanticModel;
}
var nodeToSpeculate = node.GetAncestorsOrThis(n => SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault();
if (nodeToSpeculate == null)
{
if (node.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMember))
{
nodeToSpeculate = nameMember.Name;
}
else if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax? qualifiedCref))
{
nodeToSpeculate = qualifiedCref.Container;
}
else if (node.IsKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax? typeConstraint))
{
nodeToSpeculate = typeConstraint.Type;
}
else if (node is BaseTypeSyntax baseType)
{
nodeToSpeculate = baseType.Type;
}
else
{
return null;
}
}
var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
var position = nodeToSpeculate.SpanStart;
return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, originalSemanticModel, position, isInNamespaceOrTypeContext);
}
#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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Simplification;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Rename
{
[ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared]
internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRenameConflictLanguageService()
{
}
#region "Annotation"
public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters)
{
var renameAnnotationRewriter = new RenameRewriter(parameters);
return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!;
}
private class RenameRewriter : CSharpSyntaxRewriter
{
private readonly DocumentId _documentId;
private readonly RenameAnnotation _renameRenamableSymbolDeclaration;
private readonly Solution _solution;
private readonly string _replacementText;
private readonly string _originalText;
private readonly ICollection<string> _possibleNameConflicts;
private readonly Dictionary<TextSpan, RenameLocation> _renameLocations;
private readonly ISet<TextSpan> _conflictLocations;
private readonly SemanticModel _semanticModel;
private readonly CancellationToken _cancellationToken;
private readonly ISymbol _renamedSymbol;
private readonly IAliasSymbol? _aliasSymbol;
private readonly Location? _renamableDeclarationLocation;
private readonly RenamedSpansTracker _renameSpansTracker;
private readonly bool _isVerbatim;
private readonly bool _replacementTextValid;
private readonly ISimplificationService _simplificationService;
private readonly ISemanticFactsService _semanticFactsService;
private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = new();
private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = new();
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
/// <summary>
/// Flag indicating if we should perform a rename inside string literals.
/// </summary>
private readonly bool _isRenamingInStrings;
/// <summary>
/// Flag indicating if we should perform a rename inside comment trivia.
/// </summary>
private readonly bool _isRenamingInComments;
/// <summary>
/// A map from spans of tokens needing rename within strings or comments to an optional
/// set of specific sub-spans within the token span that
/// have <see cref="_originalText"/> matches and should be renamed.
/// If this sorted set is null, it indicates that sub-spans to rename within the token span
/// are not available, and a regex match should be performed to rename
/// all <see cref="_originalText"/> matches within the span.
/// </summary>
private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans;
public bool AnnotateForComplexification
{
get
{
return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans;
}
}
private int _skipRenameForComplexification;
private bool _isProcessingComplexifiedSpans;
private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans;
private SemanticModel? _speculativeModel;
private int _isProcessingTrivia;
private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan)
{
newSpan = new TextSpan(oldSpan.Start, newSpan.Length);
if (!_isProcessingComplexifiedSpans)
{
_renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan);
}
else
{
RoslynDebug.Assert(_modifiedSubSpans != null);
_modifiedSubSpans.Add((oldSpan, newSpan));
}
}
public RenameRewriter(RenameRewriterParameters parameters)
: base(visitIntoStructuredTrivia: true)
{
_documentId = parameters.Document.Id;
_renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation;
_solution = parameters.OriginalSolution;
_replacementText = parameters.ReplacementText;
_originalText = parameters.OriginalText;
_possibleNameConflicts = parameters.PossibleNameConflicts;
_renameLocations = parameters.RenameLocations;
_conflictLocations = parameters.ConflictLocationSpans;
_cancellationToken = parameters.CancellationToken;
_semanticModel = parameters.SemanticModel;
_renamedSymbol = parameters.RenameSymbol;
_replacementTextValid = parameters.ReplacementTextValid;
_renameSpansTracker = parameters.RenameSpansTracker;
_isRenamingInStrings = parameters.OptionSet.RenameInStrings;
_isRenamingInComments = parameters.OptionSet.RenameInComments;
_stringAndCommentTextSpans = parameters.StringAndCommentTextSpans;
_renameAnnotations = parameters.RenameAnnotations;
_aliasSymbol = _renamedSymbol as IAliasSymbol;
_renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree);
_isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal);
_simplificationService = parameters.Document.Project.LanguageServices.GetRequiredService<ISimplificationService>();
_semanticFactsService = parameters.Document.Project.LanguageServices.GetRequiredService<ISemanticFactsService>();
}
public override SyntaxNode? Visit(SyntaxNode? node)
{
if (node == null)
{
return node;
}
var isInConflictLambdaBody = false;
var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax);
if (lambdas.Count() != 0)
{
foreach (var lambda in lambdas)
{
if (_conflictLocations.Any(cf => cf.Contains(lambda.Span)))
{
isInConflictLambdaBody = true;
break;
}
}
}
var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody);
SyntaxNode result;
// in case the current node was identified as being a complexification target of
// a previous node, we'll handle it accordingly.
if (shouldComplexifyNode)
{
_skipRenameForComplexification++;
result = base.Visit(node)!;
_skipRenameForComplexification--;
result = Complexify(node, result);
}
else
{
result = base.Visit(node)!;
}
return result;
}
private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody)
{
return !isInConflictLambdaBody &&
_skipRenameForComplexification == 0 &&
!_isProcessingComplexifiedSpans &&
_conflictLocations.Contains(node.Span) &&
(node is AttributeSyntax ||
node is AttributeArgumentSyntax ||
node is ConstructorInitializerSyntax ||
node is ExpressionSyntax ||
node is FieldDeclarationSyntax ||
node is StatementSyntax ||
node is CrefSyntax ||
node is XmlNameAttributeSyntax ||
node is TypeConstraintSyntax ||
node is BaseTypeSyntax);
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span);
_isProcessingTrivia += shouldCheckTrivia ? 1 : 0;
var newToken = base.VisitToken(token);
_isProcessingTrivia -= shouldCheckTrivia ? 1 : 0;
// Handle Alias annotations
newToken = UpdateAliasAnnotation(newToken);
// Rename matches in strings and comments
newToken = RenameWithinToken(token, newToken);
// We don't want to annotate XmlName with RenameActionAnnotation
if (newToken.Parent.IsKind(SyntaxKind.XmlName))
{
return newToken;
}
var isRenameLocation = IsRenameLocation(token);
// if this is a reference location, or the identifier token's name could possibly
// be a conflict, we need to process this token
var isOldText = token.ValueText == _originalText;
var tokenNeedsConflictCheck =
isRenameLocation ||
token.ValueText == _replacementText ||
isOldText ||
_possibleNameConflicts.Contains(token.ValueText) ||
IsPossiblyDestructorConflict(token) ||
IsPropertyAccessorNameConflict(token);
if (tokenNeedsConflictCheck)
{
newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken);
if (!_isProcessingComplexifiedSpans)
{
_invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>());
}
}
return newToken;
}
private bool IsPropertyAccessorNameConflict(SyntaxToken token)
=> IsGetPropertyAccessorNameConflict(token)
|| IsSetPropertyAccessorNameConflict(token)
|| IsInitPropertyAccessorNameConflict(token);
private bool IsGetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.GetKeyword)
&& IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax);
private bool IsSetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.SetKeyword)
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsInitPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.InitKeyword)
// using "set" here is intentional. The compiler generates set_PropName for both set and init accessors.
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor)
=> accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration
&& _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal);
private bool IsPossiblyDestructorConflict(SyntaxToken token)
{
return _replacementText == "Finalize" &&
token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.IsKind(SyntaxKind.DestructorDeclaration);
}
private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode)
{
_isProcessingComplexifiedSpans = true;
_modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>();
var annotation = new SyntaxAnnotation();
newNode = newNode.WithAdditionalAnnotations(annotation);
var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?");
var oldSpan = originalNode.Span;
var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0;
newNode = _simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier: null,
expandInsideNode: null,
expandParameter: expandParameter,
cancellationToken: _cancellationToken);
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
newNode = base.Visit(newNode)!;
var newSpan = newNode.Span;
newNode = newNode.WithoutAnnotations(annotation);
newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan });
_renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans);
_modifiedSubSpans = null;
_isProcessingComplexifiedSpans = false;
_speculativeModel = null;
return newNode;
}
private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText)
{
try
{
if (_isProcessingComplexifiedSpans)
{
// Rename Token
if (isRenameLocation)
{
var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault();
if (annotation != null)
{
newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix);
AddModifiedSpan(annotation.OriginalSpan, newToken.Span);
}
else
{
newToken = RenameToken(token, newToken, prefix: null, suffix: null);
}
}
return newToken;
}
var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Workspace, _cancellationToken);
string? suffix = null;
var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor
? newToken.ValueText.Substring(0, newToken.ValueText.IndexOf('_') + 1)
: null;
if (symbols.Length == 1)
{
var symbol = symbols[0];
if (symbol.IsConstructor())
{
symbol = symbol.ContainingSymbol;
}
var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false);
symbol = sourceDefinition ?? symbol;
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.IsImplicitlyDeclared &&
namedTypeSymbol.IsDelegateType() &&
namedTypeSymbol.AssociatedSymbol != null)
{
suffix = "EventHandler";
}
}
// This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace
// conflict is not shown for the namespace so we are tracking this token
if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
return newToken;
}
}
// Rename Token
if (isRenameLocation && !this.AnnotateForComplexification)
{
var oldSpan = token.Span;
newToken = RenameToken(token, newToken, prefix, suffix);
AddModifiedSpan(oldSpan, newToken.Span);
}
var renameDeclarationLocations = await
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false);
var isNamespaceDeclarationReference = false;
if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
isNamespaceDeclarationReference = true;
}
var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken);
var renameAnnotation =
new RenameActionAnnotation(
token.Span,
isRenameLocation,
prefix,
suffix,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: isOldText,
isNamespaceDeclarationReference: isNamespaceDeclarationReference,
isInvocationExpression: false,
isMemberGroupReference: isMemberGroupReference);
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span });
_annotatedIdentifierTokens.Add(token);
if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation())
{
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration);
}
return newToken;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression)
{
var identifierToken = default(SyntaxToken);
var expressionOfInvocation = invocationExpression.Expression;
while (expressionOfInvocation != null)
{
switch (expressionOfInvocation.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier;
break;
case SyntaxKind.SimpleMemberAccessExpression:
identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.QualifiedName:
identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier;
break;
case SyntaxKind.AliasQualifiedName:
identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.ParenthesizedExpression:
expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression;
continue;
}
break;
}
if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken))
{
var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken);
IEnumerable<ISymbol> symbols;
if (symbolInfo.Symbol == null)
{
return null;
}
else
{
symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol);
}
var renameDeclarationLocations =
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(
_solution,
symbols,
_cancellationToken)
.WaitAndGetResult_CanCallOnBackground(_cancellationToken);
var renameAnnotation = new RenameActionAnnotation(
identifierToken.Span,
isRenameLocation: false,
prefix: null,
suffix: null,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: false,
isNamespaceDeclarationReference: false,
isInvocationExpression: true,
isMemberGroupReference: false);
return renameAnnotation;
}
return null;
}
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var result = base.VisitInvocationExpression(node);
RoslynDebug.AssertNotNull(result);
if (_invocationExpressionsNeedingConflictChecks.Contains(node))
{
var renameAnnotation = GetAnnotationForInvocationExpression(node);
if (renameAnnotation != null)
{
result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation);
}
}
return result;
}
private bool IsRenameLocation(SyntaxToken token)
{
if (!_isProcessingComplexifiedSpans)
{
return _renameLocations.ContainsKey(token.Span);
}
else
{
RoslynDebug.Assert(_speculativeModel != null);
if (token.HasAnnotations(AliasAnnotation.Kind))
{
return false;
}
if (token.HasAnnotations(RenameAnnotation.Kind))
{
return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation;
}
if (token.Parent is SimpleNameSyntax && !token.IsKind(SyntaxKind.GlobalKeyword) && token.Parent.Parent.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedCref, SyntaxKind.QualifiedName))
{
var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol;
if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable &&
(Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey())))
{
return true;
}
}
return false;
}
}
private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken)
{
if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind))
{
newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText);
}
return newToken;
}
private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix)
{
var parent = oldToken.Parent!;
var currentNewIdentifier = _isVerbatim ? _replacementText.Substring(1) : _replacementText;
var oldIdentifier = newToken.ValueText;
var isAttributeName = SyntaxFacts.IsAttributeName(parent);
if (isAttributeName)
{
if (oldIdentifier != _renamedSymbol.Name)
{
if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix))
{
currentNewIdentifier = withoutSuffix;
}
}
}
else
{
if (!string.IsNullOrEmpty(prefix))
{
currentNewIdentifier = prefix + currentNewIdentifier;
}
if (!string.IsNullOrEmpty(suffix))
{
currentNewIdentifier += suffix;
}
}
// determine the canonical identifier name (unescaped, no unicode escaping, ...)
var valueText = currentNewIdentifier;
var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier);
if (parsedIdentifier.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName))
{
valueText = identifierName.Identifier.ValueText;
}
}
// TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well.
// <param name="\u... is invalid.
// if it's an attribute name we don't mess with the escaping because it might change overload resolution
newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier())
? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia))
: newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia));
if (_replacementTextValid)
{
if (newToken.IsVerbatimIdentifier())
{
// a reference location should always be tried to be unescaped, whether it was escaped before rename
// or the replacement itself is escaped.
newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation);
}
else
{
newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent);
}
}
return newToken;
}
private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral)
{
var originalString = newToken.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace);
if (replacedString != originalString)
{
var oldSpan = oldToken.Span;
newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia);
AddModifiedSpan(oldSpan, newToken.Span);
return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return newToken;
}
private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList)
{
return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) =>
{
if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment())
{
return RenameInCommentTrivia(newTrivia);
}
return newTrivia;
});
}
private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia)
{
var originalString = trivia.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText);
if (replacedString != originalString)
{
var oldSpan = trivia.Span;
var newTrivia = SyntaxFactory.Comment(replacedString);
AddModifiedSpan(oldSpan, newTrivia.Span);
return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return trivia;
}
private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken)
{
ImmutableSortedSet<TextSpan>? subSpansToReplace = null;
if (_isProcessingComplexifiedSpans ||
(_isProcessingTrivia == 0 &&
!_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace)))
{
return newToken;
}
if (_isRenamingInStrings || subSpansToReplace?.Count > 0)
{
if (newToken.IsKind(SyntaxKind.StringLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal);
}
else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) =>
SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia));
}
}
if (_isRenamingInComments)
{
if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral);
}
else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText)
{
var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia);
newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span }));
AddModifiedSpan(oldToken.Span, newToken.Span);
}
if (newToken.HasLeadingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia);
}
}
if (newToken.HasTrailingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia);
}
}
}
return newToken;
}
}
#endregion
#region "Declaration Conflicts"
public override bool LocalVariableConflict(
SyntaxToken token,
IEnumerable<ISymbol> newReferencedSymbols)
{
if (token.Parent.IsKind(SyntaxKind.IdentifierName, out ExpressionSyntax? expression) &&
token.Parent.IsParentKind(SyntaxKind.InvocationExpression) &&
token.GetPreviousToken().Kind() != SyntaxKind.DotToken &&
token.GetNextToken().Kind() != SyntaxKind.DotToken)
{
var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (enclosingMemberDeclaration != null)
{
var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText];
if (locals.Length > 0)
{
// This unqualified invocation name matches the name of an existing local
// or parameter. Report a conflict if the matching local/parameter is not
// a delegate type.
var relevantLocals = newReferencedSymbols
.Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText);
if (relevantLocals.Count() != 1)
{
return true;
}
var matchingLocal = relevantLocals.Single();
var invocationTargetsLocalOfDelegateType =
(matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) ||
(matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType());
return !invocationTargetsLocalOfDelegateType;
}
}
}
return false;
}
public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync(
string replacementText,
ISymbol renamedSymbol,
ISymbol renameSymbol,
IEnumerable<ISymbol> referencedSymbols,
Solution baseSolution,
Solution newSolution,
IDictionary<Location, Location> reverseMappedLocations,
CancellationToken cancellationToken)
{
try
{
using var _ = ArrayBuilder<Location>.GetInstance(out var conflicts);
// If we're renaming a named type, we can conflict with members w/ our same name. Note:
// this doesn't apply to enums.
if (renamedSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } namedType)
AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations);
// If we're contained in a named type (we may be a named type ourself!) then we have a
// conflict. NOTE(cyrusn): This does not apply to enums.
if (renamedSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } containingNamedType &&
containingNamedType.Name == renamedSymbol.Name)
{
AddSymbolSourceSpans(conflicts, SpecializedCollections.SingletonEnumerable(containingNamedType), reverseMappedLocations);
}
if (renamedSymbol.Kind == SymbolKind.Parameter ||
renamedSymbol.Kind == SymbolKind.Local ||
renamedSymbol.Kind == SymbolKind.RangeVariable)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
// If this is a parameter symbol for a partial method definition, be sure we visited
// the implementation part's body.
if (renamedSymbol is IParameterSymbol renamedParameterSymbol &&
renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.PartialImplementationPart != null)
{
var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal];
token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken);
memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
}
else if (renamedSymbol.Kind == SymbolKind.Label)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LabelConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
else if (renamedSymbol.Kind == SymbolKind.Method)
{
conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t]));
// we allow renaming overrides of VB property accessors with parameters in C#.
// VB has a special rule that properties are not allowed to have the same name as any of the parameters.
// Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#.
var properties = new List<ISymbol>();
foreach (var referencedSymbol in referencedSymbols)
{
var property = await RenameLocations.ReferenceProcessing.TryGetPropertyFromAccessorOrAnOverrideAsync(
referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false);
if (property != null)
properties.Add(property);
}
AddConflictingParametersOfProperties(properties.Distinct(), replacementText, conflicts);
}
else if (renamedSymbol.Kind == SymbolKind.Alias)
{
// in C# there can only be one using with the same alias name in the same block (top of file of namespace).
// It's ok to redefine the alias in different blocks.
var location = renamedSymbol.Locations.Single();
var tree = location.SourceTree;
Contract.ThrowIfNull(tree);
var token = await tree.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!;
var namespaceDecl = token.Parent.Ancestors().OfType<BaseNamespaceDeclarationSyntax>().FirstOrDefault();
SyntaxList<UsingDirectiveSyntax> usings;
if (namespaceDecl != null)
{
usings = namespaceDecl.Usings;
}
else
{
var compilationUnit = (CompilationUnitSyntax)await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
usings = compilationUnit.Usings;
}
foreach (var usingDirective in usings)
{
if (usingDirective.Alias != null && usingDirective != currentUsing)
{
if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]);
}
}
}
else if (renamedSymbol.Kind == SymbolKind.TypeParameter)
{
foreach (var location in renamedSymbol.Locations)
{
var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentTypeParameter = token.Parent!;
foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters)
{
if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]);
}
}
}
// if the renamed symbol is a type member, it's name should not conflict with a type parameter
if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol))
{
var conflictingLocations = renamedSymbol.ContainingType.TypeParameters
.Where(t => t.Name == renamedSymbol.Name)
.SelectMany(t => t.Locations);
foreach (var location in conflictingLocations)
{
var typeParameterToken = location.FindToken(cancellationToken);
conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]);
}
}
return conflicts.ToImmutable();
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
try
{
if (symbol.IsPropertyAccessor())
{
var property = ((IMethodSymbol)symbol).AssociatedSymbol!;
return property.Language == LanguageNames.VisualBasic ? property : null;
}
if (symbol.IsOverride && symbol.GetOverriddenMember() != null)
{
var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false);
if (originalSourceSymbol != null)
{
return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false);
}
}
return null;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static void AddSymbolSourceSpans(
ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols,
IDictionary<Location, Location> reverseMappedLocations)
{
foreach (var symbol in symbols)
{
foreach (var location in symbol.Locations)
{
// reverseMappedLocations may not contain the location if the location's token
// does not contain the text of it's name (e.g. the getter of "int X { get; }"
// does not contain the text "get_X" so conflicting renames to "get_X" will not
// have added the getter to reverseMappedLocations).
if (location.IsInSource && reverseMappedLocations.ContainsKey(location))
{
conflicts.Add(reverseMappedLocations[location]);
}
}
}
}
public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync(
ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken)
{
// Handle renaming of symbols used for foreach
var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property &&
string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0;
implicitReferencesMightConflict =
implicitReferencesMightConflict ||
(renameSymbol.Kind == SymbolKind.Method &&
(string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0));
// TODO: handle Dispose for using statement and Add methods for collection initializers.
if (implicitReferencesMightConflict)
{
if (renamedSymbol.Name != renameSymbol.Name)
{
foreach (var implicitReferenceLocation in implicitReferenceLocations)
{
var token = await implicitReferenceLocation.Location.SourceTree!.GetTouchingTokenAsync(
implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia: false).ConfigureAwait(false);
switch (token.Kind())
{
case SyntaxKind.ForEachKeyword:
return ImmutableArray.Create(((CommonForEachStatementSyntax)token.Parent!).Expression.GetLocation());
case SyntaxKind.AwaitKeyword:
return ImmutableArray.Create(token.GetLocation());
}
if (token.Parent.IsInDeconstructionLeft(out var deconstructionLeft))
{
return ImmutableArray.Create(deconstructionLeft.GetLocation());
}
}
}
}
return ImmutableArray<Location>.Empty;
}
public override ImmutableArray<Location> ComputePossibleImplicitUsageConflicts(
ISymbol renamedSymbol,
SemanticModel semanticModel,
Location originalDeclarationLocation,
int newDeclarationLocationStartingPosition,
CancellationToken cancellationToken)
{
// TODO: support other implicitly used methods like dispose
if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0)
{
// TODO: partial methods currently only show the location where the rename happens as a conflict.
// Consider showing both locations as a conflict.
var baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault();
if (baseType != null)
{
var implicitSymbols = semanticModel.LookupSymbols(
newDeclarationLocationStartingPosition,
baseType,
renamedSymbol.Name)
.Where(sym => !sym.Equals(renamedSymbol));
foreach (var symbol in implicitSymbols)
{
if (symbol.GetAllTypeArguments().Length != 0)
{
continue;
}
if (symbol.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)symbol;
if (symbol.Name == "MoveNext")
{
if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
else if (symbol.Name == "GetEnumerator")
{
// we are a bit pessimistic here.
// To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach
if (!method.ReturnsVoid &&
!method.Parameters.Any())
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current")
{
var property = (IPropertySymbol)symbol;
if (!property.Parameters.Any() && !property.IsWriteOnly)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
}
}
return ImmutableArray<Location>.Empty;
}
#endregion
public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacementText, ICollection<string> possibleNameConflicts)
{
if (replacementText.EndsWith("Attribute", StringComparison.Ordinal) && replacementText.Length > 9)
{
var conflict = replacementText.Substring(0, replacementText.Length - 9);
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
if (symbol.Kind == SymbolKind.Property)
{
foreach (var conflict in new string[] { "_" + replacementText, "get_" + replacementText, "set_" + replacementText })
{
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
}
// in C# we also need to add the valueText because it can be different from the text in source
// e.g. it can contain escaped unicode characters. Otherwise conflicts would be detected for
// v\u0061r and var or similar.
var valueText = replacementText;
var kind = SyntaxFacts.GetKeywordKind(replacementText);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var name = SyntaxFactory.ParseName(replacementText);
if (name.Kind() == SyntaxKind.IdentifierName)
{
valueText = ((IdentifierNameSyntax)name).Identifier.ValueText;
}
}
// this also covers the case of an escaped replacementText
if (valueText != replacementText)
{
possibleNameConflicts.Add(valueText);
}
}
/// <summary>
/// Gets the top most enclosing statement or CrefSyntax as target to call MakeExplicit on.
/// It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing
/// statement of this lambda.
/// </summary>
/// <param name="token">The token to get the complexification target for.</param>
/// <returns></returns>
public override SyntaxNode? GetExpansionTargetForLocation(SyntaxToken token)
=> GetExpansionTarget(token);
private static SyntaxNode? GetExpansionTarget(SyntaxToken token)
{
// get the directly enclosing statement
var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault();
// System.Func<int, int> myFunc = arg => X;
var possibleLambdaExpression = enclosingStatement == null
? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).FirstOrDefault()
: null;
if (possibleLambdaExpression != null)
{
var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression);
if (lambdaExpression.Body is ExpressionSyntax)
{
return lambdaExpression.Body;
}
}
// int M() => X;
var possibleArrowExpressionClause = enclosingStatement == null
? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault()
: null;
if (possibleArrowExpressionClause != null)
{
return possibleArrowExpressionClause.Expression;
}
var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault();
if (enclosingNameMemberCrefOrnull != null)
{
if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax)
{
enclosingNameMemberCrefOrnull = null;
}
}
var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault();
if (enclosingXmlNameAttr != null)
{
return null;
}
var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault();
if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax)
{
return enclosingInitializer.Value;
}
var attributeSyntax = token.GetAncestor<AttributeSyntax>();
if (attributeSyntax != null)
{
return attributeSyntax;
}
// there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax
return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault();
}
#region "Helper Methods"
public override bool IsIdentifierValid(string replacementText, ISyntaxFactsService syntaxFactsService)
{
// Identifiers we never consider valid to rename to.
switch (replacementText)
{
case "var":
case "dynamic":
case "unmanaged":
case "notnull":
return false;
}
var escapedIdentifier = replacementText.StartsWith("@", StringComparison.Ordinal)
? replacementText : "@" + replacementText;
// Make sure we got an identifier.
if (!syntaxFactsService.IsValidIdentifier(escapedIdentifier))
{
// We still don't have an identifier, so let's fail
return false;
}
return true;
}
/// <summary>
/// Gets the semantic model for the given node.
/// If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel.
/// Otherwise, returns a speculative model.
/// The assumption for the later case is that span start position of the given node in it's syntax tree is same as
/// the span start of the original node in the original syntax tree.
/// </summary>
public static SemanticModel? GetSemanticModelForNode(SyntaxNode node, SemanticModel originalSemanticModel)
{
if (node.SyntaxTree == originalSemanticModel.SyntaxTree)
{
// This is possible if the previous rename phase didn't rewrite any nodes in this tree.
return originalSemanticModel;
}
var nodeToSpeculate = node.GetAncestorsOrThis(n => SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault();
if (nodeToSpeculate == null)
{
if (node.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMember))
{
nodeToSpeculate = nameMember.Name;
}
else if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax? qualifiedCref))
{
nodeToSpeculate = qualifiedCref.Container;
}
else if (node.IsKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax? typeConstraint))
{
nodeToSpeculate = typeConstraint.Type;
}
else if (node is BaseTypeSyntax baseType)
{
nodeToSpeculate = baseType.Type;
}
else
{
return null;
}
}
var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
var position = nodeToSpeculate.SpanStart;
return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, originalSemanticModel, position, isInNamespaceOrTypeContext);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/MemberInfo/ConstructorInfoImpl.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using Microsoft.VisualStudio.Debugger.Metadata;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class ConstructorInfoImpl : ConstructorInfo
{
internal readonly System.Reflection.ConstructorInfo Constructor;
internal ConstructorInfoImpl(System.Reflection.ConstructorInfo constructor)
{
Debug.Assert(constructor != null);
this.Constructor = constructor;
}
public override System.Reflection.MethodAttributes Attributes
{
get
{
throw new NotImplementedException();
}
}
public override System.Reflection.CallingConventions CallingConvention
{
get
{
throw new NotImplementedException();
}
}
public override Type DeclaringType
{
get
{
return (TypeImpl)Constructor.DeclaringType;
}
}
public override bool IsEquivalentTo(MemberInfo other)
{
throw new NotImplementedException();
}
public override bool IsGenericMethodDefinition
{
get
{
throw new NotImplementedException();
}
}
public override MemberTypes MemberType
{
get
{
return (MemberTypes)Constructor.MemberType;
}
}
public override int MetadataToken
{
get
{
throw new NotImplementedException();
}
}
public override RuntimeMethodHandle MethodHandle
{
get
{
throw new NotImplementedException();
}
}
public override Microsoft.VisualStudio.Debugger.Metadata.Module Module
{
get
{
throw new NotImplementedException();
}
}
public override string Name
{
get
{
return Constructor.Name;
}
}
public override Type ReflectedType
{
get
{
throw new NotImplementedException();
}
}
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotImplementedException();
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override IList<Microsoft.VisualStudio.Debugger.Metadata.CustomAttributeData> GetCustomAttributesData()
{
throw new NotImplementedException();
}
public override Microsoft.VisualStudio.Debugger.Metadata.MethodBody GetMethodBody()
{
throw new NotImplementedException();
}
public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags()
{
throw new NotImplementedException();
}
public override Microsoft.VisualStudio.Debugger.Metadata.ParameterInfo[] GetParameters()
{
throw new NotImplementedException();
}
public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
Debug.Assert(binder == null, "NYI");
return Constructor.Invoke((System.Reflection.BindingFlags)invokeAttr, null, parameters, culture);
}
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
throw new NotImplementedException();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using Microsoft.VisualStudio.Debugger.Metadata;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class ConstructorInfoImpl : ConstructorInfo
{
internal readonly System.Reflection.ConstructorInfo Constructor;
internal ConstructorInfoImpl(System.Reflection.ConstructorInfo constructor)
{
Debug.Assert(constructor != null);
this.Constructor = constructor;
}
public override System.Reflection.MethodAttributes Attributes
{
get
{
throw new NotImplementedException();
}
}
public override System.Reflection.CallingConventions CallingConvention
{
get
{
throw new NotImplementedException();
}
}
public override Type DeclaringType
{
get
{
return (TypeImpl)Constructor.DeclaringType;
}
}
public override bool IsEquivalentTo(MemberInfo other)
{
throw new NotImplementedException();
}
public override bool IsGenericMethodDefinition
{
get
{
throw new NotImplementedException();
}
}
public override MemberTypes MemberType
{
get
{
return (MemberTypes)Constructor.MemberType;
}
}
public override int MetadataToken
{
get
{
throw new NotImplementedException();
}
}
public override RuntimeMethodHandle MethodHandle
{
get
{
throw new NotImplementedException();
}
}
public override Microsoft.VisualStudio.Debugger.Metadata.Module Module
{
get
{
throw new NotImplementedException();
}
}
public override string Name
{
get
{
return Constructor.Name;
}
}
public override Type ReflectedType
{
get
{
throw new NotImplementedException();
}
}
public override object[] GetCustomAttributes(bool inherit)
{
throw new NotImplementedException();
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public override IList<Microsoft.VisualStudio.Debugger.Metadata.CustomAttributeData> GetCustomAttributesData()
{
throw new NotImplementedException();
}
public override Microsoft.VisualStudio.Debugger.Metadata.MethodBody GetMethodBody()
{
throw new NotImplementedException();
}
public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags()
{
throw new NotImplementedException();
}
public override Microsoft.VisualStudio.Debugger.Metadata.ParameterInfo[] GetParameters()
{
throw new NotImplementedException();
}
public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
Debug.Assert(binder == null, "NYI");
return Constructor.Invoke((System.Reflection.BindingFlags)invokeAttr, null, parameters, culture);
}
public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
{
throw new NotImplementedException();
}
public override bool IsDefined(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Services/Precedence/VisualBasicPrecedenceService.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.Precedence
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Precedence
Friend Class VisualBasicPrecedenceService
Inherits AbstractPrecedenceService(Of ExpressionSyntax, OperatorPrecedence)
Public Shared ReadOnly Instance As New VisualBasicPrecedenceService()
Private Sub New()
End Sub
Public Overrides Function GetOperatorPrecedence(expression As ExpressionSyntax) As OperatorPrecedence
Return expression.GetOperatorPrecedence()
End Function
Public Overrides Function GetPrecedenceKind(operatorPrecedence As OperatorPrecedence) As PrecedenceKind
Select Case operatorPrecedence
Case OperatorPrecedence.PrecedenceXor,
OperatorPrecedence.PrecedenceOr,
OperatorPrecedence.PrecedenceAnd
Return PrecedenceKind.Logical
Case OperatorPrecedence.PrecedenceRelational
Return PrecedenceKind.Relational
Case OperatorPrecedence.PrecedenceShift
Return PrecedenceKind.Shift
Case OperatorPrecedence.PrecedenceConcatenate,
OperatorPrecedence.PrecedenceAdd,
OperatorPrecedence.PrecedenceModulus,
OperatorPrecedence.PrecedenceIntegerDivide,
OperatorPrecedence.PrecedenceMultiply,
OperatorPrecedence.PrecedenceExponentiate
Return PrecedenceKind.Arithmetic
Case Else
Return PrecedenceKind.Other
End Select
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Precedence
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Precedence
Friend Class VisualBasicPrecedenceService
Inherits AbstractPrecedenceService(Of ExpressionSyntax, OperatorPrecedence)
Public Shared ReadOnly Instance As New VisualBasicPrecedenceService()
Private Sub New()
End Sub
Public Overrides Function GetOperatorPrecedence(expression As ExpressionSyntax) As OperatorPrecedence
Return expression.GetOperatorPrecedence()
End Function
Public Overrides Function GetPrecedenceKind(operatorPrecedence As OperatorPrecedence) As PrecedenceKind
Select Case operatorPrecedence
Case OperatorPrecedence.PrecedenceXor,
OperatorPrecedence.PrecedenceOr,
OperatorPrecedence.PrecedenceAnd
Return PrecedenceKind.Logical
Case OperatorPrecedence.PrecedenceRelational
Return PrecedenceKind.Relational
Case OperatorPrecedence.PrecedenceShift
Return PrecedenceKind.Shift
Case OperatorPrecedence.PrecedenceConcatenate,
OperatorPrecedence.PrecedenceAdd,
OperatorPrecedence.PrecedenceModulus,
OperatorPrecedence.PrecedenceIntegerDivide,
OperatorPrecedence.PrecedenceMultiply,
OperatorPrecedence.PrecedenceExponentiate
Return PrecedenceKind.Arithmetic
Case Else
Return PrecedenceKind.Other
End Select
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/EditorFeatures/Core.Wpf/Interactive/InteractiveCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
internal abstract class InteractiveCommandHandler :
ICommandHandler<ExecuteInInteractiveCommandArgs>,
ICommandHandler<CopyToInteractiveCommandArgs>
{
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
protected InteractiveCommandHandler(
IContentTypeRegistryService contentTypeRegistryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
_contentTypeRegistryService = contentTypeRegistryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
protected IContentTypeRegistryService ContentTypeRegistryService { get { return _contentTypeRegistryService; } }
protected abstract IInteractiveWindow OpenInteractiveWindow(bool focus);
protected abstract ISendToInteractiveSubmissionProvider SendToInteractiveSubmissionProvider { get; }
public string DisplayName => EditorFeaturesResources.Interactive;
private string GetSelectedText(EditorCommandArgs args, CancellationToken cancellationToken)
{
var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer);
return SendToInteractiveSubmissionProvider.GetSelectedText(editorOptions, args, cancellationToken);
}
CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args)
=> CommandState.Available;
bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context)
{
var window = OpenInteractiveWindow(focus: false);
using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Executing_selection_in_Interactive_Window))
{
var submission = GetSelectedText(args, context.OperationContext.UserCancellationToken);
if (!string.IsNullOrWhiteSpace(submission))
{
window.SubmitAsync(new string[] { submission });
}
}
return true;
}
CommandState ICommandHandler<CopyToInteractiveCommandArgs>.GetCommandState(CopyToInteractiveCommandArgs args)
=> CommandState.Available;
bool ICommandHandler<CopyToInteractiveCommandArgs>.ExecuteCommand(CopyToInteractiveCommandArgs args, CommandExecutionContext context)
{
var window = OpenInteractiveWindow(focus: true);
var buffer = window.CurrentLanguageBuffer;
if (buffer != null)
{
CopyToWindow(window, args, context);
}
else
{
Action action = null;
action = new Action(() =>
{
window.ReadyForInput -= action;
CopyToWindow(window, args, context);
});
window.ReadyForInput += action;
}
return true;
}
private void CopyToWindow(IInteractiveWindow window, CopyToInteractiveCommandArgs args, CommandExecutionContext context)
{
var buffer = window.CurrentLanguageBuffer;
Debug.Assert(buffer != null);
using (var edit = buffer.CreateEdit())
using (var waitScope = context.OperationContext.AddScope(allowCancellation: true,
EditorFeaturesWpfResources.Copying_selection_to_Interactive_Window))
{
var text = GetSelectedText(args, context.OperationContext.UserCancellationToken);
// If the last line isn't empty in the existing submission buffer, we will prepend a
// newline
var lastLine = buffer.CurrentSnapshot.GetLineFromLineNumber(buffer.CurrentSnapshot.LineCount - 1);
if (lastLine.Extent.Length > 0)
{
var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer);
text = editorOptions.GetNewLineCharacter() + text;
}
edit.Insert(buffer.CurrentSnapshot.Length, text);
edit.Apply();
}
// Move the caret to the end
var editorOperations = _editorOperationsFactoryService.GetEditorOperations(window.TextView);
var endPoint = new VirtualSnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, window.TextView.TextBuffer.CurrentSnapshot.Length);
editorOperations.SelectAndMoveCaret(endPoint, endPoint);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
internal abstract class InteractiveCommandHandler :
ICommandHandler<ExecuteInInteractiveCommandArgs>,
ICommandHandler<CopyToInteractiveCommandArgs>
{
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IEditorOperationsFactoryService _editorOperationsFactoryService;
protected InteractiveCommandHandler(
IContentTypeRegistryService contentTypeRegistryService,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
_contentTypeRegistryService = contentTypeRegistryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
_editorOperationsFactoryService = editorOperationsFactoryService;
}
protected IContentTypeRegistryService ContentTypeRegistryService { get { return _contentTypeRegistryService; } }
protected abstract IInteractiveWindow OpenInteractiveWindow(bool focus);
protected abstract ISendToInteractiveSubmissionProvider SendToInteractiveSubmissionProvider { get; }
public string DisplayName => EditorFeaturesResources.Interactive;
private string GetSelectedText(EditorCommandArgs args, CancellationToken cancellationToken)
{
var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer);
return SendToInteractiveSubmissionProvider.GetSelectedText(editorOptions, args, cancellationToken);
}
CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args)
=> CommandState.Available;
bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context)
{
var window = OpenInteractiveWindow(focus: false);
using (context.OperationContext.AddScope(allowCancellation: true, EditorFeaturesWpfResources.Executing_selection_in_Interactive_Window))
{
var submission = GetSelectedText(args, context.OperationContext.UserCancellationToken);
if (!string.IsNullOrWhiteSpace(submission))
{
window.SubmitAsync(new string[] { submission });
}
}
return true;
}
CommandState ICommandHandler<CopyToInteractiveCommandArgs>.GetCommandState(CopyToInteractiveCommandArgs args)
=> CommandState.Available;
bool ICommandHandler<CopyToInteractiveCommandArgs>.ExecuteCommand(CopyToInteractiveCommandArgs args, CommandExecutionContext context)
{
var window = OpenInteractiveWindow(focus: true);
var buffer = window.CurrentLanguageBuffer;
if (buffer != null)
{
CopyToWindow(window, args, context);
}
else
{
Action action = null;
action = new Action(() =>
{
window.ReadyForInput -= action;
CopyToWindow(window, args, context);
});
window.ReadyForInput += action;
}
return true;
}
private void CopyToWindow(IInteractiveWindow window, CopyToInteractiveCommandArgs args, CommandExecutionContext context)
{
var buffer = window.CurrentLanguageBuffer;
Debug.Assert(buffer != null);
using (var edit = buffer.CreateEdit())
using (var waitScope = context.OperationContext.AddScope(allowCancellation: true,
EditorFeaturesWpfResources.Copying_selection_to_Interactive_Window))
{
var text = GetSelectedText(args, context.OperationContext.UserCancellationToken);
// If the last line isn't empty in the existing submission buffer, we will prepend a
// newline
var lastLine = buffer.CurrentSnapshot.GetLineFromLineNumber(buffer.CurrentSnapshot.LineCount - 1);
if (lastLine.Extent.Length > 0)
{
var editorOptions = _editorOptionsFactoryService.GetOptions(args.SubjectBuffer);
text = editorOptions.GetNewLineCharacter() + text;
}
edit.Insert(buffer.CurrentSnapshot.Length, text);
edit.Apply();
}
// Move the caret to the end
var editorOperations = _editorOperationsFactoryService.GetEditorOperations(window.TextView);
var endPoint = new VirtualSnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, window.TextView.TextBuffer.CurrentSnapshot.Length);
editorOperations.SelectAndMoveCaret(endPoint, endPoint);
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/VisualStudio/Core/Impl/SolutionExplorer/BrowseObjectAttributes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
using System.Globalization;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
/// <summary>
/// The attribute used for adding localized display names to properties
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
internal sealed class BrowseObjectDisplayNameAttribute : DisplayNameAttribute
{
private readonly string m_key;
private bool m_initialized;
public BrowseObjectDisplayNameAttribute(string key)
{
m_key = key;
}
public override string DisplayName
{
get
{
if (!m_initialized)
{
base.DisplayNameValue = SolutionExplorerShim.ResourceManager.GetString(m_key, CultureInfo.CurrentUICulture);
m_initialized = true;
}
return base.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;
using System.ComponentModel;
using System.Globalization;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
/// <summary>
/// The attribute used for adding localized display names to properties
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
internal sealed class BrowseObjectDisplayNameAttribute : DisplayNameAttribute
{
private readonly string m_key;
private bool m_initialized;
public BrowseObjectDisplayNameAttribute(string key)
{
m_key = key;
}
public override string DisplayName
{
get
{
if (!m_initialized)
{
base.DisplayNameValue = SolutionExplorerShim.ResourceManager.GetString(m_key, CultureInfo.CurrentUICulture);
m_initialized = true;
}
return base.DisplayName;
}
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/VisualStudio/CodeLens/PublicAPI.Shipped.txt | -1 |
||
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/VisualBasic/Portable/OrganizeImports/VisualBasicOrganizeImportsService.Rewriter.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.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports
Partial Friend Class VisualBasicOrganizeImportsService
Private Class Rewriter
Inherits VisualBasicSyntaxRewriter
Private ReadOnly _placeSystemNamespaceFirst As Boolean
Private ReadOnly _separateGroups As Boolean
Public ReadOnly TextChanges As IList(Of TextChange) = New List(Of TextChange)()
Public Sub New(placeSystemNamespaceFirst As Boolean, separateGroups As Boolean)
_placeSystemNamespaceFirst = placeSystemNamespaceFirst
_separateGroups = separateGroups
End Sub
Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitCompilationUnit(node), CompilationUnitSyntax)
Dim organizedImports = ImportsOrganizer.Organize(
node.Imports, _placeSystemNamespaceFirst, _separateGroups)
Dim result = node.WithImports(organizedImports)
If result IsNot node Then
AddTextChange(node.Imports, organizedImports)
End If
Return result
End Function
Public Overrides Function VisitImportsStatement(node As ImportsStatementSyntax) As SyntaxNode
Dim organizedImportsClauses = ImportsOrganizer.Organize(node.ImportsClauses)
Dim result = node.WithImportsClauses(organizedImportsClauses)
If result IsNot node Then
AddTextChange(node.ImportsClauses, organizedImportsClauses)
End If
Return result
End Function
Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax),
organizedList As SeparatedSyntaxList(Of TSyntax))
If list.Count > 0 Then
Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList)))
End If
End Sub
Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax),
organizedList As SyntaxList(Of TSyntax))
If list.Count > 0 Then
Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList)))
End If
End Sub
Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SyntaxList(Of TSyntax)) As String
Return String.Join(String.Empty, organizedList.[Select](Function(t) t.ToFullString()))
End Function
Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SeparatedSyntaxList(Of TSyntax)) As String
Return String.Join(String.Empty, organizedList.GetWithSeparators().[Select](Function(t) t.ToFullString()))
End Function
Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax)) As TextSpan
Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End])
End Function
Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax)) As TextSpan
Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End])
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.OrganizeImports
Partial Friend Class VisualBasicOrganizeImportsService
Private Class Rewriter
Inherits VisualBasicSyntaxRewriter
Private ReadOnly _placeSystemNamespaceFirst As Boolean
Private ReadOnly _separateGroups As Boolean
Public ReadOnly TextChanges As IList(Of TextChange) = New List(Of TextChange)()
Public Sub New(placeSystemNamespaceFirst As Boolean, separateGroups As Boolean)
_placeSystemNamespaceFirst = placeSystemNamespaceFirst
_separateGroups = separateGroups
End Sub
Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitCompilationUnit(node), CompilationUnitSyntax)
Dim organizedImports = ImportsOrganizer.Organize(
node.Imports, _placeSystemNamespaceFirst, _separateGroups)
Dim result = node.WithImports(organizedImports)
If result IsNot node Then
AddTextChange(node.Imports, organizedImports)
End If
Return result
End Function
Public Overrides Function VisitImportsStatement(node As ImportsStatementSyntax) As SyntaxNode
Dim organizedImportsClauses = ImportsOrganizer.Organize(node.ImportsClauses)
Dim result = node.WithImportsClauses(organizedImportsClauses)
If result IsNot node Then
AddTextChange(node.ImportsClauses, organizedImportsClauses)
End If
Return result
End Function
Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax),
organizedList As SeparatedSyntaxList(Of TSyntax))
If list.Count > 0 Then
Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList)))
End If
End Sub
Private Sub AddTextChange(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax),
organizedList As SyntaxList(Of TSyntax))
If list.Count > 0 Then
Me.TextChanges.Add(New TextChange(GetTextSpan(list), GetNewText(organizedList)))
End If
End Sub
Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SyntaxList(Of TSyntax)) As String
Return String.Join(String.Empty, organizedList.[Select](Function(t) t.ToFullString()))
End Function
Private Shared Function GetNewText(Of TSyntax As SyntaxNode)(organizedList As SeparatedSyntaxList(Of TSyntax)) As String
Return String.Join(String.Empty, organizedList.GetWithSeparators().[Select](Function(t) t.ToFullString()))
End Function
Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SyntaxList(Of TSyntax)) As TextSpan
Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End])
End Function
Private Shared Function GetTextSpan(Of TSyntax As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntax)) As TextSpan
Return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.[End])
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo.Node.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class SymbolTreeInfo
{
private const int RootNodeParentIndex = -1;
/// <summary>
/// <see cref="BuilderNode"/>s are produced when initially creating our indices.
/// They store Names of symbols and the index of their parent symbol. When we
/// produce the final <see cref="SymbolTreeInfo"/> though we will then convert
/// these to <see cref="Node"/>s.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
private struct BuilderNode
{
public static readonly BuilderNode RootNode = new("", RootNodeParentIndex, default);
public readonly string Name;
public readonly int ParentIndex;
public readonly MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet ParameterTypeInfos;
public BuilderNode(string name, int parentIndex, MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet parameterTypeInfos = default)
{
Name = name;
ParentIndex = parentIndex;
ParameterTypeInfos = parameterTypeInfos;
}
public bool IsRoot => ParentIndex == RootNodeParentIndex;
private string GetDebuggerDisplay()
=> Name + ", " + ParentIndex;
}
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
private struct Node
{
/// <summary>
/// The Name of this Node.
/// </summary>
public readonly string Name;
/// <summary>
/// Index in <see cref="_nodes"/> of the parent Node of this Node.
/// Value will be <see cref="RootNodeParentIndex"/> if this is the
/// Node corresponding to the root symbol.
/// </summary>
public readonly int ParentIndex;
public Node(string name, int parentIndex)
{
Name = name;
ParentIndex = parentIndex;
}
public bool IsRoot => ParentIndex == RootNodeParentIndex;
public void AssertEquivalentTo(Node node)
{
Debug.Assert(node.Name == this.Name);
Debug.Assert(node.ParentIndex == this.ParentIndex);
}
private string GetDebuggerDisplay()
=> Name + ", " + ParentIndex;
}
private readonly struct ParameterTypeInfo
{
/// <summary>
/// This is the type name of the parameter when <see cref="IsComplexType"/> is false.
/// For array types, this is just the elemtent type name.
/// e.g. `int` for `int[][,]`
/// </summary>
public readonly string Name;
/// <summary>
/// Indicate if the type of parameter is any kind of array.
/// This is relevant for both simple and complex types. For example:
/// - array of simple type like int[], int[][], int[][,], etc. are all ultimately represented as "int[]" in index.
/// - array of complex type like T[], T[][], etc are all represented as "[]" in index,
/// in contrast to just "" for non-array types.
/// </summary>
public readonly bool IsArray;
/// <summary>
/// Similar to <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>, we divide extension methods into simple
/// and complex categories for filtering purpose. Whether a method is simple is determined based on if we
/// can determine it's receiver type easily with a pure text matching. For complex methods, we will need to
/// rely on symbol to decide if it's feasible.
///
/// Simple types include:
/// - Primitive types
/// - Types which is not a generic method parameter
/// - By reference type of any types above
/// - Array types with element of any types above
/// </summary>
public readonly bool IsComplexType;
public ParameterTypeInfo(string name, bool isComplex, bool isArray)
{
Name = name;
IsComplexType = isComplex;
IsArray = isArray;
}
}
public readonly struct ExtensionMethodInfo
{
/// <summary>
/// Name of the extension method.
/// This can be used to retrive corresponding symbols via <see cref="INamespaceOrTypeSymbol.GetMembers(string)"/>
/// </summary>
public readonly string Name;
/// <summary>
/// Fully qualified name for the type that contains this extension method.
/// </summary>
public readonly string FullyQualifiedContainerName;
public ExtensionMethodInfo(string fullyQualifiedContainerName, string name)
{
FullyQualifiedContainerName = fullyQualifiedContainerName;
Name = name;
}
}
private sealed class ParameterTypeInfoProvider : ISignatureTypeProvider<ParameterTypeInfo, object>
{
public static readonly ParameterTypeInfoProvider Instance = new();
private static ParameterTypeInfo ComplexInfo
=> new(string.Empty, isComplex: true, isArray: false);
public ParameterTypeInfo GetPrimitiveType(PrimitiveTypeCode typeCode)
=> new(typeCode.ToString(), isComplex: false, isArray: false);
public ParameterTypeInfo GetGenericInstantiation(ParameterTypeInfo genericType, ImmutableArray<ParameterTypeInfo> typeArguments)
=> genericType.IsComplexType
? ComplexInfo
: new ParameterTypeInfo(genericType.Name, isComplex: false, isArray: false);
public ParameterTypeInfo GetByReferenceType(ParameterTypeInfo elementType)
=> elementType;
public ParameterTypeInfo GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
{
var type = reader.GetTypeDefinition(handle);
var name = reader.GetString(type.Name);
return new ParameterTypeInfo(name, isComplex: false, isArray: false);
}
public ParameterTypeInfo GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
{
var type = reader.GetTypeReference(handle);
var name = reader.GetString(type.Name);
return new ParameterTypeInfo(name, isComplex: false, isArray: false);
}
public ParameterTypeInfo GetTypeFromSpecification(MetadataReader reader, object genericContext, TypeSpecificationHandle handle, byte rawTypeKind)
{
var sigReader = reader.GetBlobReader(reader.GetTypeSpecification(handle).Signature);
return new SignatureDecoder<ParameterTypeInfo, object>(Instance, reader, genericContext).DecodeType(ref sigReader);
}
public ParameterTypeInfo GetArrayType(ParameterTypeInfo elementType, ArrayShape shape) => GetArrayTypeInfo(elementType);
public ParameterTypeInfo GetSZArrayType(ParameterTypeInfo elementType) => GetArrayTypeInfo(elementType);
private static ParameterTypeInfo GetArrayTypeInfo(ParameterTypeInfo elementType)
=> elementType.IsComplexType
? new ParameterTypeInfo(string.Empty, isComplex: true, isArray: true)
: new ParameterTypeInfo(elementType.Name, isComplex: false, isArray: true);
public ParameterTypeInfo GetFunctionPointerType(MethodSignature<ParameterTypeInfo> signature) => ComplexInfo;
public ParameterTypeInfo GetGenericMethodParameter(object genericContext, int index) => ComplexInfo;
public ParameterTypeInfo GetGenericTypeParameter(object genericContext, int index) => ComplexInfo;
public ParameterTypeInfo GetModifiedType(ParameterTypeInfo modifier, ParameterTypeInfo unmodifiedType, bool isRequired) => ComplexInfo;
public ParameterTypeInfo GetPinnedType(ParameterTypeInfo elementType) => ComplexInfo;
public ParameterTypeInfo GetPointerType(ParameterTypeInfo elementType) => ComplexInfo;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class SymbolTreeInfo
{
private const int RootNodeParentIndex = -1;
/// <summary>
/// <see cref="BuilderNode"/>s are produced when initially creating our indices.
/// They store Names of symbols and the index of their parent symbol. When we
/// produce the final <see cref="SymbolTreeInfo"/> though we will then convert
/// these to <see cref="Node"/>s.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
private struct BuilderNode
{
public static readonly BuilderNode RootNode = new("", RootNodeParentIndex, default);
public readonly string Name;
public readonly int ParentIndex;
public readonly MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet ParameterTypeInfos;
public BuilderNode(string name, int parentIndex, MultiDictionary<MetadataNode, ParameterTypeInfo>.ValueSet parameterTypeInfos = default)
{
Name = name;
ParentIndex = parentIndex;
ParameterTypeInfos = parameterTypeInfos;
}
public bool IsRoot => ParentIndex == RootNodeParentIndex;
private string GetDebuggerDisplay()
=> Name + ", " + ParentIndex;
}
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
private struct Node
{
/// <summary>
/// The Name of this Node.
/// </summary>
public readonly string Name;
/// <summary>
/// Index in <see cref="_nodes"/> of the parent Node of this Node.
/// Value will be <see cref="RootNodeParentIndex"/> if this is the
/// Node corresponding to the root symbol.
/// </summary>
public readonly int ParentIndex;
public Node(string name, int parentIndex)
{
Name = name;
ParentIndex = parentIndex;
}
public bool IsRoot => ParentIndex == RootNodeParentIndex;
public void AssertEquivalentTo(Node node)
{
Debug.Assert(node.Name == this.Name);
Debug.Assert(node.ParentIndex == this.ParentIndex);
}
private string GetDebuggerDisplay()
=> Name + ", " + ParentIndex;
}
private readonly struct ParameterTypeInfo
{
/// <summary>
/// This is the type name of the parameter when <see cref="IsComplexType"/> is false.
/// For array types, this is just the elemtent type name.
/// e.g. `int` for `int[][,]`
/// </summary>
public readonly string Name;
/// <summary>
/// Indicate if the type of parameter is any kind of array.
/// This is relevant for both simple and complex types. For example:
/// - array of simple type like int[], int[][], int[][,], etc. are all ultimately represented as "int[]" in index.
/// - array of complex type like T[], T[][], etc are all represented as "[]" in index,
/// in contrast to just "" for non-array types.
/// </summary>
public readonly bool IsArray;
/// <summary>
/// Similar to <see cref="SyntaxTreeIndex.ExtensionMethodInfo"/>, we divide extension methods into simple
/// and complex categories for filtering purpose. Whether a method is simple is determined based on if we
/// can determine it's receiver type easily with a pure text matching. For complex methods, we will need to
/// rely on symbol to decide if it's feasible.
///
/// Simple types include:
/// - Primitive types
/// - Types which is not a generic method parameter
/// - By reference type of any types above
/// - Array types with element of any types above
/// </summary>
public readonly bool IsComplexType;
public ParameterTypeInfo(string name, bool isComplex, bool isArray)
{
Name = name;
IsComplexType = isComplex;
IsArray = isArray;
}
}
public readonly struct ExtensionMethodInfo
{
/// <summary>
/// Name of the extension method.
/// This can be used to retrive corresponding symbols via <see cref="INamespaceOrTypeSymbol.GetMembers(string)"/>
/// </summary>
public readonly string Name;
/// <summary>
/// Fully qualified name for the type that contains this extension method.
/// </summary>
public readonly string FullyQualifiedContainerName;
public ExtensionMethodInfo(string fullyQualifiedContainerName, string name)
{
FullyQualifiedContainerName = fullyQualifiedContainerName;
Name = name;
}
}
private sealed class ParameterTypeInfoProvider : ISignatureTypeProvider<ParameterTypeInfo, object>
{
public static readonly ParameterTypeInfoProvider Instance = new();
private static ParameterTypeInfo ComplexInfo
=> new(string.Empty, isComplex: true, isArray: false);
public ParameterTypeInfo GetPrimitiveType(PrimitiveTypeCode typeCode)
=> new(typeCode.ToString(), isComplex: false, isArray: false);
public ParameterTypeInfo GetGenericInstantiation(ParameterTypeInfo genericType, ImmutableArray<ParameterTypeInfo> typeArguments)
=> genericType.IsComplexType
? ComplexInfo
: new ParameterTypeInfo(genericType.Name, isComplex: false, isArray: false);
public ParameterTypeInfo GetByReferenceType(ParameterTypeInfo elementType)
=> elementType;
public ParameterTypeInfo GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
{
var type = reader.GetTypeDefinition(handle);
var name = reader.GetString(type.Name);
return new ParameterTypeInfo(name, isComplex: false, isArray: false);
}
public ParameterTypeInfo GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
{
var type = reader.GetTypeReference(handle);
var name = reader.GetString(type.Name);
return new ParameterTypeInfo(name, isComplex: false, isArray: false);
}
public ParameterTypeInfo GetTypeFromSpecification(MetadataReader reader, object genericContext, TypeSpecificationHandle handle, byte rawTypeKind)
{
var sigReader = reader.GetBlobReader(reader.GetTypeSpecification(handle).Signature);
return new SignatureDecoder<ParameterTypeInfo, object>(Instance, reader, genericContext).DecodeType(ref sigReader);
}
public ParameterTypeInfo GetArrayType(ParameterTypeInfo elementType, ArrayShape shape) => GetArrayTypeInfo(elementType);
public ParameterTypeInfo GetSZArrayType(ParameterTypeInfo elementType) => GetArrayTypeInfo(elementType);
private static ParameterTypeInfo GetArrayTypeInfo(ParameterTypeInfo elementType)
=> elementType.IsComplexType
? new ParameterTypeInfo(string.Empty, isComplex: true, isArray: true)
: new ParameterTypeInfo(elementType.Name, isComplex: false, isArray: true);
public ParameterTypeInfo GetFunctionPointerType(MethodSignature<ParameterTypeInfo> signature) => ComplexInfo;
public ParameterTypeInfo GetGenericMethodParameter(object genericContext, int index) => ComplexInfo;
public ParameterTypeInfo GetGenericTypeParameter(object genericContext, int index) => ComplexInfo;
public ParameterTypeInfo GetModifiedType(ParameterTypeInfo modifier, ParameterTypeInfo unmodifiedType, bool isRequired) => ComplexInfo;
public ParameterTypeInfo GetPinnedType(ParameterTypeInfo elementType) => ComplexInfo;
public ParameterTypeInfo GetPointerType(ParameterTypeInfo elementType) => ComplexInfo;
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/MethodContextReuseConstraintsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class MethodContextReuseConstraintsTests : ExpressionCompilerTestBase
{
[Fact]
public void AreSatisfied()
{
var moduleVersionId = Guid.NewGuid();
const int methodToken = 0x06000001;
const int methodVersion = 1;
const uint startOffset = 1;
const uint endOffsetExclusive = 3;
var constraints = new MethodContextReuseConstraints(
moduleVersionId,
methodToken,
methodVersion,
new ILSpan(startOffset, endOffsetExclusive));
Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset));
Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive - 1));
Assert.False(constraints.AreSatisfied(Guid.NewGuid(), methodToken, methodVersion, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken + 1, methodVersion, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion + 1, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset - 1));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive));
}
[Fact]
public void EndExclusive()
{
var spans = new[]
{
new ILSpan(0u, uint.MaxValue),
new ILSpan(1, 9),
new ILSpan(2, 8),
new ILSpan(1, 3),
new ILSpan(7, 9),
};
Assert.Equal(new ILSpan(0u, uint.MaxValue), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(1)));
Assert.Equal(new ILSpan(1, 9), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(2)));
Assert.Equal(new ILSpan(2, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(3)));
Assert.Equal(new ILSpan(3, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(4)));
Assert.Equal(new ILSpan(3, 7), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(5)));
}
[Fact]
public void Cumulative()
{
var span = ILSpan.MaxValue;
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new ILSpan[0]);
Assert.Equal(new ILSpan(0u, uint.MaxValue), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 10) });
Assert.Equal(new ILSpan(1, 10), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(2, 9) });
Assert.Equal(new ILSpan(2, 9), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 3) });
Assert.Equal(new ILSpan(3, 9), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(7, 9) });
Assert.Equal(new ILSpan(3, 7), span);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class MethodContextReuseConstraintsTests : ExpressionCompilerTestBase
{
[Fact]
public void AreSatisfied()
{
var moduleVersionId = Guid.NewGuid();
const int methodToken = 0x06000001;
const int methodVersion = 1;
const uint startOffset = 1;
const uint endOffsetExclusive = 3;
var constraints = new MethodContextReuseConstraints(
moduleVersionId,
methodToken,
methodVersion,
new ILSpan(startOffset, endOffsetExclusive));
Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset));
Assert.True(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive - 1));
Assert.False(constraints.AreSatisfied(Guid.NewGuid(), methodToken, methodVersion, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken + 1, methodVersion, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion + 1, (int)startOffset));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)startOffset - 1));
Assert.False(constraints.AreSatisfied(moduleVersionId, methodToken, methodVersion, (int)endOffsetExclusive));
}
[Fact]
public void EndExclusive()
{
var spans = new[]
{
new ILSpan(0u, uint.MaxValue),
new ILSpan(1, 9),
new ILSpan(2, 8),
new ILSpan(1, 3),
new ILSpan(7, 9),
};
Assert.Equal(new ILSpan(0u, uint.MaxValue), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(1)));
Assert.Equal(new ILSpan(1, 9), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(2)));
Assert.Equal(new ILSpan(2, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(3)));
Assert.Equal(new ILSpan(3, 8), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(4)));
Assert.Equal(new ILSpan(3, 7), MethodContextReuseConstraints.CalculateReuseSpan(5, ILSpan.MaxValue, spans.Take(5)));
}
[Fact]
public void Cumulative()
{
var span = ILSpan.MaxValue;
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new ILSpan[0]);
Assert.Equal(new ILSpan(0u, uint.MaxValue), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 10) });
Assert.Equal(new ILSpan(1, 10), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(2, 9) });
Assert.Equal(new ILSpan(2, 9), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(1, 3) });
Assert.Equal(new ILSpan(3, 9), span);
span = MethodContextReuseConstraints.CalculateReuseSpan(5, span, new[] { new ILSpan(7, 9) });
Assert.Equal(new ILSpan(3, 7), span);
}
}
}
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/VisualStudio/Core/Test/ClassView/MockSyncClassViewCommandHandler.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.Shared.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ClassView
Imports Microsoft.VisualStudio.Shell
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ClassView
Friend Class MockSyncClassViewCommandHandler
Inherits AbstractSyncClassViewCommandHandler
Public Sub New(threadingContext As IThreadingContext, serviceProvider As SVsServiceProvider)
MyBase.New(threadingContext, serviceProvider)
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.Editor.Shared.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ClassView
Imports Microsoft.VisualStudio.Shell
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ClassView
Friend Class MockSyncClassViewCommandHandler
Inherits AbstractSyncClassViewCommandHandler
Public Sub New(threadingContext As IThreadingContext, serviceProvider As SVsServiceProvider)
MyBase.New(threadingContext, serviceProvider)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,098 | Use directory-scoped ALCs to load analyzers in .NET Core | Resolves #52177 | RikkiGibson | 2021-07-23T23:26:39Z | 2021-08-23T19:01:28Z | e079a36f3ade7cda2a464e4fdcde0a11577fd1ea | 99f45b7c174d1a2e9b6a1d810b4069600c80421d | Use directory-scoped ALCs to load analyzers in .NET Core. Resolves #52177 | ./src/Features/Core/Portable/EditAndContinue/EditAndContinueMethodDebugInfoReader.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.DiaSymReader;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
/// <summary>
/// Reader of debug information needed for EnC.
/// This object does not own the underlying memory (SymReader/MetadataReader).
/// </summary>
internal abstract class EditAndContinueMethodDebugInfoReader
{
public abstract bool IsPortable { get; }
public abstract EditAndContinueMethodDebugInformation GetDebugInfo(MethodDefinitionHandle methodHandle);
public abstract StandaloneSignatureHandle GetLocalSignature(MethodDefinitionHandle methodHandle);
/// <summary>
/// Reads document checksum.
/// </summary>
/// <returns>True if a document with given path is listed in the PDB.</returns>
/// <exception cref="Exception">Error reading debug information from the PDB.</exception>
public abstract bool TryGetDocumentChecksum(string documentPath, out ImmutableArray<byte> checksum, out Guid algorithmId);
private sealed class Native : EditAndContinueMethodDebugInfoReader
{
private readonly ISymUnmanagedReader5 _symReader;
private readonly int _version;
public Native(ISymUnmanagedReader5 symReader, int version)
{
Debug.Assert(symReader != null);
Debug.Assert(version >= 1);
_symReader = symReader;
_version = version;
}
public override bool IsPortable => false;
public override StandaloneSignatureHandle GetLocalSignature(MethodDefinitionHandle methodHandle)
{
var symMethod = (ISymUnmanagedMethod2)_symReader.GetMethodByVersion(MetadataTokens.GetToken(methodHandle), _version);
// Compiler generated methods (e.g. async kick-off methods) might not have debug information.
return symMethod == null ? default : MetadataTokens.StandaloneSignatureHandle(symMethod.GetLocalSignatureToken());
}
public override EditAndContinueMethodDebugInformation GetDebugInfo(MethodDefinitionHandle methodHandle)
{
var methodToken = MetadataTokens.GetToken(methodHandle);
byte[] debugInfo;
try
{
debugInfo = _symReader.GetCustomDebugInfo(methodToken, _version);
}
catch (ArgumentOutOfRangeException)
{
// Sometimes the debugger returns the HRESULT for ArgumentOutOfRangeException, rather than E_FAIL,
// for methods without custom debug info (https://github.com/dotnet/roslyn/issues/4138).
debugInfo = null;
}
catch (Exception e) when (FatalError.ReportAndCatch(e)) // likely a bug in the compiler/debugger
{
throw new InvalidDataException(e.Message, e);
}
try
{
ImmutableArray<byte> localSlots, lambdaMap;
if (debugInfo != null)
{
localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap);
lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap);
}
else
{
localSlots = lambdaMap = default;
}
return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap);
}
catch (InvalidOperationException e) when (FatalError.ReportAndCatch(e)) // likely a bug in the compiler/debugger
{
// TODO: CustomDebugInfoReader should throw InvalidDataException
throw new InvalidDataException(e.Message, e);
}
}
public override bool TryGetDocumentChecksum(string documentPath, out ImmutableArray<byte> checksum, out Guid algorithmId)
=> TryGetDocumentChecksum(_symReader, documentPath, out checksum, out algorithmId);
}
private sealed class Portable : EditAndContinueMethodDebugInfoReader
{
private readonly MetadataReader _pdbReader;
public Portable(MetadataReader pdbReader)
=> _pdbReader = pdbReader;
public override bool IsPortable => true;
public override StandaloneSignatureHandle GetLocalSignature(MethodDefinitionHandle methodHandle)
=> _pdbReader.GetMethodDebugInformation(methodHandle.ToDebugInformationHandle()).LocalSignature;
public override EditAndContinueMethodDebugInformation GetDebugInfo(MethodDefinitionHandle methodHandle)
=> EditAndContinueMethodDebugInformation.Create(
compressedSlotMap: GetCdiBytes(methodHandle, PortableCustomDebugInfoKinds.EncLocalSlotMap),
compressedLambdaMap: GetCdiBytes(methodHandle, PortableCustomDebugInfoKinds.EncLambdaAndClosureMap));
private ImmutableArray<byte> GetCdiBytes(MethodDefinitionHandle methodHandle, Guid kind)
=> TryGetCustomDebugInformation(_pdbReader, methodHandle, kind, out var cdi) ?
_pdbReader.GetBlobContent(cdi.Value) : default;
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static bool TryGetCustomDebugInformation(MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo)
{
var foundAny = false;
customDebugInfo = default;
foreach (var infoHandle in reader.GetCustomDebugInformation(handle))
{
var info = reader.GetCustomDebugInformation(infoHandle);
var id = reader.GetGuid(info.Kind);
if (id == kind)
{
if (foundAny)
{
throw new BadImageFormatException();
}
customDebugInfo = info;
foundAny = true;
}
}
return foundAny;
}
public override bool TryGetDocumentChecksum(string documentPath, out ImmutableArray<byte> checksum, out Guid algorithmId)
{
foreach (var documentHandle in _pdbReader.Documents)
{
var document = _pdbReader.GetDocument(documentHandle);
if (_pdbReader.StringComparer.Equals(document.Name, documentPath))
{
checksum = _pdbReader.GetBlobContent(document.Hash);
algorithmId = _pdbReader.GetGuid(document.HashAlgorithm);
return true;
}
}
checksum = default;
algorithmId = default;
return false;
}
}
/// <summary>
/// Creates <see cref="EditAndContinueMethodDebugInfoReader"/> backed by a given <see cref="ISymUnmanagedReader5"/>.
/// </summary>
/// <param name="symReader">SymReader open on a Portable or Windows PDB.</param>
/// <param name="version">The version of the PDB to read.</param>
/// <exception cref="ArgumentNullException"><paramref name="symReader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="version"/> is less than 1.</exception>
/// <exception cref="COMException">Error reading debug information.</exception>
/// <returns>
/// The resulting reader does not take ownership of the <paramref name="symReader"/> or the memory it reads.
/// </returns>
/// <remarks>
/// Automatically detects the underlying PDB format and returns the appropriate reader.
/// </remarks>
public static unsafe EditAndContinueMethodDebugInfoReader Create(ISymUnmanagedReader5 symReader, int version = 1)
{
if (symReader == null)
{
throw new ArgumentNullException(nameof(symReader));
}
if (version <= 0)
{
throw new ArgumentOutOfRangeException(nameof(version));
}
var hr = symReader.GetPortableDebugMetadataByVersion(version, metadata: out var metadata, size: out var size);
Marshal.ThrowExceptionForHR(hr);
if (hr == 0)
{
return new Portable(new MetadataReader(metadata, size));
}
else
{
return new Native(symReader, version);
}
}
/// <summary>
/// Creates <see cref="EditAndContinueMethodDebugInfoReader"/> back by a given <see cref="MetadataReader"/>.
/// </summary>
/// <param name="pdbReader"><see cref="MetadataReader"/> open on a Portable PDB.</param>
/// <exception cref="ArgumentNullException"><paramref name="pdbReader"/> is null.</exception>
/// <returns>
/// The resulting reader does not take ownership of the <paramref name="pdbReader"/> or the memory it reads.
/// </returns>
public static unsafe EditAndContinueMethodDebugInfoReader Create(MetadataReader pdbReader)
=> new Portable(pdbReader ?? throw new ArgumentNullException(nameof(pdbReader)));
internal static bool TryGetDocumentChecksum(ISymUnmanagedReader5 symReader, string documentPath, out ImmutableArray<byte> checksum, out Guid algorithmId)
{
var symDocument = symReader.GetDocument(documentPath);
// Make sure the full path matches.
// Native SymReader allows partial match on the document file name.
if (symDocument == null || !StringComparer.Ordinal.Equals(symDocument.GetName(), documentPath))
{
checksum = default;
algorithmId = default;
return false;
}
algorithmId = symDocument.GetHashAlgorithm();
checksum = symDocument.GetChecksum().ToImmutableArray();
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.DiaSymReader;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
/// <summary>
/// Reader of debug information needed for EnC.
/// This object does not own the underlying memory (SymReader/MetadataReader).
/// </summary>
internal abstract class EditAndContinueMethodDebugInfoReader
{
public abstract bool IsPortable { get; }
public abstract EditAndContinueMethodDebugInformation GetDebugInfo(MethodDefinitionHandle methodHandle);
public abstract StandaloneSignatureHandle GetLocalSignature(MethodDefinitionHandle methodHandle);
/// <summary>
/// Reads document checksum.
/// </summary>
/// <returns>True if a document with given path is listed in the PDB.</returns>
/// <exception cref="Exception">Error reading debug information from the PDB.</exception>
public abstract bool TryGetDocumentChecksum(string documentPath, out ImmutableArray<byte> checksum, out Guid algorithmId);
private sealed class Native : EditAndContinueMethodDebugInfoReader
{
private readonly ISymUnmanagedReader5 _symReader;
private readonly int _version;
public Native(ISymUnmanagedReader5 symReader, int version)
{
Debug.Assert(symReader != null);
Debug.Assert(version >= 1);
_symReader = symReader;
_version = version;
}
public override bool IsPortable => false;
public override StandaloneSignatureHandle GetLocalSignature(MethodDefinitionHandle methodHandle)
{
var symMethod = (ISymUnmanagedMethod2)_symReader.GetMethodByVersion(MetadataTokens.GetToken(methodHandle), _version);
// Compiler generated methods (e.g. async kick-off methods) might not have debug information.
return symMethod == null ? default : MetadataTokens.StandaloneSignatureHandle(symMethod.GetLocalSignatureToken());
}
public override EditAndContinueMethodDebugInformation GetDebugInfo(MethodDefinitionHandle methodHandle)
{
var methodToken = MetadataTokens.GetToken(methodHandle);
byte[] debugInfo;
try
{
debugInfo = _symReader.GetCustomDebugInfo(methodToken, _version);
}
catch (ArgumentOutOfRangeException)
{
// Sometimes the debugger returns the HRESULT for ArgumentOutOfRangeException, rather than E_FAIL,
// for methods without custom debug info (https://github.com/dotnet/roslyn/issues/4138).
debugInfo = null;
}
catch (Exception e) when (FatalError.ReportAndCatch(e)) // likely a bug in the compiler/debugger
{
throw new InvalidDataException(e.Message, e);
}
try
{
ImmutableArray<byte> localSlots, lambdaMap;
if (debugInfo != null)
{
localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap);
lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap);
}
else
{
localSlots = lambdaMap = default;
}
return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap);
}
catch (InvalidOperationException e) when (FatalError.ReportAndCatch(e)) // likely a bug in the compiler/debugger
{
// TODO: CustomDebugInfoReader should throw InvalidDataException
throw new InvalidDataException(e.Message, e);
}
}
public override bool TryGetDocumentChecksum(string documentPath, out ImmutableArray<byte> checksum, out Guid algorithmId)
=> TryGetDocumentChecksum(_symReader, documentPath, out checksum, out algorithmId);
}
private sealed class Portable : EditAndContinueMethodDebugInfoReader
{
private readonly MetadataReader _pdbReader;
public Portable(MetadataReader pdbReader)
=> _pdbReader = pdbReader;
public override bool IsPortable => true;
public override StandaloneSignatureHandle GetLocalSignature(MethodDefinitionHandle methodHandle)
=> _pdbReader.GetMethodDebugInformation(methodHandle.ToDebugInformationHandle()).LocalSignature;
public override EditAndContinueMethodDebugInformation GetDebugInfo(MethodDefinitionHandle methodHandle)
=> EditAndContinueMethodDebugInformation.Create(
compressedSlotMap: GetCdiBytes(methodHandle, PortableCustomDebugInfoKinds.EncLocalSlotMap),
compressedLambdaMap: GetCdiBytes(methodHandle, PortableCustomDebugInfoKinds.EncLambdaAndClosureMap));
private ImmutableArray<byte> GetCdiBytes(MethodDefinitionHandle methodHandle, Guid kind)
=> TryGetCustomDebugInformation(_pdbReader, methodHandle, kind, out var cdi) ?
_pdbReader.GetBlobContent(cdi.Value) : default;
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static bool TryGetCustomDebugInformation(MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo)
{
var foundAny = false;
customDebugInfo = default;
foreach (var infoHandle in reader.GetCustomDebugInformation(handle))
{
var info = reader.GetCustomDebugInformation(infoHandle);
var id = reader.GetGuid(info.Kind);
if (id == kind)
{
if (foundAny)
{
throw new BadImageFormatException();
}
customDebugInfo = info;
foundAny = true;
}
}
return foundAny;
}
public override bool TryGetDocumentChecksum(string documentPath, out ImmutableArray<byte> checksum, out Guid algorithmId)
{
foreach (var documentHandle in _pdbReader.Documents)
{
var document = _pdbReader.GetDocument(documentHandle);
if (_pdbReader.StringComparer.Equals(document.Name, documentPath))
{
checksum = _pdbReader.GetBlobContent(document.Hash);
algorithmId = _pdbReader.GetGuid(document.HashAlgorithm);
return true;
}
}
checksum = default;
algorithmId = default;
return false;
}
}
/// <summary>
/// Creates <see cref="EditAndContinueMethodDebugInfoReader"/> backed by a given <see cref="ISymUnmanagedReader5"/>.
/// </summary>
/// <param name="symReader">SymReader open on a Portable or Windows PDB.</param>
/// <param name="version">The version of the PDB to read.</param>
/// <exception cref="ArgumentNullException"><paramref name="symReader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="version"/> is less than 1.</exception>
/// <exception cref="COMException">Error reading debug information.</exception>
/// <returns>
/// The resulting reader does not take ownership of the <paramref name="symReader"/> or the memory it reads.
/// </returns>
/// <remarks>
/// Automatically detects the underlying PDB format and returns the appropriate reader.
/// </remarks>
public static unsafe EditAndContinueMethodDebugInfoReader Create(ISymUnmanagedReader5 symReader, int version = 1)
{
if (symReader == null)
{
throw new ArgumentNullException(nameof(symReader));
}
if (version <= 0)
{
throw new ArgumentOutOfRangeException(nameof(version));
}
var hr = symReader.GetPortableDebugMetadataByVersion(version, metadata: out var metadata, size: out var size);
Marshal.ThrowExceptionForHR(hr);
if (hr == 0)
{
return new Portable(new MetadataReader(metadata, size));
}
else
{
return new Native(symReader, version);
}
}
/// <summary>
/// Creates <see cref="EditAndContinueMethodDebugInfoReader"/> back by a given <see cref="MetadataReader"/>.
/// </summary>
/// <param name="pdbReader"><see cref="MetadataReader"/> open on a Portable PDB.</param>
/// <exception cref="ArgumentNullException"><paramref name="pdbReader"/> is null.</exception>
/// <returns>
/// The resulting reader does not take ownership of the <paramref name="pdbReader"/> or the memory it reads.
/// </returns>
public static unsafe EditAndContinueMethodDebugInfoReader Create(MetadataReader pdbReader)
=> new Portable(pdbReader ?? throw new ArgumentNullException(nameof(pdbReader)));
internal static bool TryGetDocumentChecksum(ISymUnmanagedReader5 symReader, string documentPath, out ImmutableArray<byte> checksum, out Guid algorithmId)
{
var symDocument = symReader.GetDocument(documentPath);
// Make sure the full path matches.
// Native SymReader allows partial match on the document file name.
if (symDocument == null || !StringComparer.Ordinal.Equals(symDocument.GetName(), documentPath))
{
checksum = default;
algorithmId = default;
return false;
}
algorithmId = symDocument.GetHashAlgorithm();
checksum = symDocument.GetChecksum().ToImmutableArray();
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./eng/Versions.props | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project>
<!--
Roslyn version
-->
<PropertyGroup>
<MajorVersion>4</MajorVersion>
<MinorVersion>1</MinorVersion>
<PatchVersion>0</PatchVersion>
<PreReleaseVersionLabel>1</PreReleaseVersionLabel>
<VersionPrefix>$(MajorVersion).$(MinorVersion).$(PatchVersion)</VersionPrefix>
<!--
By default the assembly version in official builds is "$(MajorVersion).$(MinorVersion).0.0".
Keep the setting conditional. The toolset sets the assembly version to 42.42.42.42 if not set explicitly.
-->
<AssemblyVersion Condition="'$(OfficialBuild)' == 'true' or '$(DotNetUseShippingVersions)' == 'true'">$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion>
<!--
Arcade overrides our VersionPrefix when MajorVersion and MinorVersion are specified. Clear them so that
we can keep the PatchVersion until we are using an SDK that includes https://github.com/dotnet/arcade/pull/3601
-->
<MajorVersion>
</MajorVersion>
<MinorVersion>
</MinorVersion>
<MicrosoftNetCompilersToolsetVersion>4.0.0-5.21469.2</MicrosoftNetCompilersToolsetVersion>
</PropertyGroup>
<PropertyGroup>
<!-- Versions used by several individual references below -->
<RoslynDiagnosticsNugetPackageVersion>3.3.3-beta1.21105.3</RoslynDiagnosticsNugetPackageVersion>
<MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-rc1.21366.2</MicrosoftCodeAnalysisNetAnalyzersVersion>
<MicrosoftCodeAnalysisTestingVersion>1.1.0-beta1.21322.2</MicrosoftCodeAnalysisTestingVersion>
<!-- CodeStyleAnalyzerVersion should we updated together with version of dotnet-format in dotnet-tools.json -->
<CodeStyleAnalyzerVersion>4.0.0-3.final</CodeStyleAnalyzerVersion>
<VisualStudioEditorPackagesVersion>16.10.230</VisualStudioEditorPackagesVersion>
<VisualStudioEditorNewPackagesVersion>17.0.391-preview-g5e248c9073</VisualStudioEditorNewPackagesVersion>
<ILAsmPackageVersion>5.0.0-alpha1.19409.1</ILAsmPackageVersion>
<ILDAsmPackageVersion>5.0.0-preview.1.20112.8</ILDAsmPackageVersion>
<MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>17.0.4129-g0e33707768</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>
<MicrosoftVisualStudioShellPackagesVersion>17.0.0-previews-4-31709-430</MicrosoftVisualStudioShellPackagesVersion>
<MicrosoftBuildPackagesVersion>16.5.0</MicrosoftBuildPackagesVersion>
<!-- The version of Roslyn we build Source Generators against that are built in this
repository. This must be lower than MicrosoftNetCompilersToolsetVersion,
but not higher than our minimum dogfoodable Visual Studio version, or else
the generators we build would load on the command line but not load in IDEs. -->
<SourceGeneratorMicrosoftCodeAnalysisVersion>3.8.0</SourceGeneratorMicrosoftCodeAnalysisVersion>
</PropertyGroup>
<!--
Dependency versions
-->
<PropertyGroup>
<BasicUndoVersion>0.9.3</BasicUndoVersion>
<BasicReferenceAssembliesNetStandard20Version>1.2.4</BasicReferenceAssembliesNetStandard20Version>
<BasicReferenceAssembliesNet50Version>1.2.4</BasicReferenceAssembliesNet50Version>
<BasicReferenceAssembliesNet60Version>1.2.4</BasicReferenceAssembliesNet60Version>
<BasicReferenceAssembliesNetStandard13Version>1.2.4</BasicReferenceAssembliesNetStandard13Version>
<BenchmarkDotNetVersion>0.13.0</BenchmarkDotNetVersion>
<BenchmarkDotNetDiagnosticsWindowsVersion>0.13.0</BenchmarkDotNetDiagnosticsWindowsVersion>
<DiffPlexVersion>1.4.4</DiffPlexVersion>
<FakeSignVersion>0.9.2</FakeSignVersion>
<HumanizerCoreVersion>2.2.0</HumanizerCoreVersion>
<ICSharpCodeDecompilerVersion>6.1.0.5902</ICSharpCodeDecompilerVersion>
<MicrosoftBuildVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildVersion>
<MicrosoftBuildFrameworkVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildFrameworkVersion>
<MicrosoftBuildLocatorVersion>1.2.6</MicrosoftBuildLocatorVersion>
<MicrosoftBuildRuntimeVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildRuntimeVersion>
<MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildTasksCoreVersion>
<NuGetVisualStudioContractsVersion>6.0.0-preview.0.15</NuGetVisualStudioContractsVersion>
<MicrosoftVisualStudioRpcContractsVersion>16.10.23</MicrosoftVisualStudioRpcContractsVersion>
<!--
Since the Microsoft.CodeAnalysis.Analyzers package is a public dependency of our NuGet
packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for
other analyzers to ensure it stays on a release version.
-->
<MicrosoftCodeAnalysisAnalyzersVersion>3.3.2</MicrosoftCodeAnalysisAnalyzersVersion>
<MicrosoftCodeAnalysisBuildTasksVersion>2.0.0-rc2-61102-09</MicrosoftCodeAnalysisBuildTasksVersion>
<MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>
<MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>
<MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>
<MicrosoftCodeAnalysisCSharpCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisCSharpCodeStyleVersion>
<MicrosoftCodeAnalysisElfieVersion>1.0.0-rc14</MicrosoftCodeAnalysisElfieVersion>
<MicrosoftCodeAnalysisTestResourcesProprietaryVersion>2.0.44</MicrosoftCodeAnalysisTestResourcesProprietaryVersion>
<MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>
<MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>
<MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>
<MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>
<MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>3.3.0</MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>
<MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>
<MicrosoftCSharpVersion>4.3.0</MicrosoftCSharpVersion>
<MicrosoftDevDivOptimizationDataPowerShellVersion>1.0.339</MicrosoftDevDivOptimizationDataPowerShellVersion>
<MicrosoftDiagnosticsRuntimeVersion>0.8.31-beta</MicrosoftDiagnosticsRuntimeVersion>
<MicrosoftDiagnosticsTracingTraceEventVersion>1.0.35</MicrosoftDiagnosticsTracingTraceEventVersion>
<MicrosoftDiaSymReaderVersion>1.3.0</MicrosoftDiaSymReaderVersion>
<MicrosoftDiaSymReaderConverterVersion>1.1.0-beta2-21477-02</MicrosoftDiaSymReaderConverterVersion>
<MicrosoftDiaSymReaderConverterXmlVersion>1.1.0-beta2-21477-02</MicrosoftDiaSymReaderConverterXmlVersion>
<MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion>
<MicrosoftDiaSymReaderPortablePdbVersion>1.5.0</MicrosoftDiaSymReaderPortablePdbVersion>
<MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion>
<MicrosoftExtensionsLoggingConsoleVersion>5.0.0</MicrosoftExtensionsLoggingConsoleVersion>
<MicrosoftIdentityModelClientsActiveDirectoryVersion>3.13.8</MicrosoftIdentityModelClientsActiveDirectoryVersion>
<MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>15.8.27812-alpha</MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>
<MicrosoftInternalVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftInternalVisualStudioInteropVersion>
<MicrosoftMetadataVisualizerVersion>1.0.0-beta3.21075.2</MicrosoftMetadataVisualizerVersion>
<MicrosoftNETBuildExtensionsVersion>2.2.101</MicrosoftNETBuildExtensionsVersion>
<MicrosoftNETCorePlatformsVersion>2.1.2</MicrosoftNETCorePlatformsVersion>
<MicrosoftNETCoreAppRefVersion>5.0.0</MicrosoftNETCoreAppRefVersion>
<MicrosoftNETFrameworkReferenceAssembliesnet461Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet461Version>
<MicrosoftNETFrameworkReferenceAssembliesnet451Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet451Version>
<MicrosoftNETFrameworkReferenceAssembliesnet40Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet40Version>
<MicrosoftNETFrameworkReferenceAssembliesnet20Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet20Version>
<jnm2ReferenceAssembliesnet35Version>1.0.1</jnm2ReferenceAssembliesnet35Version>
<MicrosoftNETCoreTestHostVersion>1.1.0</MicrosoftNETCoreTestHostVersion>
<MicrosoftNetFX20Version>1.0.3</MicrosoftNetFX20Version>
<MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.0</MicrosoftNETFrameworkReferenceAssembliesVersion>
<MicrosoftNetSdkVersion>2.0.0-alpha-20170405-2</MicrosoftNetSdkVersion>
<MicrosoftNuGetBuildTasksVersion>0.1.0</MicrosoftNuGetBuildTasksVersion>
<MicrosoftPortableTargetsVersion>0.1.2-dev</MicrosoftPortableTargetsVersion>
<MicrosoftServiceHubClientVersion>3.0.2065</MicrosoftServiceHubClientVersion>
<MicrosoftServiceHubFrameworkVersion>3.0.2065</MicrosoftServiceHubFrameworkVersion>
<MicrosoftVisualBasicVersion>10.1.0</MicrosoftVisualBasicVersion>
<MicrosoftVisualStudioCacheVersion>17.0.13-alpha</MicrosoftVisualStudioCacheVersion>
<MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>15.8.27812-alpha</MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>
<MicrosoftVisualStudioCodeAnalysisSdkUIVersion>15.8.27812-alpha</MicrosoftVisualStudioCodeAnalysisSdkUIVersion>
<MicrosoftVisualStudioComponentModelHostVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioComponentModelHostVersion>
<MicrosoftVisualStudioCompositionVersion>16.9.20</MicrosoftVisualStudioCompositionVersion>
<MicrosoftVisualStudioCoreUtilityVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioCoreUtilityVersion>
<MicrosoftVisualStudioDebuggerUIInterfacesVersion>17.2.0-beta.21417.1</MicrosoftVisualStudioDebuggerUIInterfacesVersion>
<MicrosoftVisualStudioDebuggerContractsVersion>17.2.0-beta.21417.1</MicrosoftVisualStudioDebuggerContractsVersion>
<MicrosoftVisualStudioDebuggerEngineimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerEngineimplementationVersion>
<MicrosoftVisualStudioDebuggerMetadataimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerMetadataimplementationVersion>
<MicrosoftVisualStudioDesignerInterfacesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDesignerInterfacesVersion>
<MicrosoftVisualStudioDiagnosticsMeasurementVersion>17.0.0-preview-1-30928-1112</MicrosoftVisualStudioDiagnosticsMeasurementVersion>
<MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>
<MicrosoftVisualStudioSDKEmbedInteropTypesVersion>15.0.36</MicrosoftVisualStudioSDKEmbedInteropTypesVersion>
<MicrosoftVisualStudioEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioEditorVersion>
<MicrosoftVisualStudioGraphModelVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioGraphModelVersion>
<MicrosoftVisualStudioImageCatalogVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImageCatalogVersion>
<MicrosoftVisualStudioImagingVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingVersion>
<MicrosoftVisualStudioImagingInterop140DesignTimeVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingInterop140DesignTimeVersion>
<MicrosoftVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioInteropVersion>
<MicrosoftVisualStudioLanguageVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageVersion>
<MicrosoftVisualStudioLanguageCallHierarchyVersion>15.8.27812-alpha</MicrosoftVisualStudioLanguageCallHierarchyVersion>
<MicrosoftVisualStudioLanguageIntellisenseVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageIntellisenseVersion>
<MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>17.0.25-g975cd8c52c</MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>
<MicrosoftVisualStudioLanguageServerProtocolVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolVersion>
<MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>
<MicrosoftVisualStudioLanguageServerProtocolInternalVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolInternalVersion>
<MicrosoftVisualStudioLanguageServerClientVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerClientVersion>
<MicrosoftVisualStudioLanguageStandardClassificationVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageStandardClassificationVersion>
<MicrosoftVisualStudioLiveShareVersion>2.18.6</MicrosoftVisualStudioLiveShareVersion>
<MicrosoftVisualStudioLiveShareLanguageServicesVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesVersion>
<MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>
<MicrosoftVisualStudioLiveShareWebEditorsVersion>3.0.8</MicrosoftVisualStudioLiveShareWebEditorsVersion>
<MicrosoftVisualStudioPlatformVSEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioPlatformVSEditorVersion>
<MicrosoftVisualStudioProgressionCodeSchemaVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCodeSchemaVersion>
<MicrosoftVisualStudioProgressionCommonVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCommonVersion>
<MicrosoftVisualStudioProgressionInterfacesVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionInterfacesVersion>
<MicrosoftVisualStudioProjectSystemVersion>17.0.77-pre-g62a6cb5699</MicrosoftVisualStudioProjectSystemVersion>
<MicrosoftVisualStudioProjectSystemManagedVersion>2.3.6152103</MicrosoftVisualStudioProjectSystemManagedVersion>
<MicrosoftVisualStudioRemoteControlVersion>16.3.41</MicrosoftVisualStudioRemoteControlVersion>
<MicrosoftVisualStudioSDKAnalyzersVersion>16.10.10</MicrosoftVisualStudioSDKAnalyzersVersion>
<MicrosoftVisualStudioSetupConfigurationInteropVersion>1.16.30</MicrosoftVisualStudioSetupConfigurationInteropVersion>
<MicrosoftVisualStudioShell150Version>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShell150Version>
<MicrosoftVisualStudioShellFrameworkVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellFrameworkVersion>
<MicrosoftVisualStudioShellDesignVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellDesignVersion>
<MicrosoftVisualStudioTelemetryVersion>16.3.211</MicrosoftVisualStudioTelemetryVersion>
<MicrosoftVisualStudioTemplateWizardInterfaceVersion>8.0.0.0-alpha</MicrosoftVisualStudioTemplateWizardInterfaceVersion>
<MicrosoftVisualStudioTextDataVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextDataVersion>
<MicrosoftVisualStudioTextInternalVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextInternalVersion>
<MicrosoftVisualStudioTextLogicVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextLogicVersion>
<MicrosoftVisualStudioTextUIVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIVersion>
<MicrosoftVisualStudioTextUIWpfVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIWpfVersion>
<MicrosoftVisualStudioTextUICocoaVersion>$(VisualStudioEditorPackagesVersion)</MicrosoftVisualStudioTextUICocoaVersion>
<MicrosoftVisualStudioThreadingAnalyzersVersion>17.0.46-alpha</MicrosoftVisualStudioThreadingAnalyzersVersion>
<MicrosoftVisualStudioThreadingVersion>17.0.46-alpha</MicrosoftVisualStudioThreadingVersion>
<MicrosoftVisualStudioUtilitiesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioUtilitiesVersion>
<MicrosoftVisualStudioValidationVersion>17.0.21-alpha</MicrosoftVisualStudioValidationVersion>
<MicrosoftVisualStudioInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioInteractiveWindowVersion>
<MicrosoftVisualStudioVsInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioVsInteractiveWindowVersion>
<MicrosoftVisualStudioWorkspaceVSIntegrationVersion>16.3.43</MicrosoftVisualStudioWorkspaceVSIntegrationVersion>
<MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion>
<MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion>
<MSBuildStructuredLoggerVersion>2.1.500</MSBuildStructuredLoggerVersion>
<MDbgVersion>0.1.0</MDbgVersion>
<MonoOptionsVersion>6.6.0.161</MonoOptionsVersion>
<MoqVersion>4.10.1</MoqVersion>
<NerdbankStreamsVersion>2.7.74</NerdbankStreamsVersion>
<NuGetVisualStudioVersion>6.0.0-preview.0.15</NuGetVisualStudioVersion>
<NuGetSolutionRestoreManagerInteropVersion>4.8.0</NuGetSolutionRestoreManagerInteropVersion>
<MicrosoftDiaSymReaderPdb2PdbVersion>1.1.0-beta1-62506-02</MicrosoftDiaSymReaderPdb2PdbVersion>
<RestSharpVersion>105.2.3</RestSharpVersion>
<RichCodeNavEnvVarDumpVersion>0.1.1643-alpha</RichCodeNavEnvVarDumpVersion>
<RoslynBuildUtilVersion>0.9.8-beta</RoslynBuildUtilVersion>
<RoslynDependenciesOptimizationDataVersion>3.0.0-beta2-19053-01</RoslynDependenciesOptimizationDataVersion>
<RoslynDiagnosticsAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</RoslynDiagnosticsAnalyzersVersion>
<RoslynToolsVSIXExpInstallerVersion>1.1.0-beta3.21418.3</RoslynToolsVSIXExpInstallerVersion>
<RoslynMicrosoftVisualStudioExtensionManagerVersion>0.0.4</RoslynMicrosoftVisualStudioExtensionManagerVersion>
<SourceBrowserVersion>1.0.21</SourceBrowserVersion>
<SystemBuffersVersion>4.5.1</SystemBuffersVersion>
<SystemCompositionVersion>1.0.31</SystemCompositionVersion>
<SystemCodeDomVersion>4.7.0</SystemCodeDomVersion>
<SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion>
<SystemCommandLineExperimentalVersion>0.3.0-alpha.19577.1</SystemCommandLineExperimentalVersion>
<SystemComponentModelCompositionVersion>4.5.0</SystemComponentModelCompositionVersion>
<SystemDrawingCommonVersion>4.5.0</SystemDrawingCommonVersion>
<SystemIOFileSystemVersion>4.3.0</SystemIOFileSystemVersion>
<SystemIOFileSystemPrimitivesVersion>4.3.0</SystemIOFileSystemPrimitivesVersion>
<SystemIOPipesAccessControlVersion>4.5.1</SystemIOPipesAccessControlVersion>
<SystemIOPipelinesVersion>5.0.1</SystemIOPipelinesVersion>
<SystemManagementVersion>5.0.0-preview.8.20407.11</SystemManagementVersion>
<SystemMemoryVersion>4.5.4</SystemMemoryVersion>
<SystemResourcesExtensionsVersion>4.7.1</SystemResourcesExtensionsVersion>
<SystemRuntimeCompilerServicesUnsafeVersion>5.0.0</SystemRuntimeCompilerServicesUnsafeVersion>
<SystemRuntimeLoaderVersion>4.3.0</SystemRuntimeLoaderVersion>
<SystemSecurityPrincipalVersion>4.3.0</SystemSecurityPrincipalVersion>
<SystemTextEncodingCodePagesVersion>4.5.1</SystemTextEncodingCodePagesVersion>
<SystemTextEncodingExtensionsVersion>4.3.0</SystemTextEncodingExtensionsVersion>
<!-- Note: When updating SystemTextJsonVersion ensure that the version is no higher than what is used by MSBuild. -->
<SystemTextJsonVersion>4.7.0</SystemTextJsonVersion>
<SystemThreadingTasksDataflowVersion>5.0.0</SystemThreadingTasksDataflowVersion>
<!-- We need System.ValueTuple assembly version at least 4.0.3.0 on net47 to make F5 work against Dev15 - see https://github.com/dotnet/roslyn/issues/29705 -->
<SystemValueTupleVersion>4.5.0</SystemValueTupleVersion>
<SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion>
<SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion>
<UIAComWrapperVersion>1.1.0.14</UIAComWrapperVersion>
<MicroBuildPluginsSwixBuildVersion>1.1.33</MicroBuildPluginsSwixBuildVersion>
<MicrosoftVSSDKBuildToolsVersion>17.0.1056-Dev17PIAs-g9dffd635</MicrosoftVSSDKBuildToolsVersion>
<MicrosoftVSSDKVSDConfigToolVersion>16.0.2032702</MicrosoftVSSDKVSDConfigToolVersion>
<VsWebsiteInteropVersion>8.0.50727</VsWebsiteInteropVersion>
<vswhereVersion>2.4.1</vswhereVersion>
<XamarinMacVersion>1.0.0</XamarinMacVersion>
<xunitVersion>2.4.1-pre.build.4059</xunitVersion>
<xunitanalyzersVersion>0.10.0</xunitanalyzersVersion>
<xunitassertVersion>$(xunitVersion)</xunitassertVersion>
<XunitCombinatorialVersion>1.3.2</XunitCombinatorialVersion>
<XUnitXmlTestLoggerVersion>2.1.26</XUnitXmlTestLoggerVersion>
<xunitextensibilitycoreVersion>$(xunitVersion)</xunitextensibilitycoreVersion>
<xunitrunnerconsoleVersion>2.4.1-pre.build.4059</xunitrunnerconsoleVersion>
<xunitrunnerwpfVersion>1.0.51</xunitrunnerwpfVersion>
<xunitrunnervisualstudioVersion>$(xunitVersion)</xunitrunnervisualstudioVersion>
<xunitextensibilityexecutionVersion>$(xunitVersion)</xunitextensibilityexecutionVersion>
<runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>
<runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>
<runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>
<runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>
<runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>
<runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>
<!--
NOTE: The following dependencies have been identified as particularly problematic to update.
If you bump their versions, you must push your changes to a dev branch in dotnet/roslyn and
create a test insertion in Visual Studio to validate.
-->
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
<StreamJsonRpcVersion>2.8.21</StreamJsonRpcVersion>
<!--
When updating the S.C.I or S.R.M version please let the MSBuild team know in advance so they
can update to the same version. Version changes require a VS test insertion for validation.
-->
<SystemCollectionsImmutableVersion>5.0.0</SystemCollectionsImmutableVersion>
<SystemReflectionMetadataVersion>5.0.0</SystemReflectionMetadataVersion>
<MicrosoftBclAsyncInterfacesVersion>5.0.0</MicrosoftBclAsyncInterfacesVersion>
</PropertyGroup>
<PropertyGroup>
<UsingToolPdbConverter>true</UsingToolPdbConverter>
<UsingToolSymbolUploader>true</UsingToolSymbolUploader>
<UsingToolNuGetRepack>true</UsingToolNuGetRepack>
<UsingToolVSSDK>true</UsingToolVSSDK>
<UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies>
<UsingToolIbcOptimization>true</UsingToolIbcOptimization>
<UsingToolVisualStudioIbcTraining>true</UsingToolVisualStudioIbcTraining>
<UsingToolXliff>true</UsingToolXliff>
<UsingToolXUnit>true</UsingToolXUnit>
<DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles>
<!--
When using a bootstrap builder we don't want to use the Microsoft.Net.Compilers.Toolset package but
rather explicitly override it.
-->
<UsingToolMicrosoftNetCompilers Condition="'$(BootstrapBuildPath)' == ''">true</UsingToolMicrosoftNetCompilers>
<UseVSTestRunner>true</UseVSTestRunner>
</PropertyGroup>
</Project>
| <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project>
<!--
Roslyn version
-->
<PropertyGroup>
<MajorVersion>4</MajorVersion>
<MinorVersion>1</MinorVersion>
<PatchVersion>0</PatchVersion>
<PreReleaseVersionLabel>1</PreReleaseVersionLabel>
<VersionPrefix>$(MajorVersion).$(MinorVersion).$(PatchVersion)</VersionPrefix>
<!--
By default the assembly version in official builds is "$(MajorVersion).$(MinorVersion).0.0".
Keep the setting conditional. The toolset sets the assembly version to 42.42.42.42 if not set explicitly.
-->
<AssemblyVersion Condition="'$(OfficialBuild)' == 'true' or '$(DotNetUseShippingVersions)' == 'true'">$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion>
<!--
Arcade overrides our VersionPrefix when MajorVersion and MinorVersion are specified. Clear them so that
we can keep the PatchVersion until we are using an SDK that includes https://github.com/dotnet/arcade/pull/3601
-->
<MajorVersion>
</MajorVersion>
<MinorVersion>
</MinorVersion>
<MicrosoftNetCompilersToolsetVersion>4.0.0-5.21469.2</MicrosoftNetCompilersToolsetVersion>
</PropertyGroup>
<PropertyGroup>
<!-- Versions used by several individual references below -->
<RoslynDiagnosticsNugetPackageVersion>3.3.3-beta1.21105.3</RoslynDiagnosticsNugetPackageVersion>
<MicrosoftCodeAnalysisNetAnalyzersVersion>6.0.0-rc1.21366.2</MicrosoftCodeAnalysisNetAnalyzersVersion>
<MicrosoftCodeAnalysisTestingVersion>1.1.0-beta1.21322.2</MicrosoftCodeAnalysisTestingVersion>
<!-- CodeStyleAnalyzerVersion should we updated together with version of dotnet-format in dotnet-tools.json -->
<CodeStyleAnalyzerVersion>4.0.0-3.final</CodeStyleAnalyzerVersion>
<VisualStudioEditorPackagesVersion>16.10.230</VisualStudioEditorPackagesVersion>
<VisualStudioEditorNewPackagesVersion>17.0.391-preview-g5e248c9073</VisualStudioEditorNewPackagesVersion>
<ILAsmPackageVersion>5.0.0-alpha1.19409.1</ILAsmPackageVersion>
<ILDAsmPackageVersion>5.0.0-preview.1.20112.8</ILDAsmPackageVersion>
<MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>17.0.4129-g0e33707768</MicrosoftVisualStudioLanguageServerProtocolPackagesVersion>
<MicrosoftVisualStudioShellPackagesVersion>17.0.0-previews-4-31709-430</MicrosoftVisualStudioShellPackagesVersion>
<MicrosoftBuildPackagesVersion>16.5.0</MicrosoftBuildPackagesVersion>
<!-- The version of Roslyn we build Source Generators against that are built in this
repository. This must be lower than MicrosoftNetCompilersToolsetVersion,
but not higher than our minimum dogfoodable Visual Studio version, or else
the generators we build would load on the command line but not load in IDEs. -->
<SourceGeneratorMicrosoftCodeAnalysisVersion>3.8.0</SourceGeneratorMicrosoftCodeAnalysisVersion>
</PropertyGroup>
<!--
Dependency versions
-->
<PropertyGroup>
<BasicUndoVersion>0.9.3</BasicUndoVersion>
<BasicReferenceAssembliesNetStandard20Version>1.2.4</BasicReferenceAssembliesNetStandard20Version>
<BasicReferenceAssembliesNet50Version>1.2.4</BasicReferenceAssembliesNet50Version>
<BasicReferenceAssembliesNet60Version>1.2.4</BasicReferenceAssembliesNet60Version>
<BasicReferenceAssembliesNetStandard13Version>1.2.4</BasicReferenceAssembliesNetStandard13Version>
<BenchmarkDotNetVersion>0.13.0</BenchmarkDotNetVersion>
<BenchmarkDotNetDiagnosticsWindowsVersion>0.13.0</BenchmarkDotNetDiagnosticsWindowsVersion>
<DiffPlexVersion>1.4.4</DiffPlexVersion>
<FakeSignVersion>0.9.2</FakeSignVersion>
<HumanizerCoreVersion>2.2.0</HumanizerCoreVersion>
<ICSharpCodeDecompilerVersion>6.1.0.5902</ICSharpCodeDecompilerVersion>
<MicrosoftBuildVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildVersion>
<MicrosoftBuildFrameworkVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildFrameworkVersion>
<MicrosoftBuildLocatorVersion>1.2.6</MicrosoftBuildLocatorVersion>
<MicrosoftBuildRuntimeVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildRuntimeVersion>
<MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildPackagesVersion)</MicrosoftBuildTasksCoreVersion>
<NuGetVisualStudioContractsVersion>6.0.0-preview.0.15</NuGetVisualStudioContractsVersion>
<MicrosoftVisualStudioRpcContractsVersion>16.10.23</MicrosoftVisualStudioRpcContractsVersion>
<!--
Since the Microsoft.CodeAnalysis.Analyzers package is a public dependency of our NuGet
packages we will keep it untied to the RoslynDiagnosticsNugetPackageVersion we use for
other analyzers to ensure it stays on a release version.
-->
<MicrosoftCodeAnalysisAnalyzersVersion>3.3.2</MicrosoftCodeAnalysisAnalyzersVersion>
<MicrosoftCodeAnalysisBuildTasksVersion>2.0.0-rc2-61102-09</MicrosoftCodeAnalysisBuildTasksVersion>
<MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpAnalyzerTestingXUnitVersion>
<MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeFixTestingXUnitVersion>
<MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisCSharpCodeRefactoringTestingXUnitVersion>
<MicrosoftCodeAnalysisCSharpCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisCSharpCodeStyleVersion>
<MicrosoftCodeAnalysisElfieVersion>1.0.0-rc14</MicrosoftCodeAnalysisElfieVersion>
<MicrosoftCodeAnalysisTestResourcesProprietaryVersion>2.0.44</MicrosoftCodeAnalysisTestResourcesProprietaryVersion>
<MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicAnalyzerTestingXUnitVersion>
<MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion>
<MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>$(MicrosoftCodeAnalysisTestingVersion)</MicrosoftCodeAnalysisVisualBasicCodeRefactoringTestingXUnitVersion>
<MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>$(CodeStyleAnalyzerVersion)</MicrosoftCodeAnalysisVisualBasicCodeStyleVersion>
<MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>3.3.0</MicrosoftCodeAnalysisAnalyzerUtilitiesVersion>
<MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</MicrosoftCodeAnalysisPerformanceSensitiveAnalyzersVersion>
<MicrosoftCSharpVersion>4.3.0</MicrosoftCSharpVersion>
<MicrosoftDevDivOptimizationDataPowerShellVersion>1.0.339</MicrosoftDevDivOptimizationDataPowerShellVersion>
<MicrosoftDiagnosticsRuntimeVersion>0.8.31-beta</MicrosoftDiagnosticsRuntimeVersion>
<MicrosoftDiagnosticsTracingTraceEventVersion>1.0.35</MicrosoftDiagnosticsTracingTraceEventVersion>
<MicrosoftDiaSymReaderVersion>1.3.0</MicrosoftDiaSymReaderVersion>
<MicrosoftDiaSymReaderConverterVersion>1.1.0-beta2-21477-02</MicrosoftDiaSymReaderConverterVersion>
<MicrosoftDiaSymReaderConverterXmlVersion>1.1.0-beta2-21477-02</MicrosoftDiaSymReaderConverterXmlVersion>
<MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion>
<MicrosoftDiaSymReaderPortablePdbVersion>1.5.0</MicrosoftDiaSymReaderPortablePdbVersion>
<MicrosoftExtensionsLoggingVersion>5.0.0</MicrosoftExtensionsLoggingVersion>
<MicrosoftExtensionsLoggingConsoleVersion>5.0.0</MicrosoftExtensionsLoggingConsoleVersion>
<MicrosoftIdentityModelClientsActiveDirectoryVersion>3.13.8</MicrosoftIdentityModelClientsActiveDirectoryVersion>
<MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>15.8.27812-alpha</MicrosoftInternalPerformanceCodeMarkersDesignTimeVersion>
<MicrosoftInternalVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftInternalVisualStudioInteropVersion>
<MicrosoftMetadataVisualizerVersion>1.0.0-beta3.21075.2</MicrosoftMetadataVisualizerVersion>
<MicrosoftNETBuildExtensionsVersion>2.2.101</MicrosoftNETBuildExtensionsVersion>
<MicrosoftNETCorePlatformsVersion>2.1.2</MicrosoftNETCorePlatformsVersion>
<MicrosoftNETCoreAppRefVersion>5.0.0</MicrosoftNETCoreAppRefVersion>
<MicrosoftNETFrameworkReferenceAssembliesnet461Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet461Version>
<MicrosoftNETFrameworkReferenceAssembliesnet451Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet451Version>
<MicrosoftNETFrameworkReferenceAssembliesnet40Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet40Version>
<MicrosoftNETFrameworkReferenceAssembliesnet20Version>1.0.0</MicrosoftNETFrameworkReferenceAssembliesnet20Version>
<jnm2ReferenceAssembliesnet35Version>1.0.1</jnm2ReferenceAssembliesnet35Version>
<MicrosoftNETCoreTestHostVersion>1.1.0</MicrosoftNETCoreTestHostVersion>
<MicrosoftNetFX20Version>1.0.3</MicrosoftNetFX20Version>
<MicrosoftNETFrameworkReferenceAssembliesVersion>1.0.0</MicrosoftNETFrameworkReferenceAssembliesVersion>
<MicrosoftNetSdkVersion>2.0.0-alpha-20170405-2</MicrosoftNetSdkVersion>
<MicrosoftNuGetBuildTasksVersion>0.1.0</MicrosoftNuGetBuildTasksVersion>
<MicrosoftPortableTargetsVersion>0.1.2-dev</MicrosoftPortableTargetsVersion>
<MicrosoftServiceHubClientVersion>3.0.2065</MicrosoftServiceHubClientVersion>
<MicrosoftServiceHubFrameworkVersion>3.0.2065</MicrosoftServiceHubFrameworkVersion>
<MicrosoftVisualBasicVersion>10.1.0</MicrosoftVisualBasicVersion>
<MicrosoftVisualStudioCacheVersion>17.0.13-alpha</MicrosoftVisualStudioCacheVersion>
<MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>15.8.27812-alpha</MicrosoftVisualStudioCallHierarchyPackageDefinitionsVersion>
<MicrosoftVisualStudioCodeAnalysisSdkUIVersion>15.8.27812-alpha</MicrosoftVisualStudioCodeAnalysisSdkUIVersion>
<MicrosoftVisualStudioComponentModelHostVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioComponentModelHostVersion>
<MicrosoftVisualStudioCompositionVersion>16.9.20</MicrosoftVisualStudioCompositionVersion>
<MicrosoftVisualStudioCoreUtilityVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioCoreUtilityVersion>
<MicrosoftVisualStudioDebuggerUIInterfacesVersion>17.2.0-beta.21417.1</MicrosoftVisualStudioDebuggerUIInterfacesVersion>
<MicrosoftVisualStudioDebuggerContractsVersion>17.2.0-beta.21417.1</MicrosoftVisualStudioDebuggerContractsVersion>
<MicrosoftVisualStudioDebuggerEngineimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerEngineimplementationVersion>
<MicrosoftVisualStudioDebuggerMetadataimplementationVersion>17.0.1042805-preview</MicrosoftVisualStudioDebuggerMetadataimplementationVersion>
<MicrosoftVisualStudioDesignerInterfacesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDesignerInterfacesVersion>
<MicrosoftVisualStudioDiagnosticsMeasurementVersion>17.0.0-preview-1-30928-1112</MicrosoftVisualStudioDiagnosticsMeasurementVersion>
<MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioDiagnosticsPerformanceProviderVersion>
<MicrosoftVisualStudioSDKEmbedInteropTypesVersion>15.0.36</MicrosoftVisualStudioSDKEmbedInteropTypesVersion>
<MicrosoftVisualStudioEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioEditorVersion>
<MicrosoftVisualStudioGraphModelVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioGraphModelVersion>
<MicrosoftVisualStudioImageCatalogVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImageCatalogVersion>
<MicrosoftVisualStudioImagingVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingVersion>
<MicrosoftVisualStudioImagingInterop140DesignTimeVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioImagingInterop140DesignTimeVersion>
<MicrosoftVisualStudioInteropVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioInteropVersion>
<MicrosoftVisualStudioLanguageVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageVersion>
<MicrosoftVisualStudioLanguageCallHierarchyVersion>15.8.27812-alpha</MicrosoftVisualStudioLanguageCallHierarchyVersion>
<MicrosoftVisualStudioLanguageIntellisenseVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageIntellisenseVersion>
<MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>17.0.25-g975cd8c52c</MicrosoftVisualStudioLanguageNavigateToInterfacesVersion>
<MicrosoftVisualStudioLanguageServerProtocolVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolVersion>
<MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolExtensionsVersion>
<MicrosoftVisualStudioLanguageServerProtocolInternalVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerProtocolInternalVersion>
<MicrosoftVisualStudioLanguageServerClientVersion>$(MicrosoftVisualStudioLanguageServerProtocolPackagesVersion)</MicrosoftVisualStudioLanguageServerClientVersion>
<MicrosoftVisualStudioLanguageStandardClassificationVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioLanguageStandardClassificationVersion>
<MicrosoftVisualStudioLiveShareVersion>2.18.6</MicrosoftVisualStudioLiveShareVersion>
<MicrosoftVisualStudioLiveShareLanguageServicesVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesVersion>
<MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>3.0.6</MicrosoftVisualStudioLiveShareLanguageServicesGuestVersion>
<MicrosoftVisualStudioLiveShareWebEditorsVersion>3.0.8</MicrosoftVisualStudioLiveShareWebEditorsVersion>
<MicrosoftVisualStudioPlatformVSEditorVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioPlatformVSEditorVersion>
<MicrosoftVisualStudioProgressionCodeSchemaVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCodeSchemaVersion>
<MicrosoftVisualStudioProgressionCommonVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionCommonVersion>
<MicrosoftVisualStudioProgressionInterfacesVersion>15.8.27812-alpha</MicrosoftVisualStudioProgressionInterfacesVersion>
<MicrosoftVisualStudioProjectSystemVersion>17.0.77-pre-g62a6cb5699</MicrosoftVisualStudioProjectSystemVersion>
<MicrosoftVisualStudioProjectSystemManagedVersion>2.3.6152103</MicrosoftVisualStudioProjectSystemManagedVersion>
<MicrosoftVisualStudioRemoteControlVersion>16.3.41</MicrosoftVisualStudioRemoteControlVersion>
<MicrosoftVisualStudioSDKAnalyzersVersion>16.10.10</MicrosoftVisualStudioSDKAnalyzersVersion>
<MicrosoftVisualStudioSetupConfigurationInteropVersion>1.16.30</MicrosoftVisualStudioSetupConfigurationInteropVersion>
<MicrosoftVisualStudioShell150Version>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShell150Version>
<MicrosoftVisualStudioShellFrameworkVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellFrameworkVersion>
<MicrosoftVisualStudioShellDesignVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioShellDesignVersion>
<MicrosoftVisualStudioTelemetryVersion>16.3.211</MicrosoftVisualStudioTelemetryVersion>
<MicrosoftVisualStudioTemplateWizardInterfaceVersion>8.0.0.0-alpha</MicrosoftVisualStudioTemplateWizardInterfaceVersion>
<MicrosoftVisualStudioTextDataVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextDataVersion>
<MicrosoftVisualStudioTextInternalVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextInternalVersion>
<MicrosoftVisualStudioTextLogicVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextLogicVersion>
<MicrosoftVisualStudioTextUIVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIVersion>
<MicrosoftVisualStudioTextUIWpfVersion>$(VisualStudioEditorNewPackagesVersion)</MicrosoftVisualStudioTextUIWpfVersion>
<MicrosoftVisualStudioTextUICocoaVersion>$(VisualStudioEditorPackagesVersion)</MicrosoftVisualStudioTextUICocoaVersion>
<MicrosoftVisualStudioThreadingAnalyzersVersion>17.0.46-alpha</MicrosoftVisualStudioThreadingAnalyzersVersion>
<MicrosoftVisualStudioThreadingVersion>17.0.46-alpha</MicrosoftVisualStudioThreadingVersion>
<MicrosoftVisualStudioUtilitiesVersion>$(MicrosoftVisualStudioShellPackagesVersion)</MicrosoftVisualStudioUtilitiesVersion>
<MicrosoftVisualStudioValidationVersion>17.0.23-alpha</MicrosoftVisualStudioValidationVersion>
<MicrosoftVisualStudioInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioInteractiveWindowVersion>
<MicrosoftVisualStudioVsInteractiveWindowVersion>4.0.0-beta.21267.2</MicrosoftVisualStudioVsInteractiveWindowVersion>
<MicrosoftVisualStudioWorkspaceVSIntegrationVersion>16.3.43</MicrosoftVisualStudioWorkspaceVSIntegrationVersion>
<MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion>
<MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion>
<MSBuildStructuredLoggerVersion>2.1.500</MSBuildStructuredLoggerVersion>
<MDbgVersion>0.1.0</MDbgVersion>
<MonoOptionsVersion>6.6.0.161</MonoOptionsVersion>
<MoqVersion>4.10.1</MoqVersion>
<NerdbankStreamsVersion>2.7.74</NerdbankStreamsVersion>
<NuGetVisualStudioVersion>6.0.0-preview.0.15</NuGetVisualStudioVersion>
<NuGetSolutionRestoreManagerInteropVersion>4.8.0</NuGetSolutionRestoreManagerInteropVersion>
<MicrosoftDiaSymReaderPdb2PdbVersion>1.1.0-beta1-62506-02</MicrosoftDiaSymReaderPdb2PdbVersion>
<RestSharpVersion>105.2.3</RestSharpVersion>
<RichCodeNavEnvVarDumpVersion>0.1.1643-alpha</RichCodeNavEnvVarDumpVersion>
<RoslynBuildUtilVersion>0.9.8-beta</RoslynBuildUtilVersion>
<RoslynDependenciesOptimizationDataVersion>3.0.0-beta2-19053-01</RoslynDependenciesOptimizationDataVersion>
<RoslynDiagnosticsAnalyzersVersion>$(RoslynDiagnosticsNugetPackageVersion)</RoslynDiagnosticsAnalyzersVersion>
<RoslynToolsVSIXExpInstallerVersion>1.1.0-beta3.21418.3</RoslynToolsVSIXExpInstallerVersion>
<RoslynMicrosoftVisualStudioExtensionManagerVersion>0.0.4</RoslynMicrosoftVisualStudioExtensionManagerVersion>
<SourceBrowserVersion>1.0.21</SourceBrowserVersion>
<SystemBuffersVersion>4.5.1</SystemBuffersVersion>
<SystemCompositionVersion>1.0.31</SystemCompositionVersion>
<SystemCodeDomVersion>4.7.0</SystemCodeDomVersion>
<SystemCommandLineVersion>2.0.0-beta1.20574.7</SystemCommandLineVersion>
<SystemCommandLineExperimentalVersion>0.3.0-alpha.19577.1</SystemCommandLineExperimentalVersion>
<SystemComponentModelCompositionVersion>4.5.0</SystemComponentModelCompositionVersion>
<SystemDrawingCommonVersion>4.5.0</SystemDrawingCommonVersion>
<SystemIOFileSystemVersion>4.3.0</SystemIOFileSystemVersion>
<SystemIOFileSystemPrimitivesVersion>4.3.0</SystemIOFileSystemPrimitivesVersion>
<SystemIOPipesAccessControlVersion>4.5.1</SystemIOPipesAccessControlVersion>
<SystemIOPipelinesVersion>5.0.1</SystemIOPipelinesVersion>
<SystemManagementVersion>5.0.0-preview.8.20407.11</SystemManagementVersion>
<SystemMemoryVersion>4.5.4</SystemMemoryVersion>
<SystemResourcesExtensionsVersion>4.7.1</SystemResourcesExtensionsVersion>
<SystemRuntimeCompilerServicesUnsafeVersion>5.0.0</SystemRuntimeCompilerServicesUnsafeVersion>
<SystemRuntimeLoaderVersion>4.3.0</SystemRuntimeLoaderVersion>
<SystemSecurityPrincipalVersion>4.3.0</SystemSecurityPrincipalVersion>
<SystemTextEncodingCodePagesVersion>4.5.1</SystemTextEncodingCodePagesVersion>
<SystemTextEncodingExtensionsVersion>4.3.0</SystemTextEncodingExtensionsVersion>
<!-- Note: When updating SystemTextJsonVersion ensure that the version is no higher than what is used by MSBuild. -->
<SystemTextJsonVersion>4.7.0</SystemTextJsonVersion>
<SystemThreadingTasksDataflowVersion>5.0.0</SystemThreadingTasksDataflowVersion>
<!-- We need System.ValueTuple assembly version at least 4.0.3.0 on net47 to make F5 work against Dev15 - see https://github.com/dotnet/roslyn/issues/29705 -->
<SystemValueTupleVersion>4.5.0</SystemValueTupleVersion>
<SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion>
<SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion>
<UIAComWrapperVersion>1.1.0.14</UIAComWrapperVersion>
<MicroBuildPluginsSwixBuildVersion>1.1.33</MicroBuildPluginsSwixBuildVersion>
<MicrosoftVSSDKBuildToolsVersion>17.0.1056-Dev17PIAs-g9dffd635</MicrosoftVSSDKBuildToolsVersion>
<MicrosoftVSSDKVSDConfigToolVersion>16.0.2032702</MicrosoftVSSDKVSDConfigToolVersion>
<VsWebsiteInteropVersion>8.0.50727</VsWebsiteInteropVersion>
<vswhereVersion>2.4.1</vswhereVersion>
<XamarinMacVersion>1.0.0</XamarinMacVersion>
<xunitVersion>2.4.1-pre.build.4059</xunitVersion>
<xunitanalyzersVersion>0.10.0</xunitanalyzersVersion>
<xunitassertVersion>$(xunitVersion)</xunitassertVersion>
<XunitCombinatorialVersion>1.3.2</XunitCombinatorialVersion>
<XUnitXmlTestLoggerVersion>2.1.26</XUnitXmlTestLoggerVersion>
<xunitextensibilitycoreVersion>$(xunitVersion)</xunitextensibilitycoreVersion>
<xunitrunnerconsoleVersion>2.4.1-pre.build.4059</xunitrunnerconsoleVersion>
<xunitrunnerwpfVersion>1.0.51</xunitrunnerwpfVersion>
<xunitrunnervisualstudioVersion>$(xunitVersion)</xunitrunnervisualstudioVersion>
<xunitextensibilityexecutionVersion>$(xunitVersion)</xunitextensibilityexecutionVersion>
<runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILAsmPackageVersion>
<runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILAsmPackageVersion>
<runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>$(ILAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILAsmPackageVersion>
<runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeWinX64MicrosoftNETCoreILDAsmPackageVersion>
<runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeLinuxX64MicrosoftNETCoreILDAsmPackageVersion>
<runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>$(ILDAsmPackageVersion)</runtimeOSXX64MicrosoftNETCoreILDAsmPackageVersion>
<!--
NOTE: The following dependencies have been identified as particularly problematic to update.
If you bump their versions, you must push your changes to a dev branch in dotnet/roslyn and
create a test insertion in Visual Studio to validate.
-->
<NewtonsoftJsonVersion>13.0.1</NewtonsoftJsonVersion>
<StreamJsonRpcVersion>2.8.21</StreamJsonRpcVersion>
<!--
When updating the S.C.I or S.R.M version please let the MSBuild team know in advance so they
can update to the same version. Version changes require a VS test insertion for validation.
-->
<SystemCollectionsImmutableVersion>5.0.0</SystemCollectionsImmutableVersion>
<SystemReflectionMetadataVersion>5.0.0</SystemReflectionMetadataVersion>
<MicrosoftBclAsyncInterfacesVersion>5.0.0</MicrosoftBclAsyncInterfacesVersion>
</PropertyGroup>
<PropertyGroup>
<UsingToolPdbConverter>true</UsingToolPdbConverter>
<UsingToolSymbolUploader>true</UsingToolSymbolUploader>
<UsingToolNuGetRepack>true</UsingToolNuGetRepack>
<UsingToolVSSDK>true</UsingToolVSSDK>
<UsingToolNetFrameworkReferenceAssemblies>true</UsingToolNetFrameworkReferenceAssemblies>
<UsingToolIbcOptimization>true</UsingToolIbcOptimization>
<UsingToolVisualStudioIbcTraining>true</UsingToolVisualStudioIbcTraining>
<UsingToolXliff>true</UsingToolXliff>
<UsingToolXUnit>true</UsingToolXUnit>
<DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles>
<!--
When using a bootstrap builder we don't want to use the Microsoft.Net.Compilers.Toolset package but
rather explicitly override it.
-->
<UsingToolMicrosoftNetCompilers Condition="'$(BootstrapBuildPath)' == ''">true</UsingToolMicrosoftNetCompilers>
<UseVSTestRunner>true</UseVSTestRunner>
</PropertyGroup>
</Project>
| 1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/EditorFeatures/Core.Wpf/InlineDiagnostics/InlineDiagnosticsAdornmentManager.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Windows.Controls;
using Microsoft.CodeAnalysis.Editor.Implementation.Adornments;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.InlineDiagnostics
{
internal class InlineDiagnosticsAdornmentManager : AbstractAdornmentManager<InlineDiagnosticsTag>
{
private readonly IClassificationTypeRegistryService _classificationRegistryService;
private readonly IClassificationFormatMap _formatMap;
public InlineDiagnosticsAdornmentManager(
IThreadingContext threadingContext, IWpfTextView textView, IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IAsynchronousOperationListener asyncListener, string adornmentLayerName,
IClassificationFormatMapService classificationFormatMapService,
IClassificationTypeRegistryService classificationTypeRegistryService)
: base(threadingContext, textView, tagAggregatorFactoryService, asyncListener, adornmentLayerName)
{
_classificationRegistryService = classificationTypeRegistryService;
_formatMap = classificationFormatMapService.GetClassificationFormatMap(textView);
_formatMap.ClassificationFormatMappingChanged += OnClassificationFormatMappingChanged;
TextView.ViewportWidthChanged += TextView_ViewportWidthChanged;
}
/// <summary>
/// Need to remove the tags if they intersect with the editor view, but only if the option
/// to place the tags at the end of the editor is selected.
/// </summary>
private void TextView_ViewportWidthChanged(object sender, EventArgs e)
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
if (AdornmentLayer is null)
{
return;
}
if (!TryTextView_ViewportWidthChanged(out var workspace, out var document))
{
AdornmentLayer.RemoveAllAdornments();
return;
}
var option = workspace.Options.GetOption(InlineDiagnosticsOptions.Location, document.Project.Language);
if (option == InlineDiagnosticsLocations.PlacedAtEndOfEditor)
{
var normalizedCollectionSpan = new NormalizedSnapshotSpanCollection(TextView.TextViewLines.FormattedSpan);
UpdateSpans_CallOnlyOnUIThread(normalizedCollectionSpan, removeOldTags: true);
}
}
private bool TryTextView_ViewportWidthChanged(
[NotNullWhen(true)] out Workspace? workspace,
[NotNullWhen(true)] out Document? document)
{
var sourceContainer = TextView.TextBuffer.AsTextContainer();
workspace = null;
document = null;
if (sourceContainer is null)
{
return false;
}
if (!Workspace.TryGetWorkspace(sourceContainer, out workspace))
{
return false;
}
document = sourceContainer.GetOpenDocumentInCurrentContext();
return document != null;
}
private void OnClassificationFormatMappingChanged(object sender, EventArgs e)
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
if (AdornmentLayer is not null)
{
foreach (var element in AdornmentLayer.Elements)
{
var tag = (InlineDiagnosticsTag)element.Tag;
var classificationType = _classificationRegistryService.GetClassificationType(InlineDiagnosticsTag.GetClassificationId(tag.ErrorType));
var format = GetFormat(classificationType);
InlineDiagnosticsTag.UpdateColor(format, element.Adornment);
}
}
}
private TextFormattingRunProperties GetFormat(IClassificationType classificationType)
{
return _formatMap.GetTextProperties(classificationType);
}
/// <summary>
/// Get the spans located on each line so that it can only display the first one that appears on the line
/// </summary>
private void AddSpansOnEachLine(NormalizedSnapshotSpanCollection changedSpanCollection,
Dictionary<int, IMappingTagSpan<InlineDiagnosticsTag>> map)
{
var viewLines = TextView.TextViewLines;
foreach (var changedSpan in changedSpanCollection)
{
if (!viewLines.IntersectsBufferSpan(changedSpan))
{
continue;
}
var tagSpans = TagAggregator.GetTags(changedSpan);
foreach (var tagMappingSpan in tagSpans)
{
if (!ShouldDrawTag(changedSpan, tagMappingSpan, out var mappedPoint))
{
continue;
}
// mappedPoint is known to not be null here because it is checked in the ShouldDrawTag method call.
var lineNum = mappedPoint.GetContainingLine().LineNumber;
// If the line does not have an associated tagMappingSpan and changedSpan, then add the first one.
if (!map.TryGetValue(lineNum, out var value))
{
map.Add(lineNum, tagMappingSpan);
}
else if (value.Tag.ErrorType is not PredefinedErrorTypeNames.SyntaxError && tagMappingSpan.Tag.ErrorType is PredefinedErrorTypeNames.SyntaxError)
{
// Draw the first instance of an error, if what is stored in the map at a specific line is
// not an error, then replace it. Otherwise, just get the first warning on the line.
map[lineNum] = tagMappingSpan;
}
}
}
}
/// <summary>
/// Iterates through the mapping of line number to span and draws the diagnostic in the appropriate position on the screen,
/// as well as adding the tag to the adornment layer.
/// </summary>
protected override void AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection)
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
if (changedSpanCollection.IsEmpty())
{
return;
}
var viewLines = TextView.TextViewLines;
using var _ = PooledDictionary<int, IMappingTagSpan<InlineDiagnosticsTag>>.GetInstance(out var map);
AddSpansOnEachLine(changedSpanCollection, map);
foreach (var (lineNum, tagMappingSpan) in map)
{
// Mapping the IMappingTagSpan back up to the TextView's visual snapshot to ensure there will
// be no adornments drawn on disjoint spans.
if (!TryMapToSingleSnapshotSpan(tagMappingSpan.Span, TextView.TextSnapshot, out var span))
{
continue;
}
var geometry = viewLines.GetMarkerGeometry(span);
if (geometry is null)
{
continue;
}
// Need to get the SnapshotPoint to be able to get the IWpfTextViewLine
var point = tagMappingSpan.Span.Start.GetPoint(TextView.TextSnapshot, PositionAffinity.Predecessor);
if (point == null)
{
continue;
}
var tag = tagMappingSpan.Tag;
var classificationType = _classificationRegistryService.GetClassificationType(InlineDiagnosticsTag.GetClassificationId(tag.ErrorType));
var graphicsResult = tag.GetGraphics(TextView, geometry, GetFormat(classificationType));
var lineView = TextView.GetTextViewLineContainingBufferPosition(point.Value);
var visualElement = graphicsResult.VisualElement;
// Only place the diagnostics if the diagnostic would not intersect with the editor window
if (lineView.Right >= TextView.ViewportWidth - visualElement.DesiredSize.Width)
{
continue;
}
Canvas.SetLeft(visualElement,
tag.Location == InlineDiagnosticsLocations.PlacedAtEndOfCode ? lineView.Right :
tag.Location == InlineDiagnosticsLocations.PlacedAtEndOfEditor ? TextView.ViewportRight - visualElement.DesiredSize.Width :
throw ExceptionUtilities.UnexpectedValue(tag.Location));
Canvas.SetTop(visualElement, geometry.Bounds.Bottom - visualElement.DesiredSize.Height);
AdornmentLayer.AddAdornment(
behavior: AdornmentPositioningBehavior.TextRelative,
visualSpan: span,
tag: tag,
adornment: visualElement,
removedCallback: delegate { graphicsResult.Dispose(); });
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Windows.Controls;
using Microsoft.CodeAnalysis.Editor.Implementation.Adornments;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.InlineDiagnostics
{
internal class InlineDiagnosticsAdornmentManager : AbstractAdornmentManager<InlineDiagnosticsTag>
{
private readonly IClassificationTypeRegistryService _classificationRegistryService;
private readonly IClassificationFormatMap _formatMap;
private readonly ITagAggregator<IEndOfLineAdornmentTag> _endLineTagAggregator;
public InlineDiagnosticsAdornmentManager(
IThreadingContext threadingContext, IWpfTextView textView, IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IAsynchronousOperationListener asyncListener, string adornmentLayerName,
IClassificationFormatMapService classificationFormatMapService,
IClassificationTypeRegistryService classificationTypeRegistryService)
: base(threadingContext, textView, tagAggregatorFactoryService, asyncListener, adornmentLayerName)
{
_classificationRegistryService = classificationTypeRegistryService;
_formatMap = classificationFormatMapService.GetClassificationFormatMap(textView);
_formatMap.ClassificationFormatMappingChanged += OnClassificationFormatMappingChanged;
TextView.ViewportWidthChanged += TextView_ViewportWidthChanged;
_endLineTagAggregator = tagAggregatorFactoryService.CreateTagAggregator<IEndOfLineAdornmentTag>(textView);
_endLineTagAggregator.BatchedTagsChanged += EndLineTagAggregator_BatchedTagsChanged;
}
/// <summary>
/// Getting all tags changed events and removing all inline diagnostics to be redrawn
/// based on if they intersect with any IEndOfLineAdornmentTags after the layout change
/// has completed.
/// </summary>
private void EndLineTagAggregator_BatchedTagsChanged(object sender, BatchedTagsChangedEventArgs e)
{
TextView.QueuePostLayoutAction(() =>
{
var allSpans = e.Spans.SelectMany(span => span.GetSpans(TextView.TextBuffer));
UpdateSpans_CallOnlyOnUIThread(new NormalizedSnapshotSpanCollection(allSpans), removeOldTags: true);
});
}
/// <summary>
/// Need to remove the tags if they intersect with the editor view, but only if the option
/// to place the tags at the end of the editor is selected.
/// </summary>
private void TextView_ViewportWidthChanged(object sender, EventArgs e)
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
if (AdornmentLayer is null)
{
return;
}
if (!TryTextView_ViewportWidthChanged(out var workspace, out var document))
{
AdornmentLayer.RemoveAllAdornments();
return;
}
var option = workspace.Options.GetOption(InlineDiagnosticsOptions.Location, document.Project.Language);
if (option == InlineDiagnosticsLocations.PlacedAtEndOfEditor)
{
var normalizedCollectionSpan = new NormalizedSnapshotSpanCollection(TextView.TextViewLines.FormattedSpan);
UpdateSpans_CallOnlyOnUIThread(normalizedCollectionSpan, removeOldTags: true);
}
}
private bool TryTextView_ViewportWidthChanged(
[NotNullWhen(true)] out Workspace? workspace,
[NotNullWhen(true)] out Document? document)
{
var sourceContainer = TextView.TextBuffer.AsTextContainer();
workspace = null;
document = null;
if (sourceContainer is null)
{
return false;
}
if (!Workspace.TryGetWorkspace(sourceContainer, out workspace))
{
return false;
}
document = sourceContainer.GetOpenDocumentInCurrentContext();
return document != null;
}
private void OnClassificationFormatMappingChanged(object sender, EventArgs e)
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
if (AdornmentLayer is not null)
{
foreach (var element in AdornmentLayer.Elements)
{
var tag = (InlineDiagnosticsTag)element.Tag;
var classificationType = _classificationRegistryService.GetClassificationType(InlineDiagnosticsTag.GetClassificationId(tag.ErrorType));
var format = GetFormat(classificationType);
InlineDiagnosticsTag.UpdateColor(format, element.Adornment);
}
}
}
private TextFormattingRunProperties GetFormat(IClassificationType classificationType)
{
return _formatMap.GetTextProperties(classificationType);
}
/// <summary>
/// Get the spans located on each line so that it can only display the first one that appears on the line
/// </summary>
private void AddSpansOnEachLine(NormalizedSnapshotSpanCollection changedSpanCollection,
Dictionary<int, IMappingTagSpan<InlineDiagnosticsTag>> map)
{
var viewLines = TextView.TextViewLines;
foreach (var changedSpan in changedSpanCollection)
{
if (!viewLines.IntersectsBufferSpan(changedSpan))
{
continue;
}
var tagSpans = TagAggregator.GetTags(changedSpan);
foreach (var tagMappingSpan in tagSpans)
{
if (!ShouldDrawTag(changedSpan, tagMappingSpan, out var mappedPoint))
{
continue;
}
// mappedPoint is known to not be null here because it is checked in the ShouldDrawTag method call.
var lineNum = mappedPoint.GetContainingLine().LineNumber;
// If the line does not have an associated tagMappingSpan and changedSpan, then add the first one.
if (!map.TryGetValue(lineNum, out var value))
{
map.Add(lineNum, tagMappingSpan);
}
else if (value.Tag.ErrorType is not PredefinedErrorTypeNames.SyntaxError && tagMappingSpan.Tag.ErrorType is PredefinedErrorTypeNames.SyntaxError)
{
// Draw the first instance of an error, if what is stored in the map at a specific line is
// not an error, then replace it. Otherwise, just get the first warning on the line.
map[lineNum] = tagMappingSpan;
}
}
}
}
/// <summary>
/// Iterates through the mapping of line number to span and draws the diagnostic in the appropriate position on the screen,
/// as well as adding the tag to the adornment layer.
/// </summary>
protected override void AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection)
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess());
if (changedSpanCollection.IsEmpty())
{
return;
}
var viewLines = TextView.TextViewLines;
using var _ = PooledDictionary<int, IMappingTagSpan<InlineDiagnosticsTag>>.GetInstance(out var map);
AddSpansOnEachLine(changedSpanCollection, map);
foreach (var (lineNum, tagMappingSpan) in map)
{
// Mapping the IMappingTagSpan back up to the TextView's visual snapshot to ensure there will
// be no adornments drawn on disjoint spans.
if (!TryMapToSingleSnapshotSpan(tagMappingSpan.Span, TextView.TextSnapshot, out var span))
{
continue;
}
var geometry = viewLines.GetMarkerGeometry(span);
if (geometry is null)
{
continue;
}
// Need to get the SnapshotPoint to be able to get the IWpfTextViewLine
var point = tagMappingSpan.Span.Start.GetPoint(TextView.TextSnapshot, PositionAffinity.Predecessor);
if (point == null)
{
continue;
}
var lineView = viewLines.GetTextViewLineContainingBufferPosition(point.Value);
if (lineView is null)
{
continue;
}
// Looking for IEndOfLineTags and seeing if they exist on the same line as where the
// diagnostic would be drawn. If they are the same, then we do not want to draw
// the diagnostic.
var obstructingTags = _endLineTagAggregator.GetTags(lineView.Extent);
if (obstructingTags.Where(tag => tag.Tag.Type is not "Inline Diagnostics").Any())
{
continue;
}
var tag = tagMappingSpan.Tag;
var classificationType = _classificationRegistryService.GetClassificationType(InlineDiagnosticsTag.GetClassificationId(tag.ErrorType));
var graphicsResult = tag.GetGraphics(TextView, geometry, GetFormat(classificationType));
var visualElement = graphicsResult.VisualElement;
// Only place the diagnostics if the diagnostic would not intersect with the editor window
if (lineView.Right >= TextView.ViewportWidth - visualElement.DesiredSize.Width)
{
continue;
}
Canvas.SetLeft(visualElement,
tag.Location == InlineDiagnosticsLocations.PlacedAtEndOfCode ? lineView.Right :
tag.Location == InlineDiagnosticsLocations.PlacedAtEndOfEditor ? TextView.ViewportRight - visualElement.DesiredSize.Width :
throw ExceptionUtilities.UnexpectedValue(tag.Location));
Canvas.SetTop(visualElement, geometry.Bounds.Bottom - visualElement.DesiredSize.Height);
AdornmentLayer.AddAdornment(
behavior: AdornmentPositioningBehavior.TextRelative,
visualSpan: lineView.Extent,
tag: tag,
adornment: visualElement,
removedCallback: delegate { graphicsResult.Dispose(); });
}
}
}
}
| 1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/EditorFeatures/Core.Wpf/InlineDiagnostics/InlineDiagnosticsTag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Adornments;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.InlineDiagnostics
{
internal class InlineDiagnosticsTag : GraphicsTag
{
public const string TagID = "inline diagnostics - ";
public readonly string ErrorType;
public readonly InlineDiagnosticsLocations Location;
private readonly DiagnosticData _diagnostic;
private readonly INavigateToLinkService _navigateToLinkService;
private readonly IEditorFormatMap _editorFormatMap;
private readonly IClassificationFormatMap _classificationFormatMap;
private readonly IClassificationTypeRegistryService _classificationTypeRegistryService;
private readonly IClassificationType? _classificationType;
public InlineDiagnosticsTag(string errorType, DiagnosticData diagnostic, IEditorFormatMap editorFormatMap,
IClassificationFormatMapService classificationFormatMapService, IClassificationTypeRegistryService classificationTypeRegistryService,
InlineDiagnosticsLocations location, INavigateToLinkService navigateToLinkService)
: base(editorFormatMap)
{
ErrorType = errorType;
_diagnostic = diagnostic;
Location = location;
_navigateToLinkService = navigateToLinkService;
_editorFormatMap = editorFormatMap;
_classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap("text");
_classificationTypeRegistryService = classificationTypeRegistryService;
_classificationType = _classificationTypeRegistryService.GetClassificationType("url");
}
/// <summary>
/// Creates a GraphicsResult object which is the error block based on the geometry and formatting set for the item.
/// </summary>
public override GraphicsResult GetGraphics(IWpfTextView view, Geometry bounds, TextFormattingRunProperties format)
{
var block = new TextBlock
{
FontFamily = format.Typeface.FontFamily,
FontSize = 0.75 * format.FontRenderingEmSize,
FontStyle = FontStyles.Normal,
Foreground = format.ForegroundBrush,
Padding = new Thickness(left: 2, top: 0, right: 2, bottom: 0),
};
var idRun = GetRunForId(out var hyperlink);
if (hyperlink is null)
{
block.Inlines.Add(idRun);
}
else
{
// Match the hyperlink color to what the classification is set to by the user
var linkColor = _classificationFormatMap.GetTextProperties(_classificationType);
hyperlink.Foreground = linkColor.ForegroundBrush;
block.Inlines.Add(hyperlink);
hyperlink.RequestNavigate += HandleRequestNavigate;
}
block.Inlines.Add(": " + _diagnostic.Message);
var lineHeight = Math.Floor(format.Typeface.FontFamily.LineSpacing * block.FontSize);
var image = new CrispImage
{
Moniker = GetMoniker(),
MaxHeight = lineHeight,
Margin = new Thickness(1, 0, 5, 0)
};
var border = new Border
{
BorderBrush = format.BackgroundBrush,
BorderThickness = new Thickness(1),
Background = Brushes.Transparent,
Child = new StackPanel
{
Height = lineHeight,
Orientation = Orientation.Horizontal,
Children = { image, block }
},
CornerRadius = new CornerRadius(2),
// Highlighting lines are 2px buffer. So shift us up by one from the bottom so we feel centered between them.
Margin = new Thickness(10, top: 0, right: 0, bottom: 1),
Padding = new Thickness(1)
};
// This is used as a workaround to the moniker issues in blue theme
var editorBackground = (Color)_editorFormatMap.GetProperties("TextView Background")["BackgroundColor"];
ImageThemingUtilities.SetImageBackgroundColor(border, editorBackground);
border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
view.ViewportWidthChanged += ViewportWidthChangedHandler;
view.LayoutChanged += View_LayoutChanged;
return new GraphicsResult(border, dispose:
() =>
{
if (hyperlink is not null)
{
hyperlink.RequestNavigate -= HandleRequestNavigate;
}
view.ViewportWidthChanged -= ViewportWidthChangedHandler;
view.LayoutChanged -= View_LayoutChanged;
});
// The tag listens to the width changing to allow the diagnostic UI to move with
// the window as it gets moved.
// The InlineDiagnosticsAdornmentManager listens to the viewport width
// changing to deal with diagnostics intersecting with the text in the editor.
void ViewportWidthChangedHandler(object s, EventArgs e)
{
if (Location is InlineDiagnosticsLocations.PlacedAtEndOfEditor)
{
Canvas.SetLeft(border, view.ViewportRight - border.DesiredSize.Width);
}
}
void View_LayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
if (Location is InlineDiagnosticsLocations.PlacedAtEndOfEditor)
{
Canvas.SetLeft(border, view.ViewportRight - border.DesiredSize.Width);
}
}
void HandleRequestNavigate(object sender, RoutedEventArgs e)
{
var uri = hyperlink.NavigateUri;
_ = _navigateToLinkService.TryNavigateToLinkAsync(uri, CancellationToken.None);
e.Handled = true;
}
Run GetRunForId(out Hyperlink? link)
{
var id = new Run(_diagnostic.Id);
link = null;
if (!string.IsNullOrEmpty(_diagnostic.HelpLink))
{
link = new Hyperlink(id)
{
NavigateUri = new Uri(_diagnostic.HelpLink),
};
}
return id;
}
}
private ImageMoniker GetMoniker()
=> _diagnostic.Severity switch
{
DiagnosticSeverity.Warning => KnownMonikers.StatusWarning,
_ => KnownMonikers.StatusError,
};
public static string GetClassificationId(string error)
=> error switch
{
EditAndContinueErrorTypeDefinition.Name => "inline diagnostics - Edit and Continue",
PredefinedErrorTypeNames.SyntaxError => "inline diagnostics - syntax error",
PredefinedErrorTypeNames.Warning => "inline diagnostics - compiler warning",
_ => throw ExceptionUtilities.UnexpectedValue(error)
};
/// <summary>
/// Gets called when the ClassificationFormatMap is changed to update the adornment
/// </summary>
public static void UpdateColor(TextFormattingRunProperties format, UIElement adornment)
{
var border = (Border)adornment;
border.BorderBrush = format.BackgroundBrush;
var stackPanel = (StackPanel)border.Child;
foreach (var child in stackPanel.Children)
{
if (child is TextBlock block)
{
block.Foreground = format.ForegroundBrush;
}
}
}
/// <summary>
/// We do not need to set a default color so this remains unimplemented
/// </summary>
protected override Color? GetColor(IWpfTextView view, IEditorFormatMap editorFormatMap)
{
throw new NotImplementedException();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Adornments;
using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.InlineDiagnostics
{
internal class InlineDiagnosticsTag : GraphicsTag, IEndOfLineAdornmentTag
{
public const string TagID = "inline diagnostics - ";
public readonly string ErrorType;
public readonly InlineDiagnosticsLocations Location;
private readonly DiagnosticData _diagnostic;
private readonly INavigateToLinkService _navigateToLinkService;
private readonly IEditorFormatMap _editorFormatMap;
private readonly IClassificationFormatMap _classificationFormatMap;
private readonly IClassificationTypeRegistryService _classificationTypeRegistryService;
private readonly IClassificationType? _classificationType;
public string Type => "Inline Diagnostics";
public double HorizontalOffset => double.NaN;
public double VerticalOffset => double.NaN;
public double Width => double.NaN;
public double Height => double.NaN;
public InlineDiagnosticsTag(string errorType, DiagnosticData diagnostic, IEditorFormatMap editorFormatMap,
IClassificationFormatMapService classificationFormatMapService, IClassificationTypeRegistryService classificationTypeRegistryService,
InlineDiagnosticsLocations location, INavigateToLinkService navigateToLinkService)
: base(editorFormatMap)
{
ErrorType = errorType;
_diagnostic = diagnostic;
Location = location;
_navigateToLinkService = navigateToLinkService;
_editorFormatMap = editorFormatMap;
_classificationFormatMap = classificationFormatMapService.GetClassificationFormatMap("text");
_classificationTypeRegistryService = classificationTypeRegistryService;
_classificationType = _classificationTypeRegistryService.GetClassificationType("url");
}
/// <summary>
/// Creates a GraphicsResult object which is the error block based on the geometry and formatting set for the item.
/// </summary>
public override GraphicsResult GetGraphics(IWpfTextView view, Geometry bounds, TextFormattingRunProperties format)
{
var block = new TextBlock
{
FontFamily = format.Typeface.FontFamily,
FontSize = 0.75 * format.FontRenderingEmSize,
FontStyle = FontStyles.Normal,
Foreground = format.ForegroundBrush,
Padding = new Thickness(left: 2, top: 0, right: 2, bottom: 0),
};
var idRun = GetRunForId(out var hyperlink);
if (hyperlink is null)
{
block.Inlines.Add(idRun);
}
else
{
// Match the hyperlink color to what the classification is set to by the user
var linkColor = _classificationFormatMap.GetTextProperties(_classificationType);
hyperlink.Foreground = linkColor.ForegroundBrush;
block.Inlines.Add(hyperlink);
hyperlink.RequestNavigate += HandleRequestNavigate;
}
block.Inlines.Add(": " + _diagnostic.Message);
var lineHeight = Math.Floor(format.Typeface.FontFamily.LineSpacing * block.FontSize);
var image = new CrispImage
{
Moniker = GetMoniker(),
MaxHeight = lineHeight,
Margin = new Thickness(1, 0, 5, 0)
};
var border = new Border
{
BorderBrush = format.BackgroundBrush,
BorderThickness = new Thickness(1),
Background = Brushes.Transparent,
Child = new StackPanel
{
Height = lineHeight,
Orientation = Orientation.Horizontal,
Children = { image, block }
},
CornerRadius = new CornerRadius(2),
// Highlighting lines are 2px buffer. So shift us up by one from the bottom so we feel centered between them.
Margin = new Thickness(10, top: 0, right: 0, bottom: 1),
Padding = new Thickness(1)
};
// This is used as a workaround to the moniker issues in blue theme
var editorBackground = (Color)_editorFormatMap.GetProperties("TextView Background")["BackgroundColor"];
ImageThemingUtilities.SetImageBackgroundColor(border, editorBackground);
border.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
view.ViewportWidthChanged += ViewportWidthChangedHandler;
view.LayoutChanged += View_LayoutChanged;
return new GraphicsResult(border, dispose:
() =>
{
if (hyperlink is not null)
{
hyperlink.RequestNavigate -= HandleRequestNavigate;
}
view.ViewportWidthChanged -= ViewportWidthChangedHandler;
view.LayoutChanged -= View_LayoutChanged;
});
// The tag listens to the width changing to allow the diagnostic UI to move with
// the window as it gets moved.
// The InlineDiagnosticsAdornmentManager listens to the viewport width
// changing to deal with diagnostics intersecting with the text in the editor.
void ViewportWidthChangedHandler(object s, EventArgs e)
{
if (Location is InlineDiagnosticsLocations.PlacedAtEndOfEditor)
{
Canvas.SetLeft(border, view.ViewportRight - border.DesiredSize.Width);
}
}
void View_LayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
if (Location is InlineDiagnosticsLocations.PlacedAtEndOfEditor)
{
Canvas.SetLeft(border, view.ViewportRight - border.DesiredSize.Width);
}
}
void HandleRequestNavigate(object sender, RoutedEventArgs e)
{
var uri = hyperlink.NavigateUri;
_ = _navigateToLinkService.TryNavigateToLinkAsync(uri, CancellationToken.None);
e.Handled = true;
}
Run GetRunForId(out Hyperlink? link)
{
var id = new Run(_diagnostic.Id);
link = null;
if (!string.IsNullOrEmpty(_diagnostic.HelpLink))
{
link = new Hyperlink(id)
{
NavigateUri = new Uri(_diagnostic.HelpLink),
};
}
return id;
}
}
private ImageMoniker GetMoniker()
=> _diagnostic.Severity switch
{
DiagnosticSeverity.Warning => KnownMonikers.StatusWarning,
_ => KnownMonikers.StatusError,
};
public static string GetClassificationId(string error)
=> error switch
{
EditAndContinueErrorTypeDefinition.Name => "inline diagnostics - Edit and Continue",
PredefinedErrorTypeNames.SyntaxError => "inline diagnostics - syntax error",
PredefinedErrorTypeNames.Warning => "inline diagnostics - compiler warning",
_ => throw ExceptionUtilities.UnexpectedValue(error)
};
/// <summary>
/// Gets called when the ClassificationFormatMap is changed to update the adornment
/// </summary>
public static void UpdateColor(TextFormattingRunProperties format, UIElement adornment)
{
var border = (Border)adornment;
border.BorderBrush = format.BackgroundBrush;
var stackPanel = (StackPanel)border.Child;
foreach (var child in stackPanel.Children)
{
if (child is TextBlock block)
{
block.Foreground = format.ForegroundBrush;
}
}
}
/// <summary>
/// We do not need to set a default color so this remains unimplemented
/// </summary>
protected override Color? GetColor(IWpfTextView view, IEditorFormatMap editorFormatMap)
{
throw new NotImplementedException();
}
}
}
| 1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/ExplicitInterfaceMemberCompletionProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 ExplicitInterfaceMemberCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(ExplicitInterfaceMemberCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitInterfaceMember_01()
{
var markup = @"
interface IGoo
{
void Goo();
void Goo(int x);
int Prop { get; }
int Generic<K, V>(K key, V value);
string this[int i] { get; }
void With_Underscore();
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "(int x)");
await VerifyItemExistsAsync(markup, "Prop");
await VerifyItemExistsAsync(markup, "Generic", displayTextSuffix: "<K, V>(K key, V value)");
await VerifyItemExistsAsync(markup, "this", displayTextSuffix: "[int i]");
await VerifyItemExistsAsync(markup, "With_Underscore", displayTextSuffix: "()");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitInterfaceMember_02()
{
var markup = @"
interface IGoo
{
void Goo();
void Goo(int x);
int Prop { get; }
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "(int x)");
await VerifyItemExistsAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitInterfaceMember_03()
{
var markup = @"
interface IGoo
{
virtual void Goo() {}
virtual void Goo(int x) {}
virtual int Prop { get => 0; }
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "(int x)");
await VerifyItemExistsAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitInterfaceMember_04()
{
var markup = @"
interface IGoo
{
virtual void Goo() {}
virtual void Goo(int x) {}
virtual int Prop { get => 0; }
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "(int x)");
await VerifyItemExistsAsync(markup, "Prop");
}
[WorkItem(709988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709988")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitOnNotParen()
{
var markup = @"
interface IGoo
{
void Goo();
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
void Goo();
}
class Bar : IGoo
{
void IGoo.Goo()
}";
await VerifyProviderCommitAsync(markup, "Goo()", expected, null);
}
[WorkItem(709988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709988")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitOnParen()
{
var markup = @"
interface IGoo
{
void Goo();
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
void Goo();
}
class Bar : IGoo
{
void IGoo.Goo(
}";
await VerifyProviderCommitAsync(markup, "Goo()", expected, '(');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(19947, "https://github.com/dotnet/roslyn/issues/19947")]
public async Task ExplicitInterfaceMemberCompletionContainsOnlyValidValues()
{
var markup = @"
interface I1
{
void Goo();
}
interface I2 : I1
{
void Goo2();
int Prop { get; }
}
class Bar : I2
{
void I2.$$
}";
await VerifyItemIsAbsentAsync(markup, "Equals(object obj)");
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "GetHashCode()");
await VerifyItemIsAbsentAsync(markup, "GetType()");
await VerifyItemIsAbsentAsync(markup, "ToString()");
await VerifyItemExistsAsync(markup, "Goo2", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(26595, "https://github.com/dotnet/roslyn/issues/26595")]
public async Task ExplicitInterfaceMemberCompletionDoesNotContainAccessors()
{
var markup = @"
interface I1
{
void Foo();
int Prop { get; }
event EventHandler TestEvent;
}
class Bar : I1
{
void I1.$$
}";
await VerifyItemIsAbsentAsync(markup, "Prop.get");
await VerifyItemIsAbsentAsync(markup, "TestEvent.add");
await VerifyItemIsAbsentAsync(markup, "TestEvent.remove");
await VerifyItemExistsAsync(markup, "Foo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Prop");
await VerifyItemExistsAsync(markup, "TestEvent");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotStaticMember_01()
{
var markup = @"
interface IGoo
{
static void Goo() {}
static int Prop { get => 0; }
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotStaticMember_02()
{
var markup = @"
interface IGoo
{
static void Goo() {}
static int Prop { get => 0; }
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotSealedMember_01()
{
var markup = @"
interface IGoo
{
sealed void Goo() {}
sealed int Prop { get => 0; }
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotSealedMember_02()
{
var markup = @"
interface IGoo
{
sealed void Goo() {}
sealed int Prop { get => 0; }
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotNestedType_01()
{
var markup = @"
interface IGoo
{
public abstract class Goo
{
}
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotNestedType_02()
{
var markup = @"
interface IGoo
{
public abstract class Goo
{
}
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(34456, "https://github.com/dotnet/roslyn/issues/34456")]
public async Task NotInaccessibleMember_01()
{
var markup =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<ProjectReference>Assembly2</ProjectReference>
<Document FilePath=""Test1.cs"">
<![CDATA[
class Bar : IGoo
{
void IGoo.$$
}
]]>
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" LanguageVersion=""Preview"">
<Document FilePath=""Test2.cs"">
public interface IGoo
{
internal void Goo1() {}
internal int Prop1 { get => 0; }
protected void Goo2() {}
protected int Prop2 { get => 0; }
}
</Document>
</Project>
</Workspace>";
await VerifyItemIsAbsentAsync(markup, "Goo1", displayTextSuffix: "()");
await VerifyItemIsAbsentAsync(markup, "Prop1");
await VerifyItemExistsAsync(markup, "Goo2", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Prop2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(34456, "https://github.com/dotnet/roslyn/issues/34456")]
public async Task NotInaccessibleMember_02()
{
var markup =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<ProjectReference>Assembly2</ProjectReference>
<Document FilePath=""Test1.cs"">
<![CDATA[
interface IBar : IGoo
{
void IGoo.$$
}
]]>
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" LanguageVersion=""Preview"">
<Document FilePath=""Test2.cs"">
public interface IGoo
{
internal void Goo1() {}
internal int Prop1 { get => 0; }
protected void Goo2() {}
protected int Prop2 { get => 0; }
}
</Document>
</Project>
</Workspace>";
await VerifyItemIsAbsentAsync(markup, "Goo1", displayTextSuffix: "()");
await VerifyItemIsAbsentAsync(markup, "Prop1");
await VerifyItemExistsAsync(markup, "Goo2", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Prop2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Generic_Tab()
{
var markup = @"
interface IGoo
{
int Generic<K, V>(K key, V value);
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int Generic<K, V>(K key, V value);
}
class Bar : IGoo
{
void IGoo.Generic<K, V>(K key, V value)
}";
await VerifyProviderCommitAsync(markup, "Generic<K, V>(K key, V value)", expected, '\t');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Generic_OpenBrace()
{
var markup = @"
interface IGoo
{
int Generic<K, V>(K key, V value);
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int Generic<K, V>(K key, V value);
}
class Bar : IGoo
{
void IGoo.Generic<
}";
await VerifyProviderCommitAsync(markup, "Generic<K, V>(K key, V value)", expected, '<');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Method_Tab()
{
var markup = @"
interface IGoo
{
int Generic(K key, V value);
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int Generic(K key, V value);
}
class Bar : IGoo
{
void IGoo.Generic(K key, V value)
}";
await VerifyProviderCommitAsync(markup, "Generic(K key, V value)", expected, '\t');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Method_OpenBrace()
{
var markup = @"
interface IGoo
{
int Generic(K key, V value);
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int Generic(K key, V value);
}
class Bar : IGoo
{
void IGoo.Generic(
}";
await VerifyProviderCommitAsync(markup, "Generic(K key, V value)", expected, '(');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Indexer_Tab()
{
var markup = @"
interface IGoo
{
int this[K key, V value] { get; }
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int this[K key, V value] { get; }
}
class Bar : IGoo
{
void IGoo.this[K key, V value]
}";
await VerifyProviderCommitAsync(markup, "this[K key, V value]", expected, '\t');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Indexer_OpenBrace()
{
var markup = @"
interface IGoo
{
int this[K key, V value] { get; }
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int this[K key, V value] { get; }
}
class Bar : IGoo
{
void IGoo.this[
}";
await VerifyProviderCommitAsync(markup, "this[K key, V value]", 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.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 ExplicitInterfaceMemberCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(ExplicitInterfaceMemberCompletionProvider);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitInterfaceMember_01()
{
var markup = @"
interface IGoo
{
void Goo();
void Goo(int x);
int Prop { get; }
int Generic<K, V>(K key, V value);
string this[int i] { get; }
void With_Underscore();
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "(int x)");
await VerifyItemExistsAsync(markup, "Prop");
await VerifyItemExistsAsync(markup, "Generic", displayTextSuffix: "<K, V>(K key, V value)");
await VerifyItemExistsAsync(markup, "this", displayTextSuffix: "[int i]");
await VerifyItemExistsAsync(markup, "With_Underscore", displayTextSuffix: "()");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitInterfaceMember_02()
{
var markup = @"
interface IGoo
{
void Goo();
void Goo(int x);
int Prop { get; }
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "(int x)");
await VerifyItemExistsAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitInterfaceMember_03()
{
var markup = @"
interface IGoo
{
virtual void Goo() {}
virtual void Goo(int x) {}
virtual int Prop { get => 0; }
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "(int x)");
await VerifyItemExistsAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExplicitInterfaceMember_04()
{
var markup = @"
interface IGoo
{
virtual void Goo() {}
virtual void Goo(int x) {}
virtual int Prop { get => 0; }
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Goo", displayTextSuffix: "(int x)");
await VerifyItemExistsAsync(markup, "Prop");
}
[WorkItem(709988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709988")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitOnNotParen()
{
var markup = @"
interface IGoo
{
void Goo();
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
void Goo();
}
class Bar : IGoo
{
void IGoo.Goo()
}";
await VerifyProviderCommitAsync(markup, "Goo()", expected, null);
}
[WorkItem(709988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709988")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitOnParen()
{
var markup = @"
interface IGoo
{
void Goo();
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
void Goo();
}
class Bar : IGoo
{
void IGoo.Goo(
}";
await VerifyProviderCommitAsync(markup, "Goo()", expected, '(');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(19947, "https://github.com/dotnet/roslyn/issues/19947")]
public async Task ExplicitInterfaceMemberCompletionContainsOnlyValidValues()
{
var markup = @"
interface I1
{
void Goo();
}
interface I2 : I1
{
void Goo2();
int Prop { get; }
}
class Bar : I2
{
void I2.$$
}";
await VerifyItemIsAbsentAsync(markup, "Equals(object obj)");
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "GetHashCode()");
await VerifyItemIsAbsentAsync(markup, "GetType()");
await VerifyItemIsAbsentAsync(markup, "ToString()");
await VerifyItemExistsAsync(markup, "Goo2", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(26595, "https://github.com/dotnet/roslyn/issues/26595")]
public async Task ExplicitInterfaceMemberCompletionDoesNotContainAccessors()
{
var markup = @"
interface I1
{
void Foo();
int Prop { get; }
event EventHandler TestEvent;
}
class Bar : I1
{
void I1.$$
}";
await VerifyItemIsAbsentAsync(markup, "Prop.get");
await VerifyItemIsAbsentAsync(markup, "TestEvent.add");
await VerifyItemIsAbsentAsync(markup, "TestEvent.remove");
await VerifyItemExistsAsync(markup, "Foo", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Prop");
await VerifyItemExistsAsync(markup, "TestEvent");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotStaticMember_01()
{
var markup = @"
interface IGoo
{
static void Goo() {}
static int Prop { get => 0; }
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotStaticMember_02()
{
var markup = @"
interface IGoo
{
static void Goo() {}
static int Prop { get => 0; }
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotSealedMember_01()
{
var markup = @"
interface IGoo
{
sealed void Goo() {}
sealed int Prop { get => 0; }
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotSealedMember_02()
{
var markup = @"
interface IGoo
{
sealed void Goo() {}
sealed int Prop { get => 0; }
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo()");
await VerifyItemIsAbsentAsync(markup, "Prop");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotNestedType_01()
{
var markup = @"
interface IGoo
{
public abstract class Goo
{
}
}
class Bar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotNestedType_02()
{
var markup = @"
interface IGoo
{
public abstract class Goo
{
}
}
interface IBar : IGoo
{
void IGoo.$$
}";
await VerifyItemIsAbsentAsync(markup, "Goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(34456, "https://github.com/dotnet/roslyn/issues/34456")]
public async Task NotInaccessibleMember_01()
{
var markup =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<ProjectReference>Assembly2</ProjectReference>
<Document FilePath=""Test1.cs"">
<![CDATA[
class Bar : IGoo
{
void IGoo.$$
}
]]>
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" LanguageVersion=""Preview"">
<Document FilePath=""Test2.cs"">
public interface IGoo
{
internal void Goo1() {}
internal int Prop1 { get => 0; }
protected void Goo2() {}
protected int Prop2 { get => 0; }
}
</Document>
</Project>
</Workspace>";
await VerifyItemIsAbsentAsync(markup, "Goo1", displayTextSuffix: "()");
await VerifyItemIsAbsentAsync(markup, "Prop1");
await VerifyItemExistsAsync(markup, "Goo2", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Prop2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(34456, "https://github.com/dotnet/roslyn/issues/34456")]
public async Task NotInaccessibleMember_02()
{
var markup =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<ProjectReference>Assembly2</ProjectReference>
<Document FilePath=""Test1.cs"">
<![CDATA[
interface IBar : IGoo
{
void IGoo.$$
}
]]>
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"" LanguageVersion=""Preview"">
<Document FilePath=""Test2.cs"">
public interface IGoo
{
internal void Goo1() {}
internal int Prop1 { get => 0; }
protected void Goo2() {}
protected int Prop2 { get => 0; }
}
</Document>
</Project>
</Workspace>";
await VerifyItemIsAbsentAsync(markup, "Goo1", displayTextSuffix: "()");
await VerifyItemIsAbsentAsync(markup, "Prop1");
await VerifyItemExistsAsync(markup, "Goo2", displayTextSuffix: "()");
await VerifyItemExistsAsync(markup, "Prop2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Generic_Tab()
{
var markup = @"
interface IGoo
{
int Generic<K, V>(K key, V value);
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int Generic<K, V>(K key, V value);
}
class Bar : IGoo
{
void IGoo.Generic<K, V>(K key, V value)
}";
await VerifyProviderCommitAsync(markup, "Generic<K, V>(K key, V value)", expected, '\t');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Generic_OpenBrace()
{
var markup = @"
interface IGoo
{
int Generic<K, V>(K key, V value);
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int Generic<K, V>(K key, V value);
}
class Bar : IGoo
{
void IGoo.Generic<
}";
await VerifyProviderCommitAsync(markup, "Generic<K, V>(K key, V value)", expected, '<');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Method_Tab()
{
var markup = @"
interface IGoo
{
int Generic(K key, V value);
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int Generic(K key, V value);
}
class Bar : IGoo
{
void IGoo.Generic(K key, V value)
}";
await VerifyProviderCommitAsync(markup, "Generic(K key, V value)", expected, '\t');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Method_OpenBrace()
{
var markup = @"
interface IGoo
{
int Generic(K key, V value);
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int Generic(K key, V value);
}
class Bar : IGoo
{
void IGoo.Generic(
}";
await VerifyProviderCommitAsync(markup, "Generic(K key, V value)", expected, '(');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Indexer_Tab()
{
var markup = @"
interface IGoo
{
int this[K key, V value] { get; }
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int this[K key, V value] { get; }
}
class Bar : IGoo
{
void IGoo.this[K key, V value]
}";
await VerifyProviderCommitAsync(markup, "this[K key, V value]", expected, '\t');
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VerifySignatureCommit_Indexer_OpenBrace()
{
var markup = @"
interface IGoo
{
int this[K key, V value] { get; }
}
class Bar : IGoo
{
void IGoo.$$
}";
var expected = @"
interface IGoo
{
int this[K key, V value] { get; }
}
class Bar : IGoo
{
void IGoo.this[
}";
await VerifyProviderCommitAsync(markup, "this[K key, V value]", expected, '[');
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenStructsAndEnum.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenStructsAndEnum : EmitMetadataTestBase
{
#region "Struct"
[Fact]
public void ValInstanceField()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public static Boo Inst;
}
public static void Main()
{
Boo val = Boo.Inst;
int i = val.I1;
System.Console.Write(i);
val.I1 = 42;
System.Console.Write(val.I1);
val.I1 = 7;
System.Console.Write(val.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0427");
compilation.VerifyIL("D.Main",
@"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (D.Boo V_0) //val
IL_0000: ldsfld ""D.Boo D.Boo.Inst""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldfld ""int D.Boo.I1""
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldloca.s V_0
IL_0013: ldc.i4.s 42
IL_0015: stfld ""int D.Boo.I1""
IL_001a: ldloc.0
IL_001b: ldfld ""int D.Boo.I1""
IL_0020: call ""void System.Console.Write(int)""
IL_0025: ldloca.s V_0
IL_0027: ldc.i4.7
IL_0028: stfld ""int D.Boo.I1""
IL_002d: ldloc.0
IL_002e: ldfld ""int D.Boo.I1""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[Fact]
public void ValStaticField()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public static Boo Inst;
}
public static void Main()
{
Boo val = Boo.Inst;
System.Console.Write(Boo.Inst.I1);
val.I1 = 42;
Boo.Inst = val;
System.Console.Write(Boo.Inst.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "042");
compilation.VerifyIL("D.Main",
@"{
// Code size 52 (0x34)
.maxstack 2
.locals init (D.Boo V_0) //val
IL_0000: ldsfld ""D.Boo D.Boo.Inst""
IL_0005: stloc.0
IL_0006: ldsflda ""D.Boo D.Boo.Inst""
IL_000b: ldfld ""int D.Boo.I1""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ldloca.s V_0
IL_0017: ldc.i4.s 42
IL_0019: stfld ""int D.Boo.I1""
IL_001e: ldloc.0
IL_001f: stsfld ""D.Boo D.Boo.Inst""
IL_0024: ldsflda ""D.Boo D.Boo.Inst""
IL_0029: ldfld ""int D.Boo.I1""
IL_002e: call ""void System.Console.Write(int)""
IL_0033: ret
}
");
}
[Fact]
public void StructCtor()
{
string source = @"
public class D
{
public static void Main()
{
System.Decimal val = 0m;
System.Console.Write(val);
val = new System.Decimal(7);
System.Console.Write(val);
val = new System.Decimal();
System.Console.Write(val);
val = ((decimal)int.MaxValue + 1) * 4; // use the ctor that takes a long
System.Console.Write(val);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0708589934592");
// expect just two locals (temp is reused)
compilation.VerifyIL("D.Main",
@"
{
// Code size 51 (0x33)
.maxstack 1
IL_0000: ldsfld ""decimal decimal.Zero""
IL_0005: call ""void System.Console.Write(decimal)""
IL_000a: ldc.i4.7
IL_000b: newobj ""decimal..ctor(int)""
IL_0010: call ""void System.Console.Write(decimal)""
IL_0015: ldsfld ""decimal decimal.Zero""
IL_001a: call ""void System.Console.Write(decimal)""
IL_001f: ldc.i8 0x200000000
IL_0028: newobj ""decimal..ctor(long)""
IL_002d: call ""void System.Console.Write(decimal)""
IL_0032: ret
}
");
}
[Fact]
public void AddressUnbox()
{
string source = @"
using System;
class Program
{
public struct S1
{
public int x;
public void Goo()
{
x = 123;
}
}
public static S1 goo()
{
return new S1();
}
static void Main()
{
goo().ToString();
Console.Write(goo().x);
}
}";
var compilation = CompileAndVerify(source, expectedOutput: @"0");
compilation.VerifyIL("Program.Main",
@"{
// Code size 36 (0x24)
.maxstack 1
.locals init (Program.S1 V_0)
IL_0000: call ""Program.S1 Program.goo()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: constrained. ""Program.S1""
IL_000e: callvirt ""string object.ToString()""
IL_0013: pop
IL_0014: call ""Program.S1 Program.goo()""
IL_0019: ldfld ""int Program.S1.x""
IL_001e: call ""void System.Console.Write(int)""
IL_0023: ret
}
");
}
[Fact]
public void EqualsHashcode()
{
string source = @"
using System;
struct S1
{
public int field;
public override bool Equals(object obj)
{
return obj is S1 && field == ((S1)obj).field;
}
public override int GetHashCode()
{
return field;
}
public static bool operator ==(S1 value1, S1 value2)
{
return value1.field == value2.field;
}
public static bool operator !=(S1 value1, S1 value2)
{
return value1.field != value2.field;
}
}
class Program
{
static void Main(string[] args)
{
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"");
compilation.VerifyIL("S1.Equals(object)",
@"
{
// Code size 30 (0x1e)
.maxstack 2
IL_0000: ldarg.1
IL_0001: isinst ""S1""
IL_0006: brfalse.s IL_001c
IL_0008: ldarg.0
IL_0009: ldfld ""int S1.field""
IL_000e: ldarg.1
IL_000f: unbox ""S1""
IL_0014: ldfld ""int S1.field""
IL_0019: ceq
IL_001b: ret
IL_001c: ldc.i4.0
IL_001d: ret
}
").VerifyIL("S1.GetHashCode()",
@"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int S1.field""
IL_0006: ret
}
").VerifyIL("bool S1.op_Equality(S1, S1)",
@"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int S1.field""
IL_0006: ldarg.1
IL_0007: ldfld ""int S1.field""
IL_000c: ceq
IL_000e: ret
}
").VerifyIL("bool S1.op_Inequality(S1, S1)",
@"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int S1.field""
IL_0006: ldarg.1
IL_0007: ldfld ""int S1.field""
IL_000c: ceq
IL_000e: ldc.i4.0
IL_000f: ceq
IL_0011: ret
}
");
}
[Fact]
public void EmitObjectGetTypeCallOnStruct()
{
string source = @"
using System;
class Program
{
public struct S1
{
}
static void Main()
{
Console.Write((new S1()).GetType());
}
}";
var compilation = CompileAndVerify(source, expectedOutput: @"Program+S1");
compilation.VerifyIL("Program.Main",
@"{
// Code size 25 (0x19)
.maxstack 1
.locals init (Program.S1 V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""Program.S1""
IL_0008: ldloc.0
IL_0009: box ""Program.S1""
IL_000e: call ""System.Type object.GetType()""
IL_0013: call ""void System.Console.Write(object)""
IL_0018: ret
}
");
}
[Fact]
public void EmitInterfaceMethodOnStruct()
{
string source = @"
using System;
class Program
{
interface I
{
void M();
}
struct S : I
{
public void M()
{
Console.WriteLine(""S::M"");
}
}
static void Main(string[] args)
{
S s = new S();
s.M();
((I)s).M();
}
}";
var compilation = CompileAndVerify(source, expectedOutput: @"S::M
S::M");
compilation.VerifyIL("Program.Main",
@"{
// Code size 27 (0x1b)
.maxstack 1
.locals init (Program.S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""Program.S""
IL_0008: ldloca.s V_0
IL_000a: call ""void Program.S.M()""
IL_000f: ldloc.0
IL_0010: box ""Program.S""
IL_0015: callvirt ""void Program.I.M()""
IL_001a: ret
}
");
}
[Fact]
public void ValueTypeWithGeneric()
{
string source = @"
namespace NS
{
using System;
using N2;
namespace N2
{
public interface IGoo<T>
{
void M(T t);
}
struct S<T, V> : IGoo<T>
{
public S(V v)
{
field = v;
}
public V field;
public void M(T t) { Console.WriteLine(t); }
}
}
public class Test
{
static S<N2, char>[] ary;
class N1 { }
class N2 : N1 { }
static void Main()
{
IGoo<string> goo = new S<string, byte>(255);
goo.M(""Abc"");
Console.WriteLine(((S<string, byte>)goo).field);
ary = new S<N2, char>[3];
ary[0] = ary[1] = ary[2] = new S<N2, char>('q');
Console.WriteLine(ary[1].field);
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
Abc
255
q");
compilation.VerifyIL("NS.Test.Main",
@"{
// Code size 120 (0x78)
.maxstack 8
.locals init (NS.N2.S<NS.Test.N2, char> V_0)
IL_0000: ldc.i4 0xff
IL_0005: newobj ""NS.N2.S<string, byte>..ctor(byte)""
IL_000a: box ""NS.N2.S<string, byte>""
IL_000f: dup
IL_0010: ldstr ""Abc""
IL_0015: callvirt ""void NS.N2.IGoo<string>.M(string)""
IL_001a: unbox ""NS.N2.S<string, byte>""
IL_001f: ldfld ""byte NS.N2.S<string, byte>.field""
IL_0024: call ""void System.Console.WriteLine(int)""
IL_0029: ldc.i4.3
IL_002a: newarr ""NS.N2.S<NS.Test.N2, char>""
IL_002f: stsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_0034: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_0039: ldc.i4.0
IL_003a: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_003f: ldc.i4.1
IL_0040: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_0045: ldc.i4.2
IL_0046: ldc.i4.s 113
IL_0048: newobj ""NS.N2.S<NS.Test.N2, char>..ctor(char)""
IL_004d: dup
IL_004e: stloc.0
IL_004f: stelem ""NS.N2.S<NS.Test.N2, char>""
IL_0054: ldloc.0
IL_0055: dup
IL_0056: stloc.0
IL_0057: stelem ""NS.N2.S<NS.Test.N2, char>""
IL_005c: ldloc.0
IL_005d: stelem ""NS.N2.S<NS.Test.N2, char>""
IL_0062: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_0067: ldc.i4.1
IL_0068: ldelema ""NS.N2.S<NS.Test.N2, char>""
IL_006d: ldfld ""char NS.N2.S<NS.Test.N2, char>.field""
IL_0072: call ""void System.Console.WriteLine(char)""
IL_0077: ret
}
");
}
[WorkItem(540954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540954")]
[Fact]
public void StructInit()
{
var text =
@"
struct Struct
{
public static void Main()
{
Struct s = new Struct();
}
}
";
string expectedIL = @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Struct V_0) //s
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""Struct""
IL_0009: ret
}
";
CompileAndVerify(text, options: TestOptions.DebugExe).VerifyIL("Struct.Main()", expectedIL);
}
[WorkItem(541845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541845")]
[Fact]
public void ConstructEnum()
{
var text =
@"
using System;
class A
{
enum E1
{
AA
}
static void Main()
{
var v = new DayOfWeek();
Console.Write(v.ToString());
var e = new E1();
Console.WriteLine(e.ToString());
}
}
";
string expectedIL = @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (System.DayOfWeek V_0, //v
A.E1 V_1) //e
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: constrained. ""System.DayOfWeek""
IL_000a: callvirt ""string object.ToString()""
IL_000f: call ""void System.Console.Write(string)""
IL_0014: ldc.i4.0
IL_0015: stloc.1
IL_0016: ldloca.s V_1
IL_0018: constrained. ""A.E1""
IL_001e: callvirt ""string object.ToString()""
IL_0023: call ""void System.Console.WriteLine(string)""
IL_0028: ret
}";
CompileAndVerify(text, expectedOutput: "SundayAA").VerifyIL("A.Main()", expectedIL);
}
[WorkItem(541599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541599")]
[Fact]
public void TestStructWithStaticField01()
{
var source = @"
using System;
public struct S
{
public static int _verify = 123;
static void Main()
{
Console.Write(_verify);
}
}
";
CompileAndVerify(source, expectedOutput: @"123");
}
[Fact, WorkItem(543088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543088")]
public void UseStructLocal()
{
var text = @"
using System;
struct GetProperty
{
int i;
GetProperty(int x)
{
i = x;
}
static void Main()
{
GetProperty t = new GetProperty(123);
Console.Write(t.i);
}
}
";
CompileAndVerify(text, expectedOutput: "123");
}
[Fact]
public void InplaceInit001()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
v1 = default(Boo);
DummyUse(v1);
Boo v2 = default(Boo);
DummyUse(v2);
rArg = default(Boo);
DummyUse(rArg);
vArg = default(Boo);
DummyUse(rArg);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 73 (0x49)
.maxstack 1
.locals init (D.Boo V_0)
IL_0000: ldsflda ""D.Boo D.v1""
IL_0005: initobj ""D.Boo""
IL_000b: ldsfld ""D.Boo D.v1""
IL_0010: call ""void D.DummyUse(D.Boo)""
IL_0015: ldloca.s V_0
IL_0017: initobj ""D.Boo""
IL_001d: ldloc.0
IL_001e: call ""void D.DummyUse(D.Boo)""
IL_0023: ldarg.0
IL_0024: initobj ""D.Boo""
IL_002a: ldarg.0
IL_002b: ldobj ""D.Boo""
IL_0030: call ""void D.DummyUse(D.Boo)""
IL_0035: ldarga.s V_1
IL_0037: initobj ""D.Boo""
IL_003d: ldarg.0
IL_003e: ldobj ""D.Boo""
IL_0043: call ""void D.DummyUse(D.Boo)""
IL_0048: ret
}
");
}
[Fact]
public void InplaceInit002()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
try
{
v1 = default(Boo);
DummyUse(v1);
Boo v2 = default(Boo);
DummyUse(v2);
rArg = default(Boo);
DummyUse(rArg);
vArg = default(Boo);
DummyUse(rArg);
}
catch (System.Exception)
{
rArg = default(Boo);
DummyUse(rArg);
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 96 (0x60)
.maxstack 1
.locals init (D.Boo V_0)
.try
{
IL_0000: ldsflda ""D.Boo D.v1""
IL_0005: initobj ""D.Boo""
IL_000b: ldsfld ""D.Boo D.v1""
IL_0010: call ""void D.DummyUse(D.Boo)""
IL_0015: ldloca.s V_0
IL_0017: initobj ""D.Boo""
IL_001d: ldloc.0
IL_001e: call ""void D.DummyUse(D.Boo)""
IL_0023: ldarg.0
IL_0024: initobj ""D.Boo""
IL_002a: ldarg.0
IL_002b: ldobj ""D.Boo""
IL_0030: call ""void D.DummyUse(D.Boo)""
IL_0035: ldarga.s V_1
IL_0037: initobj ""D.Boo""
IL_003d: ldarg.0
IL_003e: ldobj ""D.Boo""
IL_0043: call ""void D.DummyUse(D.Boo)""
IL_0048: leave.s IL_005f
}
catch System.Exception
{
IL_004a: pop
IL_004b: ldarg.0
IL_004c: initobj ""D.Boo""
IL_0052: ldarg.0
IL_0053: ldobj ""D.Boo""
IL_0058: call ""void D.DummyUse(D.Boo)""
IL_005d: leave.s IL_005f
}
IL_005f: ret
}
");
}
[Fact]
public void InplaceCtor001()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(int i1)
{
this.I1 = i1;
}
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
//try
//{
v1 = new Boo(42);
DummyUse(v1);
Boo v2 = new Boo(42);
DummyUse(v2);
rArg = new Boo(42);
DummyUse(rArg);
vArg = new Boo(42);
DummyUse(rArg);
//}
//catch (System.Exception)
//
// rArg = new Boo(42);
// DummyUse(rArg);
//}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 79 (0x4f)
.maxstack 2
IL_0000: ldc.i4.s 42
IL_0002: newobj ""D.Boo..ctor(int)""
IL_0007: stsfld ""D.Boo D.v1""
IL_000c: ldsfld ""D.Boo D.v1""
IL_0011: call ""void D.DummyUse(D.Boo)""
IL_0016: ldc.i4.s 42
IL_0018: newobj ""D.Boo..ctor(int)""
IL_001d: call ""void D.DummyUse(D.Boo)""
IL_0022: ldarg.0
IL_0023: ldc.i4.s 42
IL_0025: newobj ""D.Boo..ctor(int)""
IL_002a: stobj ""D.Boo""
IL_002f: ldarg.0
IL_0030: ldobj ""D.Boo""
IL_0035: call ""void D.DummyUse(D.Boo)""
IL_003a: ldarga.s V_1
IL_003c: ldc.i4.s 42
IL_003e: call ""D.Boo..ctor(int)""
IL_0043: ldarg.0
IL_0044: ldobj ""D.Boo""
IL_0049: call ""void D.DummyUse(D.Boo)""
IL_004e: ret
}
");
}
[Fact]
public void InplaceCtor002()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(int i1)
{
this.I1 = i1;
}
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
Boo v3;
try{
Boo v3a;
try
{
v1 = new Boo(42);
DummyUse(v1);
Boo v2 = new Boo(43);
DummyUse(v2);
v3 = new Boo(44);
v3.ToString();
// should be a call, since v4 is defined in the same try scope
Boo v4 = new Boo(45);
v4.ToString();
rArg = new Boo(46);
DummyUse(rArg);
vArg = new Boo(47);
DummyUse(rArg);
}
catch (System.Exception)
{
v3 = new Boo(44);
v3.ToString();
// should be a call, since v3a is defined in the same try scope
v3a = new Boo(44);
v3a.ToString();
// should be a call, since v4 is defined in the same try scope
Boo v4 = new Boo(45);
v4.ToString();
rArg = new Boo(48);
DummyUse(rArg);
}
}
finally
{
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 222 (0xde)
.maxstack 2
.locals init (D.Boo V_0, //v3
D.Boo V_1, //v3a
D.Boo V_2, //v4
D.Boo V_3) //v4
.try
{
IL_0000: ldc.i4.s 42
IL_0002: newobj ""D.Boo..ctor(int)""
IL_0007: stsfld ""D.Boo D.v1""
IL_000c: ldsfld ""D.Boo D.v1""
IL_0011: call ""void D.DummyUse(D.Boo)""
IL_0016: ldc.i4.s 43
IL_0018: newobj ""D.Boo..ctor(int)""
IL_001d: call ""void D.DummyUse(D.Boo)""
IL_0022: ldc.i4.s 44
IL_0024: newobj ""D.Boo..ctor(int)""
IL_0029: stloc.0
IL_002a: ldloca.s V_0
IL_002c: constrained. ""D.Boo""
IL_0032: callvirt ""string object.ToString()""
IL_0037: pop
IL_0038: ldloca.s V_2
IL_003a: ldc.i4.s 45
IL_003c: call ""D.Boo..ctor(int)""
IL_0041: ldloca.s V_2
IL_0043: constrained. ""D.Boo""
IL_0049: callvirt ""string object.ToString()""
IL_004e: pop
IL_004f: ldarg.0
IL_0050: ldc.i4.s 46
IL_0052: newobj ""D.Boo..ctor(int)""
IL_0057: stobj ""D.Boo""
IL_005c: ldarg.0
IL_005d: ldobj ""D.Boo""
IL_0062: call ""void D.DummyUse(D.Boo)""
IL_0067: ldc.i4.s 47
IL_0069: newobj ""D.Boo..ctor(int)""
IL_006e: starg.s V_1
IL_0070: ldarg.0
IL_0071: ldobj ""D.Boo""
IL_0076: call ""void D.DummyUse(D.Boo)""
IL_007b: leave.s IL_00dd
}
catch System.Exception
{
IL_007d: pop
IL_007e: ldloca.s V_0
IL_0080: ldc.i4.s 44
IL_0082: call ""D.Boo..ctor(int)""
IL_0087: ldloca.s V_0
IL_0089: constrained. ""D.Boo""
IL_008f: callvirt ""string object.ToString()""
IL_0094: pop
IL_0095: ldloca.s V_1
IL_0097: ldc.i4.s 44
IL_0099: call ""D.Boo..ctor(int)""
IL_009e: ldloca.s V_1
IL_00a0: constrained. ""D.Boo""
IL_00a6: callvirt ""string object.ToString()""
IL_00ab: pop
IL_00ac: ldloca.s V_3
IL_00ae: ldc.i4.s 45
IL_00b0: call ""D.Boo..ctor(int)""
IL_00b5: ldloca.s V_3
IL_00b7: constrained. ""D.Boo""
IL_00bd: callvirt ""string object.ToString()""
IL_00c2: pop
IL_00c3: ldarg.0
IL_00c4: ldc.i4.s 48
IL_00c6: newobj ""D.Boo..ctor(int)""
IL_00cb: stobj ""D.Boo""
IL_00d0: ldarg.0
IL_00d1: ldobj ""D.Boo""
IL_00d6: call ""void D.DummyUse(D.Boo)""
IL_00db: leave.s IL_00dd
}
IL_00dd: ret
}
");
}
[WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")]
[Fact]
public void InplaceCtor003()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(ref int i1)
{
this.I1 = 1;
this.I1 += i1;
}
public Boo(ref Boo b1)
{
this.I1 = 1;
this.I1 += b1.I1;
}
}
public static Boo v1;
public static void Main()
{
Boo a1 = default(Boo);
a1 = new Boo(ref a1);
System.Console.Write(a1.I1);
v1 = new Boo(ref v1);
System.Console.Write(v1.I1);
a1 = default(Boo);
v1 = default(Boo);
a1 = new Boo(ref a1.I1);
System.Console.Write(a1.I1);
v1 = new Boo(ref v1.I1);
System.Console.Write(v1.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "1111");
compilation.VerifyIL("D.Main",
@"
{
// Code size 136 (0x88)
.maxstack 1
.locals init (D.Boo V_0) //a1
IL_0000: ldloca.s V_0
IL_0002: initobj ""D.Boo""
IL_0008: ldloca.s V_0
IL_000a: newobj ""D.Boo..ctor(ref D.Boo)""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: ldfld ""int D.Boo.I1""
IL_0016: call ""void System.Console.Write(int)""
IL_001b: ldsflda ""D.Boo D.v1""
IL_0020: newobj ""D.Boo..ctor(ref D.Boo)""
IL_0025: stsfld ""D.Boo D.v1""
IL_002a: ldsflda ""D.Boo D.v1""
IL_002f: ldfld ""int D.Boo.I1""
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ldloca.s V_0
IL_003b: initobj ""D.Boo""
IL_0041: ldsflda ""D.Boo D.v1""
IL_0046: initobj ""D.Boo""
IL_004c: ldloca.s V_0
IL_004e: ldflda ""int D.Boo.I1""
IL_0053: newobj ""D.Boo..ctor(ref int)""
IL_0058: stloc.0
IL_0059: ldloc.0
IL_005a: ldfld ""int D.Boo.I1""
IL_005f: call ""void System.Console.Write(int)""
IL_0064: ldsflda ""D.Boo D.v1""
IL_0069: ldflda ""int D.Boo.I1""
IL_006e: newobj ""D.Boo..ctor(ref int)""
IL_0073: stsfld ""D.Boo D.v1""
IL_0078: ldsflda ""D.Boo D.v1""
IL_007d: ldfld ""int D.Boo.I1""
IL_0082: call ""void System.Console.Write(int)""
IL_0087: ret
}
");
}
[WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")]
[Fact]
public void InplaceCtor004()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(ref int i1)
{
this.I1 = 1;
this.I1 += i1;
}
public Boo(ref Boo b1)
{
this.I1 = 1;
this.I1 += b1.I1;
}
}
public static Boo v1;
public static void Main()
{
Boo a1 = default(Boo);
ref var r1 = ref a1;
a1 = new Boo(ref r1);
System.Console.Write(a1.I1);
ref var r2 = ref v1;
v1 = new Boo(ref r2);
System.Console.Write(v1.I1);
a1 = default(Boo);
v1 = default(Boo);
ref var r3 = ref a1.I1;
a1 = new Boo(ref r3);
System.Console.Write(a1.I1);
ref var r4 = ref v1.I1;
v1 = new Boo(ref r4);
System.Console.Write(v1.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "1111");
compilation.VerifyIL("D.Main",
@"
{
// Code size 146 (0x92)
.maxstack 1
.locals init (D.Boo V_0, //a1
D.Boo& V_1, //r1
D.Boo& V_2, //r2
int& V_3, //r3
int& V_4) //r4
IL_0000: ldloca.s V_0
IL_0002: initobj ""D.Boo""
IL_0008: ldloca.s V_0
IL_000a: stloc.1
IL_000b: ldloc.1
IL_000c: newobj ""D.Boo..ctor(ref D.Boo)""
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: ldfld ""int D.Boo.I1""
IL_0018: call ""void System.Console.Write(int)""
IL_001d: ldsflda ""D.Boo D.v1""
IL_0022: stloc.2
IL_0023: ldloc.2
IL_0024: newobj ""D.Boo..ctor(ref D.Boo)""
IL_0029: stsfld ""D.Boo D.v1""
IL_002e: ldsflda ""D.Boo D.v1""
IL_0033: ldfld ""int D.Boo.I1""
IL_0038: call ""void System.Console.Write(int)""
IL_003d: ldloca.s V_0
IL_003f: initobj ""D.Boo""
IL_0045: ldsflda ""D.Boo D.v1""
IL_004a: initobj ""D.Boo""
IL_0050: ldloca.s V_0
IL_0052: ldflda ""int D.Boo.I1""
IL_0057: stloc.3
IL_0058: ldloc.3
IL_0059: newobj ""D.Boo..ctor(ref int)""
IL_005e: stloc.0
IL_005f: ldloc.0
IL_0060: ldfld ""int D.Boo.I1""
IL_0065: call ""void System.Console.Write(int)""
IL_006a: ldsflda ""D.Boo D.v1""
IL_006f: ldflda ""int D.Boo.I1""
IL_0074: stloc.s V_4
IL_0076: ldloc.s V_4
IL_0078: newobj ""D.Boo..ctor(ref int)""
IL_007d: stsfld ""D.Boo D.v1""
IL_0082: ldsflda ""D.Boo D.v1""
IL_0087: ldfld ""int D.Boo.I1""
IL_008c: call ""void System.Console.Write(int)""
IL_0091: ret
}
");
}
[WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void InplaceCtor005()
{
string source = @"
using System;
public class D
{
public struct Boo
{
public int I1;
public Boo(int x, __arglist)
{
this.I1 = 1;
this.I1 += __refvalue(new ArgIterator(__arglist).GetNextArg(), Boo).I1;
}
}
public static Boo v1;
public static void Main()
{
Boo a1 = default(Boo);
a1 = new Boo(1, __arglist(ref a1));
System.Console.Write(a1.I1);
v1 = new Boo(1, __arglist(ref v1));
System.Console.Write(v1.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "11");
compilation.VerifyIL("D.Main",
@"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (D.Boo V_0) //a1
IL_0000: ldloca.s V_0
IL_0002: initobj ""D.Boo""
IL_0008: ldc.i4.1
IL_0009: ldloca.s V_0
IL_000b: newobj ""D.Boo..ctor(int, __arglist) with __arglist( ref D.Boo)""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldfld ""int D.Boo.I1""
IL_0017: call ""void System.Console.Write(int)""
IL_001c: ldc.i4.1
IL_001d: ldsflda ""D.Boo D.v1""
IL_0022: newobj ""D.Boo..ctor(int, __arglist) with __arglist( ref D.Boo)""
IL_0027: stsfld ""D.Boo D.v1""
IL_002c: ldsflda ""D.Boo D.v1""
IL_0031: ldfld ""int D.Boo.I1""
IL_0036: call ""void System.Console.Write(int)""
IL_003b: ret
}
");
}
[Fact]
public void InitUsed001()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(int i1)
{
this.I1 = i1;
}
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void DummyUse1(ref Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
DummyUse(v1 = default(Boo));
DummyUse(v1);
Boo v2;
DummyUse(v2 = default(Boo));
DummyUse(v2);
// TODO: no need for a temp
Boo v2a;
DummyUse(v2a = default(Boo));
DummyUse1(ref v2a);
DummyUse(rArg = default(Boo));
DummyUse(rArg);
// TODO: no need for a temp
DummyUse(vArg = default(Boo));
DummyUse(vArg);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 126 (0x7e)
.maxstack 3
.locals init (D.Boo V_0, //v2a
D.Boo V_1)
IL_0000: ldloca.s V_1
IL_0002: initobj ""D.Boo""
IL_0008: ldloc.1
IL_0009: dup
IL_000a: stsfld ""D.Boo D.v1""
IL_000f: call ""void D.DummyUse(D.Boo)""
IL_0014: ldsfld ""D.Boo D.v1""
IL_0019: call ""void D.DummyUse(D.Boo)""
IL_001e: ldloca.s V_1
IL_0020: initobj ""D.Boo""
IL_0026: ldloc.1
IL_0027: dup
IL_0028: call ""void D.DummyUse(D.Boo)""
IL_002d: call ""void D.DummyUse(D.Boo)""
IL_0032: ldloca.s V_0
IL_0034: initobj ""D.Boo""
IL_003a: ldloc.0
IL_003b: call ""void D.DummyUse(D.Boo)""
IL_0040: ldloca.s V_0
IL_0042: call ""void D.DummyUse1(ref D.Boo)""
IL_0047: ldarg.0
IL_0048: ldloca.s V_1
IL_004a: initobj ""D.Boo""
IL_0050: ldloc.1
IL_0051: dup
IL_0052: stloc.1
IL_0053: stobj ""D.Boo""
IL_0058: ldloc.1
IL_0059: call ""void D.DummyUse(D.Boo)""
IL_005e: ldarg.0
IL_005f: ldobj ""D.Boo""
IL_0064: call ""void D.DummyUse(D.Boo)""
IL_0069: ldarga.s V_1
IL_006b: initobj ""D.Boo""
IL_0071: ldarg.1
IL_0072: call ""void D.DummyUse(D.Boo)""
IL_0077: ldarg.1
IL_0078: call ""void D.DummyUse(D.Boo)""
IL_007d: ret
}
");
}
[Fact]
public void CtorUsed001()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(int i1)
{
this.I1 = i1;
}
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void DummyUse1(ref Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
DummyUse(v1 = new Boo(42));
DummyUse(v1);
Boo v2;
DummyUse(v2 = new Boo(42));
DummyUse(v2);
Boo v2a;
DummyUse(v2a = new Boo(42));
DummyUse1(ref v2a);
DummyUse(rArg = new Boo(42));
DummyUse(rArg);
DummyUse(vArg = new Boo(42));
DummyUse(vArg);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 122 (0x7a)
.maxstack 3
.locals init (D.Boo V_0, //v2a
D.Boo V_1)
IL_0000: ldc.i4.s 42
IL_0002: newobj ""D.Boo..ctor(int)""
IL_0007: dup
IL_0008: stsfld ""D.Boo D.v1""
IL_000d: call ""void D.DummyUse(D.Boo)""
IL_0012: ldsfld ""D.Boo D.v1""
IL_0017: call ""void D.DummyUse(D.Boo)""
IL_001c: ldc.i4.s 42
IL_001e: newobj ""D.Boo..ctor(int)""
IL_0023: dup
IL_0024: call ""void D.DummyUse(D.Boo)""
IL_0029: call ""void D.DummyUse(D.Boo)""
IL_002e: ldloca.s V_0
IL_0030: ldc.i4.s 42
IL_0032: call ""D.Boo..ctor(int)""
IL_0037: ldloc.0
IL_0038: call ""void D.DummyUse(D.Boo)""
IL_003d: ldloca.s V_0
IL_003f: call ""void D.DummyUse1(ref D.Boo)""
IL_0044: ldarg.0
IL_0045: ldc.i4.s 42
IL_0047: newobj ""D.Boo..ctor(int)""
IL_004c: dup
IL_004d: stloc.1
IL_004e: stobj ""D.Boo""
IL_0053: ldloc.1
IL_0054: call ""void D.DummyUse(D.Boo)""
IL_0059: ldarg.0
IL_005a: ldobj ""D.Boo""
IL_005f: call ""void D.DummyUse(D.Boo)""
IL_0064: ldarga.s V_1
IL_0066: ldc.i4.s 42
IL_0068: call ""D.Boo..ctor(int)""
IL_006d: ldarg.1
IL_006e: call ""void D.DummyUse(D.Boo)""
IL_0073: ldarg.1
IL_0074: call ""void D.DummyUse(D.Boo)""
IL_0079: ret
}
");
}
[Fact]
public void InheritedCallOnReadOnly()
{
string source = @"
class Program
{
static void Main()
{
var obj = new C1();
System.Console.WriteLine(obj.field.ToString());
}
}
class C1
{
public readonly S1 field;
}
struct S1
{
}
";
var compilation = CompileAndVerify(source, expectedOutput: "S1", verify: Verification.Skipped);
compilation.VerifyIL("Program.Main",
@"
{
// Code size 27 (0x1b)
.maxstack 1
IL_0000: newobj ""C1..ctor()""
IL_0005: ldflda ""S1 C1.field""
IL_000a: constrained. ""S1""
IL_0010: callvirt ""string object.ToString()""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: ret
}
");
compilation = CompileAndVerify(source, expectedOutput: "S1", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature());
compilation.VerifyIL("Program.Main",
@"
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (S1 V_0)
IL_0000: newobj ""C1..ctor()""
IL_0005: ldfld ""S1 C1.field""
IL_000a: stloc.0
IL_000b: ldloca.s V_0
IL_000d: constrained. ""S1""
IL_0013: callvirt ""string object.ToString()""
IL_0018: call ""void System.Console.WriteLine(string)""
IL_001d: ret
}
");
}
[Fact]
[WorkItem(27049, "https://github.com/dotnet/roslyn/issues/27049")]
public void BoxingRefStructForBaseCall()
{
CreateCompilation(@"
ref struct S
{
public override bool Equals(object obj) => base.Equals(obj);
public override int GetHashCode() => base.GetHashCode();
public override string ToString() => base.ToString();
}").VerifyDiagnostics(
// (4,48): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType'
// public override bool Equals(object obj) => base.Equals(obj);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(4, 48),
// (6,42): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType'
// public override int GetHashCode() => base.GetHashCode();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(6, 42),
// (8,42): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType'
// public override string ToString() => base.ToString();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(8, 42));
}
#endregion
#region "Enum"
[Fact]
public void TestEnum()
{
string source =
@"enum E { A, B }
class C
{
static void Main()
{
E e = E.A;
e = e + 1;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.Main",
@"{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: pop
IL_0002: ret
}
");
}
[Fact]
public void BoxEnum()
{
string source =
@"enum E { A, B }
class C
{
static void Main()
{
E e = E.B;
object o = e;
e = (E)o;
System.Console.Write(e);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "B");
compilation.VerifyIL("C.Main",
@"{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: box ""E""
IL_0006: unbox.any ""E""
IL_000b: box ""E""
IL_0010: call ""void System.Console.Write(object)""
IL_0015: ret
}
");
}
[Fact]
public void MBRO_StructField()
{
string source =
@"
using System;
class Program
{
static void Main(string[] args)
{
var v = new cls1();
v.Test();
}
}
struct S1
{
public Guid g;
}
class cls1 : MarshalByRefObject
{
public Guid g1;
public S1 s;
public void Test()
{
g1 = new Guid();
TestRef(ref g1);
g1 = new Guid(g1.ToString());
System.Console.WriteLine(g1);
System.Console.WriteLine(s.g.ToString());
var other = new cls1();
other.g1 = new Guid();
System.Console.WriteLine(other.g1);
TestRef(ref other.g1);
other.g1 = new Guid(other.g1.ToString());
System.Console.WriteLine(other.g1);
System.Console.WriteLine(other.s.g.ToString());
var gg = other.s.g;
System.Console.WriteLine(gg);
}
public void TestRef(ref Guid arg)
{
arg = new Guid(""ca761232ed4211cebacd00aa0057b223"");
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"ca761232-ed42-11ce-bacd-00aa0057b223
00000000-0000-0000-0000-000000000000
00000000-0000-0000-0000-000000000000
ca761232-ed42-11ce-bacd-00aa0057b223
00000000-0000-0000-0000-000000000000
00000000-0000-0000-0000-000000000000");
compilation.VerifyIL("cls1.Test",
@"
{
// Code size 237 (0xed)
.maxstack 2
.locals init (cls1 V_0, //other
System.Guid V_1)
IL_0000: ldarg.0
IL_0001: ldflda ""System.Guid cls1.g1""
IL_0006: initobj ""System.Guid""
IL_000c: ldarg.0
IL_000d: ldarg.0
IL_000e: ldflda ""System.Guid cls1.g1""
IL_0013: call ""void cls1.TestRef(ref System.Guid)""
IL_0018: ldarg.0
IL_0019: ldarg.0
IL_001a: ldflda ""System.Guid cls1.g1""
IL_001f: constrained. ""System.Guid""
IL_0025: callvirt ""string object.ToString()""
IL_002a: newobj ""System.Guid..ctor(string)""
IL_002f: stfld ""System.Guid cls1.g1""
IL_0034: ldarg.0
IL_0035: ldfld ""System.Guid cls1.g1""
IL_003a: box ""System.Guid""
IL_003f: call ""void System.Console.WriteLine(object)""
IL_0044: ldarg.0
IL_0045: ldflda ""S1 cls1.s""
IL_004a: ldflda ""System.Guid S1.g""
IL_004f: constrained. ""System.Guid""
IL_0055: callvirt ""string object.ToString()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: newobj ""cls1..ctor()""
IL_0064: stloc.0
IL_0065: ldloc.0
IL_0066: ldloca.s V_1
IL_0068: initobj ""System.Guid""
IL_006e: ldloc.1
IL_006f: stfld ""System.Guid cls1.g1""
IL_0074: ldloc.0
IL_0075: ldfld ""System.Guid cls1.g1""
IL_007a: box ""System.Guid""
IL_007f: call ""void System.Console.WriteLine(object)""
IL_0084: ldarg.0
IL_0085: ldloc.0
IL_0086: ldflda ""System.Guid cls1.g1""
IL_008b: call ""void cls1.TestRef(ref System.Guid)""
IL_0090: ldloc.0
IL_0091: ldloc.0
IL_0092: ldflda ""System.Guid cls1.g1""
IL_0097: constrained. ""System.Guid""
IL_009d: callvirt ""string object.ToString()""
IL_00a2: newobj ""System.Guid..ctor(string)""
IL_00a7: stfld ""System.Guid cls1.g1""
IL_00ac: ldloc.0
IL_00ad: ldfld ""System.Guid cls1.g1""
IL_00b2: box ""System.Guid""
IL_00b7: call ""void System.Console.WriteLine(object)""
IL_00bc: ldloc.0
IL_00bd: ldflda ""S1 cls1.s""
IL_00c2: ldflda ""System.Guid S1.g""
IL_00c7: constrained. ""System.Guid""
IL_00cd: callvirt ""string object.ToString()""
IL_00d2: call ""void System.Console.WriteLine(string)""
IL_00d7: ldloc.0
IL_00d8: ldfld ""S1 cls1.s""
IL_00dd: ldfld ""System.Guid S1.g""
IL_00e2: box ""System.Guid""
IL_00e7: call ""void System.Console.WriteLine(object)""
IL_00ec: ret
}
");
}
[Fact]
public void InitTemp001()
{
string source = @"
using System;
struct S
{
int x;
static void Main()
{
Console.WriteLine(new S { x = 0 }.Equals(new S { x = 1 }));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False");
compilation.VerifyIL("S.Main",
@"
{
// Code size 57 (0x39)
.maxstack 3
.locals init (S V_0,
S V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.0
IL_000b: stfld ""int S.x""
IL_0010: ldloca.s V_0
IL_0012: ldloca.s V_1
IL_0014: initobj ""S""
IL_001a: ldloca.s V_1
IL_001c: ldc.i4.1
IL_001d: stfld ""int S.x""
IL_0022: ldloc.1
IL_0023: box ""S""
IL_0028: constrained. ""S""
IL_002e: callvirt ""bool object.Equals(object)""
IL_0033: call ""void System.Console.WriteLine(bool)""
IL_0038: ret
}
");
}
[Fact]
public void InitTemp001a()
{
string source = @"
using System;
struct S1
{
public int x;
}
struct S
{
public S1 x;
static void Main()
{
Console.WriteLine(new S { x = new S1{x=0} }.x.Equals(new S { x = new S1{x=1} }));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False");
compilation.VerifyIL("S.Main",
@"
{
// Code size 94 (0x5e)
.maxstack 4
.locals init (S V_0,
S1 V_1,
S V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldloca.s V_1
IL_000c: initobj ""S1""
IL_0012: ldloca.s V_1
IL_0014: ldc.i4.0
IL_0015: stfld ""int S1.x""
IL_001a: ldloc.1
IL_001b: stfld ""S1 S.x""
IL_0020: ldloca.s V_0
IL_0022: ldflda ""S1 S.x""
IL_0027: ldloca.s V_2
IL_0029: initobj ""S""
IL_002f: ldloca.s V_2
IL_0031: ldloca.s V_1
IL_0033: initobj ""S1""
IL_0039: ldloca.s V_1
IL_003b: ldc.i4.1
IL_003c: stfld ""int S1.x""
IL_0041: ldloc.1
IL_0042: stfld ""S1 S.x""
IL_0047: ldloc.2
IL_0048: box ""S""
IL_004d: constrained. ""S1""
IL_0053: callvirt ""bool object.Equals(object)""
IL_0058: call ""void System.Console.WriteLine(bool)""
IL_005d: ret
}
");
}
[Fact]
public void InitTemp001b()
{
string source = @"
using System;
class S1
{
public int x;
}
struct S
{
public S1 x;
static void Main()
{
Console.WriteLine(new S { x = new S1{x=0} }.x.Equals(new S { x = new S1{x=1} }));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False");
compilation.VerifyIL("S.Main",
@"
{
// Code size 77 (0x4d)
.maxstack 5
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: newobj ""S1..ctor()""
IL_000f: dup
IL_0010: ldc.i4.0
IL_0011: stfld ""int S1.x""
IL_0016: stfld ""S1 S.x""
IL_001b: ldloc.0
IL_001c: ldfld ""S1 S.x""
IL_0021: ldloca.s V_0
IL_0023: initobj ""S""
IL_0029: ldloca.s V_0
IL_002b: newobj ""S1..ctor()""
IL_0030: dup
IL_0031: ldc.i4.1
IL_0032: stfld ""int S1.x""
IL_0037: stfld ""S1 S.x""
IL_003c: ldloc.0
IL_003d: box ""S""
IL_0042: callvirt ""bool object.Equals(object)""
IL_0047: call ""void System.Console.WriteLine(bool)""
IL_004c: ret
}
");
}
[Fact]
public void InitTemp002()
{
string source = @"
using System;
struct S
{
int x;
static void Main()
{
Console.WriteLine(new S { x = 0 }.Equals(new S { x = 1 }).Equals(
new S { x = 1 }.Equals(new S { x = 1 })));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False");
compilation.VerifyIL("S.Main",
@"
{
// Code size 116 (0x74)
.maxstack 4
.locals init (S V_0,
S V_1,
bool V_2,
S V_3)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.0
IL_000b: stfld ""int S.x""
IL_0010: ldloca.s V_0
IL_0012: ldloca.s V_1
IL_0014: initobj ""S""
IL_001a: ldloca.s V_1
IL_001c: ldc.i4.1
IL_001d: stfld ""int S.x""
IL_0022: ldloc.1
IL_0023: box ""S""
IL_0028: constrained. ""S""
IL_002e: callvirt ""bool object.Equals(object)""
IL_0033: stloc.2
IL_0034: ldloca.s V_2
IL_0036: ldloca.s V_1
IL_0038: initobj ""S""
IL_003e: ldloca.s V_1
IL_0040: ldc.i4.1
IL_0041: stfld ""int S.x""
IL_0046: ldloca.s V_1
IL_0048: ldloca.s V_3
IL_004a: initobj ""S""
IL_0050: ldloca.s V_3
IL_0052: ldc.i4.1
IL_0053: stfld ""int S.x""
IL_0058: ldloc.3
IL_0059: box ""S""
IL_005e: constrained. ""S""
IL_0064: callvirt ""bool object.Equals(object)""
IL_0069: call ""bool bool.Equals(bool)""
IL_006e: call ""void System.Console.WriteLine(bool)""
IL_0073: ret
}
");
}
[Fact]
public void InitTemp003()
{
string source = @"
using System;
readonly struct S
{
readonly int x;
public S(int x)
{
this.x = x;
}
static void Main()
{
// named argument reordering introduces a sequence with temps
// and we cannot know whether RefMethod returns a ref to a sequence local
// so we must assume that it can, and therefore must keep all the sequence the locals in use
// for the duration of the most-encompassing expression.
Console.WriteLine(RefMethod(arg2: I(5), arg1: I(3)).GreaterThan(
RefMethod(arg2: I(0), arg1: I(0))));
}
public static ref readonly S RefMethod(in S arg1, in S arg2)
{
return ref arg2;
}
public bool GreaterThan(in S arg)
{
return this.x > arg.x;
}
public static S I(int arg)
{
return new S(arg);
}
}
";
var compilation = CompileAndVerify(source, verify: Verification.Fails, expectedOutput: "True");
compilation.VerifyIL("S.Main",
@"
{
// Code size 57 (0x39)
.maxstack 3
.locals init (S V_0,
S V_1,
S V_2,
S V_3)
IL_0000: ldc.i4.5
IL_0001: call ""S S.I(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.3
IL_0008: call ""S S.I(int)""
IL_000d: stloc.1
IL_000e: ldloca.s V_1
IL_0010: ldloca.s V_0
IL_0012: call ""ref readonly S S.RefMethod(in S, in S)""
IL_0017: ldc.i4.0
IL_0018: call ""S S.I(int)""
IL_001d: stloc.2
IL_001e: ldc.i4.0
IL_001f: call ""S S.I(int)""
IL_0024: stloc.3
IL_0025: ldloca.s V_3
IL_0027: ldloca.s V_2
IL_0029: call ""ref readonly S S.RefMethod(in S, in S)""
IL_002e: call ""bool S.GreaterThan(in S)""
IL_0033: call ""void System.Console.WriteLine(bool)""
IL_0038: ret
}
");
}
[Fact]
public void InitTemp004()
{
string source = @"
using System;
readonly struct S
{
public readonly int x;
public S(int x)
{
this.x = x;
}
static void Main()
{
System.Console.Write(TestRO().x);
System.Console.WriteLine();
System.Console.Write(Test().x);
}
static ref readonly S TestRO()
{
try
{
// both args are refs
return ref RefMethodRO(arg2: I(5), arg1: I(3));
}
finally
{
// first arg is a value!!
RefMethodRO(arg2: I_Val(5), arg1: I(3));
}
}
public static ref readonly S RefMethodRO(in S arg1, in S arg2)
{
System.Console.Write(arg2.x);
return ref arg2;
}
// similar as above, but with regular (not readonly) refs for comparison
static ref S Test()
{
try
{
return ref RefMethod(arg2: ref I(5), arg1: ref I(3));
}
finally
{
var temp = I(5);
RefMethod(arg2: ref temp, arg1: ref I(3));
}
}
public static ref S RefMethod(ref S arg1, ref S arg2)
{
System.Console.Write(arg2.x);
return ref arg2;
}
private static S[] arr = new S[] { new S() };
public static ref S I(int arg)
{
arr[0] = new S(arg);
return ref arr[0];
}
public static S I_Val(int arg)
{
arr[0] = new S(arg);
return arr[0];
}
}
";
var compilation = CompileAndVerify(source, verify: Verification.Fails, expectedOutput: @"353
353");
compilation.VerifyIL("S.TestRO",
@"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (S& V_0,
S& V_1,
S V_2)
.try
{
IL_0000: ldc.i4.5
IL_0001: call ""ref S S.I(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.3
IL_0008: call ""ref S S.I(int)""
IL_000d: ldloc.0
IL_000e: call ""ref readonly S S.RefMethodRO(in S, in S)""
IL_0013: stloc.1
IL_0014: leave.s IL_002c
}
finally
{
IL_0016: ldc.i4.5
IL_0017: call ""S S.I_Val(int)""
IL_001c: stloc.2
IL_001d: ldc.i4.3
IL_001e: call ""ref S S.I(int)""
IL_0023: ldloca.s V_2
IL_0025: call ""ref readonly S S.RefMethodRO(in S, in S)""
IL_002a: pop
IL_002b: endfinally
}
IL_002c: ldloc.1
IL_002d: ret
}
");
}
[WorkItem(842477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842477")]
[Fact]
public void DecimalConst()
{
string source = @"
#pragma warning disable 458, 169, 414
using System;
public class NullableTest
{
static decimal? NULL = null;
public static void EqualEqual()
{
Test.Eval((decimal?)1m == null, false);
Test.Eval((decimal?)1m == NULL, false);
Test.Eval((decimal?)0 == NULL, false);
}
}
public class Test
{
public static void Eval(object obj1, object obj2)
{
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("NullableTest.EqualEqual",
@"
{
// Code size 112 (0x70)
.maxstack 2
.locals init (decimal? V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: ldc.i4.0
IL_0007: box ""bool""
IL_000c: call ""void Test.Eval(object, object)""
IL_0011: ldsfld ""decimal decimal.One""
IL_0016: ldsfld ""decimal? NullableTest.NULL""
IL_001b: stloc.0
IL_001c: ldloca.s V_0
IL_001e: call ""decimal decimal?.GetValueOrDefault()""
IL_0023: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0028: ldloca.s V_0
IL_002a: call ""bool decimal?.HasValue.get""
IL_002f: and
IL_0030: box ""bool""
IL_0035: ldc.i4.0
IL_0036: box ""bool""
IL_003b: call ""void Test.Eval(object, object)""
IL_0040: ldsfld ""decimal decimal.Zero""
IL_0045: ldsfld ""decimal? NullableTest.NULL""
IL_004a: stloc.0
IL_004b: ldloca.s V_0
IL_004d: call ""decimal decimal?.GetValueOrDefault()""
IL_0052: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0057: ldloca.s V_0
IL_0059: call ""bool decimal?.HasValue.get""
IL_005e: and
IL_005f: box ""bool""
IL_0064: ldc.i4.0
IL_0065: box ""bool""
IL_006a: call ""void Test.Eval(object, object)""
IL_006f: ret
}
");
}
[Fact]
public void FieldLoad001()
{
string source = @"
using System;
struct Point
{
public int x;
public int y;
}
class Rectangle
{
public Point topLeft;
public Point bottomRight;
}
struct C1
{
public C1(int i)
{
r = new Rectangle();
}
public Rectangle r;
}
class Program
{
static object p = new C1(1);
static void Main(string[] args)
{
System.Console.WriteLine(((C1)p).r.topLeft.x);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldsfld ""object Program.p""
IL_0005: unbox ""C1""
IL_000a: ldfld ""Rectangle C1.r""
IL_000f: ldflda ""Point Rectangle.topLeft""
IL_0014: ldfld ""int Point.x""
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ret
}
");
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenStructsAndEnum : EmitMetadataTestBase
{
#region "Struct"
[Fact]
public void ValInstanceField()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public static Boo Inst;
}
public static void Main()
{
Boo val = Boo.Inst;
int i = val.I1;
System.Console.Write(i);
val.I1 = 42;
System.Console.Write(val.I1);
val.I1 = 7;
System.Console.Write(val.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0427");
compilation.VerifyIL("D.Main",
@"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (D.Boo V_0) //val
IL_0000: ldsfld ""D.Boo D.Boo.Inst""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldfld ""int D.Boo.I1""
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldloca.s V_0
IL_0013: ldc.i4.s 42
IL_0015: stfld ""int D.Boo.I1""
IL_001a: ldloc.0
IL_001b: ldfld ""int D.Boo.I1""
IL_0020: call ""void System.Console.Write(int)""
IL_0025: ldloca.s V_0
IL_0027: ldc.i4.7
IL_0028: stfld ""int D.Boo.I1""
IL_002d: ldloc.0
IL_002e: ldfld ""int D.Boo.I1""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[Fact]
public void ValStaticField()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public static Boo Inst;
}
public static void Main()
{
Boo val = Boo.Inst;
System.Console.Write(Boo.Inst.I1);
val.I1 = 42;
Boo.Inst = val;
System.Console.Write(Boo.Inst.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "042");
compilation.VerifyIL("D.Main",
@"{
// Code size 52 (0x34)
.maxstack 2
.locals init (D.Boo V_0) //val
IL_0000: ldsfld ""D.Boo D.Boo.Inst""
IL_0005: stloc.0
IL_0006: ldsflda ""D.Boo D.Boo.Inst""
IL_000b: ldfld ""int D.Boo.I1""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ldloca.s V_0
IL_0017: ldc.i4.s 42
IL_0019: stfld ""int D.Boo.I1""
IL_001e: ldloc.0
IL_001f: stsfld ""D.Boo D.Boo.Inst""
IL_0024: ldsflda ""D.Boo D.Boo.Inst""
IL_0029: ldfld ""int D.Boo.I1""
IL_002e: call ""void System.Console.Write(int)""
IL_0033: ret
}
");
}
[Fact]
public void StructCtor()
{
string source = @"
public class D
{
public static void Main()
{
System.Decimal val = 0m;
System.Console.Write(val);
val = new System.Decimal(7);
System.Console.Write(val);
val = new System.Decimal();
System.Console.Write(val);
val = ((decimal)int.MaxValue + 1) * 4; // use the ctor that takes a long
System.Console.Write(val);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0708589934592");
// expect just two locals (temp is reused)
compilation.VerifyIL("D.Main",
@"
{
// Code size 51 (0x33)
.maxstack 1
IL_0000: ldsfld ""decimal decimal.Zero""
IL_0005: call ""void System.Console.Write(decimal)""
IL_000a: ldc.i4.7
IL_000b: newobj ""decimal..ctor(int)""
IL_0010: call ""void System.Console.Write(decimal)""
IL_0015: ldsfld ""decimal decimal.Zero""
IL_001a: call ""void System.Console.Write(decimal)""
IL_001f: ldc.i8 0x200000000
IL_0028: newobj ""decimal..ctor(long)""
IL_002d: call ""void System.Console.Write(decimal)""
IL_0032: ret
}
");
}
[Fact]
public void AddressUnbox()
{
string source = @"
using System;
class Program
{
public struct S1
{
public int x;
public void Goo()
{
x = 123;
}
}
public static S1 goo()
{
return new S1();
}
static void Main()
{
goo().ToString();
Console.Write(goo().x);
}
}";
var compilation = CompileAndVerify(source, expectedOutput: @"0");
compilation.VerifyIL("Program.Main",
@"{
// Code size 36 (0x24)
.maxstack 1
.locals init (Program.S1 V_0)
IL_0000: call ""Program.S1 Program.goo()""
IL_0005: stloc.0
IL_0006: ldloca.s V_0
IL_0008: constrained. ""Program.S1""
IL_000e: callvirt ""string object.ToString()""
IL_0013: pop
IL_0014: call ""Program.S1 Program.goo()""
IL_0019: ldfld ""int Program.S1.x""
IL_001e: call ""void System.Console.Write(int)""
IL_0023: ret
}
");
}
[Fact]
public void EqualsHashcode()
{
string source = @"
using System;
struct S1
{
public int field;
public override bool Equals(object obj)
{
return obj is S1 && field == ((S1)obj).field;
}
public override int GetHashCode()
{
return field;
}
public static bool operator ==(S1 value1, S1 value2)
{
return value1.field == value2.field;
}
public static bool operator !=(S1 value1, S1 value2)
{
return value1.field != value2.field;
}
}
class Program
{
static void Main(string[] args)
{
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"");
compilation.VerifyIL("S1.Equals(object)",
@"
{
// Code size 30 (0x1e)
.maxstack 2
IL_0000: ldarg.1
IL_0001: isinst ""S1""
IL_0006: brfalse.s IL_001c
IL_0008: ldarg.0
IL_0009: ldfld ""int S1.field""
IL_000e: ldarg.1
IL_000f: unbox ""S1""
IL_0014: ldfld ""int S1.field""
IL_0019: ceq
IL_001b: ret
IL_001c: ldc.i4.0
IL_001d: ret
}
").VerifyIL("S1.GetHashCode()",
@"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int S1.field""
IL_0006: ret
}
").VerifyIL("bool S1.op_Equality(S1, S1)",
@"
{
// Code size 15 (0xf)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int S1.field""
IL_0006: ldarg.1
IL_0007: ldfld ""int S1.field""
IL_000c: ceq
IL_000e: ret
}
").VerifyIL("bool S1.op_Inequality(S1, S1)",
@"
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int S1.field""
IL_0006: ldarg.1
IL_0007: ldfld ""int S1.field""
IL_000c: ceq
IL_000e: ldc.i4.0
IL_000f: ceq
IL_0011: ret
}
");
}
[Fact]
public void EmitObjectGetTypeCallOnStruct()
{
string source = @"
using System;
class Program
{
public struct S1
{
}
static void Main()
{
Console.Write((new S1()).GetType());
}
}";
var compilation = CompileAndVerify(source, expectedOutput: @"Program+S1");
compilation.VerifyIL("Program.Main",
@"{
// Code size 25 (0x19)
.maxstack 1
.locals init (Program.S1 V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""Program.S1""
IL_0008: ldloc.0
IL_0009: box ""Program.S1""
IL_000e: call ""System.Type object.GetType()""
IL_0013: call ""void System.Console.Write(object)""
IL_0018: ret
}
");
}
[Fact]
public void EmitInterfaceMethodOnStruct()
{
string source = @"
using System;
class Program
{
interface I
{
void M();
}
struct S : I
{
public void M()
{
Console.WriteLine(""S::M"");
}
}
static void Main(string[] args)
{
S s = new S();
s.M();
((I)s).M();
}
}";
var compilation = CompileAndVerify(source, expectedOutput: @"S::M
S::M");
compilation.VerifyIL("Program.Main",
@"{
// Code size 27 (0x1b)
.maxstack 1
.locals init (Program.S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""Program.S""
IL_0008: ldloca.s V_0
IL_000a: call ""void Program.S.M()""
IL_000f: ldloc.0
IL_0010: box ""Program.S""
IL_0015: callvirt ""void Program.I.M()""
IL_001a: ret
}
");
}
[Fact]
public void ValueTypeWithGeneric()
{
string source = @"
namespace NS
{
using System;
using N2;
namespace N2
{
public interface IGoo<T>
{
void M(T t);
}
struct S<T, V> : IGoo<T>
{
public S(V v)
{
field = v;
}
public V field;
public void M(T t) { Console.WriteLine(t); }
}
}
public class Test
{
static S<N2, char>[] ary;
class N1 { }
class N2 : N1 { }
static void Main()
{
IGoo<string> goo = new S<string, byte>(255);
goo.M(""Abc"");
Console.WriteLine(((S<string, byte>)goo).field);
ary = new S<N2, char>[3];
ary[0] = ary[1] = ary[2] = new S<N2, char>('q');
Console.WriteLine(ary[1].field);
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"
Abc
255
q");
compilation.VerifyIL("NS.Test.Main",
@"{
// Code size 120 (0x78)
.maxstack 8
.locals init (NS.N2.S<NS.Test.N2, char> V_0)
IL_0000: ldc.i4 0xff
IL_0005: newobj ""NS.N2.S<string, byte>..ctor(byte)""
IL_000a: box ""NS.N2.S<string, byte>""
IL_000f: dup
IL_0010: ldstr ""Abc""
IL_0015: callvirt ""void NS.N2.IGoo<string>.M(string)""
IL_001a: unbox ""NS.N2.S<string, byte>""
IL_001f: ldfld ""byte NS.N2.S<string, byte>.field""
IL_0024: call ""void System.Console.WriteLine(int)""
IL_0029: ldc.i4.3
IL_002a: newarr ""NS.N2.S<NS.Test.N2, char>""
IL_002f: stsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_0034: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_0039: ldc.i4.0
IL_003a: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_003f: ldc.i4.1
IL_0040: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_0045: ldc.i4.2
IL_0046: ldc.i4.s 113
IL_0048: newobj ""NS.N2.S<NS.Test.N2, char>..ctor(char)""
IL_004d: dup
IL_004e: stloc.0
IL_004f: stelem ""NS.N2.S<NS.Test.N2, char>""
IL_0054: ldloc.0
IL_0055: dup
IL_0056: stloc.0
IL_0057: stelem ""NS.N2.S<NS.Test.N2, char>""
IL_005c: ldloc.0
IL_005d: stelem ""NS.N2.S<NS.Test.N2, char>""
IL_0062: ldsfld ""NS.N2.S<NS.Test.N2, char>[] NS.Test.ary""
IL_0067: ldc.i4.1
IL_0068: ldelema ""NS.N2.S<NS.Test.N2, char>""
IL_006d: ldfld ""char NS.N2.S<NS.Test.N2, char>.field""
IL_0072: call ""void System.Console.WriteLine(char)""
IL_0077: ret
}
");
}
[WorkItem(540954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540954")]
[Fact]
public void StructInit()
{
var text =
@"
struct Struct
{
public static void Main()
{
Struct s = new Struct();
}
}
";
string expectedIL = @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (Struct V_0) //s
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj ""Struct""
IL_0009: ret
}
";
CompileAndVerify(text, options: TestOptions.DebugExe).VerifyIL("Struct.Main()", expectedIL);
}
[WorkItem(541845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541845")]
[Fact]
public void ConstructEnum()
{
var text =
@"
using System;
class A
{
enum E1
{
AA
}
static void Main()
{
var v = new DayOfWeek();
Console.Write(v.ToString());
var e = new E1();
Console.WriteLine(e.ToString());
}
}
";
string expectedIL = @"
{
// Code size 41 (0x29)
.maxstack 1
.locals init (System.DayOfWeek V_0, //v
A.E1 V_1) //e
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: constrained. ""System.DayOfWeek""
IL_000a: callvirt ""string object.ToString()""
IL_000f: call ""void System.Console.Write(string)""
IL_0014: ldc.i4.0
IL_0015: stloc.1
IL_0016: ldloca.s V_1
IL_0018: constrained. ""A.E1""
IL_001e: callvirt ""string object.ToString()""
IL_0023: call ""void System.Console.WriteLine(string)""
IL_0028: ret
}";
CompileAndVerify(text, expectedOutput: "SundayAA").VerifyIL("A.Main()", expectedIL);
}
[WorkItem(541599, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541599")]
[Fact]
public void TestStructWithStaticField01()
{
var source = @"
using System;
public struct S
{
public static int _verify = 123;
static void Main()
{
Console.Write(_verify);
}
}
";
CompileAndVerify(source, expectedOutput: @"123");
}
[Fact, WorkItem(543088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543088")]
public void UseStructLocal()
{
var text = @"
using System;
struct GetProperty
{
int i;
GetProperty(int x)
{
i = x;
}
static void Main()
{
GetProperty t = new GetProperty(123);
Console.Write(t.i);
}
}
";
CompileAndVerify(text, expectedOutput: "123");
}
[Fact]
public void InplaceInit001()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
v1 = default(Boo);
DummyUse(v1);
Boo v2 = default(Boo);
DummyUse(v2);
rArg = default(Boo);
DummyUse(rArg);
vArg = default(Boo);
DummyUse(rArg);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 73 (0x49)
.maxstack 1
.locals init (D.Boo V_0)
IL_0000: ldsflda ""D.Boo D.v1""
IL_0005: initobj ""D.Boo""
IL_000b: ldsfld ""D.Boo D.v1""
IL_0010: call ""void D.DummyUse(D.Boo)""
IL_0015: ldloca.s V_0
IL_0017: initobj ""D.Boo""
IL_001d: ldloc.0
IL_001e: call ""void D.DummyUse(D.Boo)""
IL_0023: ldarg.0
IL_0024: initobj ""D.Boo""
IL_002a: ldarg.0
IL_002b: ldobj ""D.Boo""
IL_0030: call ""void D.DummyUse(D.Boo)""
IL_0035: ldarga.s V_1
IL_0037: initobj ""D.Boo""
IL_003d: ldarg.0
IL_003e: ldobj ""D.Boo""
IL_0043: call ""void D.DummyUse(D.Boo)""
IL_0048: ret
}
");
}
[Fact]
public void InplaceInit002()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
try
{
v1 = default(Boo);
DummyUse(v1);
Boo v2 = default(Boo);
DummyUse(v2);
rArg = default(Boo);
DummyUse(rArg);
vArg = default(Boo);
DummyUse(rArg);
}
catch (System.Exception)
{
rArg = default(Boo);
DummyUse(rArg);
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 96 (0x60)
.maxstack 1
.locals init (D.Boo V_0)
.try
{
IL_0000: ldsflda ""D.Boo D.v1""
IL_0005: initobj ""D.Boo""
IL_000b: ldsfld ""D.Boo D.v1""
IL_0010: call ""void D.DummyUse(D.Boo)""
IL_0015: ldloca.s V_0
IL_0017: initobj ""D.Boo""
IL_001d: ldloc.0
IL_001e: call ""void D.DummyUse(D.Boo)""
IL_0023: ldarg.0
IL_0024: initobj ""D.Boo""
IL_002a: ldarg.0
IL_002b: ldobj ""D.Boo""
IL_0030: call ""void D.DummyUse(D.Boo)""
IL_0035: ldarga.s V_1
IL_0037: initobj ""D.Boo""
IL_003d: ldarg.0
IL_003e: ldobj ""D.Boo""
IL_0043: call ""void D.DummyUse(D.Boo)""
IL_0048: leave.s IL_005f
}
catch System.Exception
{
IL_004a: pop
IL_004b: ldarg.0
IL_004c: initobj ""D.Boo""
IL_0052: ldarg.0
IL_0053: ldobj ""D.Boo""
IL_0058: call ""void D.DummyUse(D.Boo)""
IL_005d: leave.s IL_005f
}
IL_005f: ret
}
");
}
[Fact]
public void InplaceCtor001()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(int i1)
{
this.I1 = i1;
}
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
//try
//{
v1 = new Boo(42);
DummyUse(v1);
Boo v2 = new Boo(42);
DummyUse(v2);
rArg = new Boo(42);
DummyUse(rArg);
vArg = new Boo(42);
DummyUse(rArg);
//}
//catch (System.Exception)
//
// rArg = new Boo(42);
// DummyUse(rArg);
//}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 79 (0x4f)
.maxstack 2
IL_0000: ldc.i4.s 42
IL_0002: newobj ""D.Boo..ctor(int)""
IL_0007: stsfld ""D.Boo D.v1""
IL_000c: ldsfld ""D.Boo D.v1""
IL_0011: call ""void D.DummyUse(D.Boo)""
IL_0016: ldc.i4.s 42
IL_0018: newobj ""D.Boo..ctor(int)""
IL_001d: call ""void D.DummyUse(D.Boo)""
IL_0022: ldarg.0
IL_0023: ldc.i4.s 42
IL_0025: newobj ""D.Boo..ctor(int)""
IL_002a: stobj ""D.Boo""
IL_002f: ldarg.0
IL_0030: ldobj ""D.Boo""
IL_0035: call ""void D.DummyUse(D.Boo)""
IL_003a: ldarga.s V_1
IL_003c: ldc.i4.s 42
IL_003e: call ""D.Boo..ctor(int)""
IL_0043: ldarg.0
IL_0044: ldobj ""D.Boo""
IL_0049: call ""void D.DummyUse(D.Boo)""
IL_004e: ret
}
");
}
[Fact]
public void InplaceCtor002()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(int i1)
{
this.I1 = i1;
}
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
Boo v3;
try{
Boo v3a;
try
{
v1 = new Boo(42);
DummyUse(v1);
Boo v2 = new Boo(43);
DummyUse(v2);
v3 = new Boo(44);
v3.ToString();
// should be a call, since v4 is defined in the same try scope
Boo v4 = new Boo(45);
v4.ToString();
rArg = new Boo(46);
DummyUse(rArg);
vArg = new Boo(47);
DummyUse(rArg);
}
catch (System.Exception)
{
v3 = new Boo(44);
v3.ToString();
// should be a call, since v3a is defined in the same try scope
v3a = new Boo(44);
v3a.ToString();
// should be a call, since v4 is defined in the same try scope
Boo v4 = new Boo(45);
v4.ToString();
rArg = new Boo(48);
DummyUse(rArg);
}
}
finally
{
}
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 222 (0xde)
.maxstack 2
.locals init (D.Boo V_0, //v3
D.Boo V_1, //v3a
D.Boo V_2, //v4
D.Boo V_3) //v4
.try
{
IL_0000: ldc.i4.s 42
IL_0002: newobj ""D.Boo..ctor(int)""
IL_0007: stsfld ""D.Boo D.v1""
IL_000c: ldsfld ""D.Boo D.v1""
IL_0011: call ""void D.DummyUse(D.Boo)""
IL_0016: ldc.i4.s 43
IL_0018: newobj ""D.Boo..ctor(int)""
IL_001d: call ""void D.DummyUse(D.Boo)""
IL_0022: ldc.i4.s 44
IL_0024: newobj ""D.Boo..ctor(int)""
IL_0029: stloc.0
IL_002a: ldloca.s V_0
IL_002c: constrained. ""D.Boo""
IL_0032: callvirt ""string object.ToString()""
IL_0037: pop
IL_0038: ldloca.s V_2
IL_003a: ldc.i4.s 45
IL_003c: call ""D.Boo..ctor(int)""
IL_0041: ldloca.s V_2
IL_0043: constrained. ""D.Boo""
IL_0049: callvirt ""string object.ToString()""
IL_004e: pop
IL_004f: ldarg.0
IL_0050: ldc.i4.s 46
IL_0052: newobj ""D.Boo..ctor(int)""
IL_0057: stobj ""D.Boo""
IL_005c: ldarg.0
IL_005d: ldobj ""D.Boo""
IL_0062: call ""void D.DummyUse(D.Boo)""
IL_0067: ldc.i4.s 47
IL_0069: newobj ""D.Boo..ctor(int)""
IL_006e: starg.s V_1
IL_0070: ldarg.0
IL_0071: ldobj ""D.Boo""
IL_0076: call ""void D.DummyUse(D.Boo)""
IL_007b: leave.s IL_00dd
}
catch System.Exception
{
IL_007d: pop
IL_007e: ldloca.s V_0
IL_0080: ldc.i4.s 44
IL_0082: call ""D.Boo..ctor(int)""
IL_0087: ldloca.s V_0
IL_0089: constrained. ""D.Boo""
IL_008f: callvirt ""string object.ToString()""
IL_0094: pop
IL_0095: ldloca.s V_1
IL_0097: ldc.i4.s 44
IL_0099: call ""D.Boo..ctor(int)""
IL_009e: ldloca.s V_1
IL_00a0: constrained. ""D.Boo""
IL_00a6: callvirt ""string object.ToString()""
IL_00ab: pop
IL_00ac: ldloca.s V_3
IL_00ae: ldc.i4.s 45
IL_00b0: call ""D.Boo..ctor(int)""
IL_00b5: ldloca.s V_3
IL_00b7: constrained. ""D.Boo""
IL_00bd: callvirt ""string object.ToString()""
IL_00c2: pop
IL_00c3: ldarg.0
IL_00c4: ldc.i4.s 48
IL_00c6: newobj ""D.Boo..ctor(int)""
IL_00cb: stobj ""D.Boo""
IL_00d0: ldarg.0
IL_00d1: ldobj ""D.Boo""
IL_00d6: call ""void D.DummyUse(D.Boo)""
IL_00db: leave.s IL_00dd
}
IL_00dd: ret
}
");
}
[WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")]
[Fact]
public void InplaceCtor003()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(ref int i1)
{
this.I1 = 1;
this.I1 += i1;
}
public Boo(ref Boo b1)
{
this.I1 = 1;
this.I1 += b1.I1;
}
}
public static Boo v1;
public static void Main()
{
Boo a1 = default(Boo);
a1 = new Boo(ref a1);
System.Console.Write(a1.I1);
v1 = new Boo(ref v1);
System.Console.Write(v1.I1);
a1 = default(Boo);
v1 = default(Boo);
a1 = new Boo(ref a1.I1);
System.Console.Write(a1.I1);
v1 = new Boo(ref v1.I1);
System.Console.Write(v1.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "1111");
compilation.VerifyIL("D.Main",
@"
{
// Code size 136 (0x88)
.maxstack 1
.locals init (D.Boo V_0) //a1
IL_0000: ldloca.s V_0
IL_0002: initobj ""D.Boo""
IL_0008: ldloca.s V_0
IL_000a: newobj ""D.Boo..ctor(ref D.Boo)""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: ldfld ""int D.Boo.I1""
IL_0016: call ""void System.Console.Write(int)""
IL_001b: ldsflda ""D.Boo D.v1""
IL_0020: newobj ""D.Boo..ctor(ref D.Boo)""
IL_0025: stsfld ""D.Boo D.v1""
IL_002a: ldsflda ""D.Boo D.v1""
IL_002f: ldfld ""int D.Boo.I1""
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ldloca.s V_0
IL_003b: initobj ""D.Boo""
IL_0041: ldsflda ""D.Boo D.v1""
IL_0046: initobj ""D.Boo""
IL_004c: ldloca.s V_0
IL_004e: ldflda ""int D.Boo.I1""
IL_0053: newobj ""D.Boo..ctor(ref int)""
IL_0058: stloc.0
IL_0059: ldloc.0
IL_005a: ldfld ""int D.Boo.I1""
IL_005f: call ""void System.Console.Write(int)""
IL_0064: ldsflda ""D.Boo D.v1""
IL_0069: ldflda ""int D.Boo.I1""
IL_006e: newobj ""D.Boo..ctor(ref int)""
IL_0073: stsfld ""D.Boo D.v1""
IL_0078: ldsflda ""D.Boo D.v1""
IL_007d: ldfld ""int D.Boo.I1""
IL_0082: call ""void System.Console.Write(int)""
IL_0087: ret
}
");
}
[WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")]
[Fact]
public void InplaceCtor004()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(ref int i1)
{
this.I1 = 1;
this.I1 += i1;
}
public Boo(ref Boo b1)
{
this.I1 = 1;
this.I1 += b1.I1;
}
}
public static Boo v1;
public static void Main()
{
Boo a1 = default(Boo);
ref var r1 = ref a1;
a1 = new Boo(ref r1);
System.Console.Write(a1.I1);
ref var r2 = ref v1;
v1 = new Boo(ref r2);
System.Console.Write(v1.I1);
a1 = default(Boo);
v1 = default(Boo);
ref var r3 = ref a1.I1;
a1 = new Boo(ref r3);
System.Console.Write(a1.I1);
ref var r4 = ref v1.I1;
v1 = new Boo(ref r4);
System.Console.Write(v1.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "1111");
compilation.VerifyIL("D.Main",
@"
{
// Code size 146 (0x92)
.maxstack 1
.locals init (D.Boo V_0, //a1
D.Boo& V_1, //r1
D.Boo& V_2, //r2
int& V_3, //r3
int& V_4) //r4
IL_0000: ldloca.s V_0
IL_0002: initobj ""D.Boo""
IL_0008: ldloca.s V_0
IL_000a: stloc.1
IL_000b: ldloc.1
IL_000c: newobj ""D.Boo..ctor(ref D.Boo)""
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: ldfld ""int D.Boo.I1""
IL_0018: call ""void System.Console.Write(int)""
IL_001d: ldsflda ""D.Boo D.v1""
IL_0022: stloc.2
IL_0023: ldloc.2
IL_0024: newobj ""D.Boo..ctor(ref D.Boo)""
IL_0029: stsfld ""D.Boo D.v1""
IL_002e: ldsflda ""D.Boo D.v1""
IL_0033: ldfld ""int D.Boo.I1""
IL_0038: call ""void System.Console.Write(int)""
IL_003d: ldloca.s V_0
IL_003f: initobj ""D.Boo""
IL_0045: ldsflda ""D.Boo D.v1""
IL_004a: initobj ""D.Boo""
IL_0050: ldloca.s V_0
IL_0052: ldflda ""int D.Boo.I1""
IL_0057: stloc.3
IL_0058: ldloc.3
IL_0059: newobj ""D.Boo..ctor(ref int)""
IL_005e: stloc.0
IL_005f: ldloc.0
IL_0060: ldfld ""int D.Boo.I1""
IL_0065: call ""void System.Console.Write(int)""
IL_006a: ldsflda ""D.Boo D.v1""
IL_006f: ldflda ""int D.Boo.I1""
IL_0074: stloc.s V_4
IL_0076: ldloc.s V_4
IL_0078: newobj ""D.Boo..ctor(ref int)""
IL_007d: stsfld ""D.Boo D.v1""
IL_0082: ldsflda ""D.Boo D.v1""
IL_0087: ldfld ""int D.Boo.I1""
IL_008c: call ""void System.Console.Write(int)""
IL_0091: ret
}
");
}
[WorkItem(16364, "https://github.com/dotnet/roslyn/issues/16364")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)]
public void InplaceCtor005()
{
string source = @"
using System;
public class D
{
public struct Boo
{
public int I1;
public Boo(int x, __arglist)
{
this.I1 = 1;
this.I1 += __refvalue(new ArgIterator(__arglist).GetNextArg(), Boo).I1;
}
}
public static Boo v1;
public static void Main()
{
Boo a1 = default(Boo);
a1 = new Boo(1, __arglist(ref a1));
System.Console.Write(a1.I1);
v1 = new Boo(1, __arglist(ref v1));
System.Console.Write(v1.I1);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "11");
compilation.VerifyIL("D.Main",
@"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (D.Boo V_0) //a1
IL_0000: ldloca.s V_0
IL_0002: initobj ""D.Boo""
IL_0008: ldc.i4.1
IL_0009: ldloca.s V_0
IL_000b: newobj ""D.Boo..ctor(int, __arglist) with __arglist( ref D.Boo)""
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: ldfld ""int D.Boo.I1""
IL_0017: call ""void System.Console.Write(int)""
IL_001c: ldc.i4.1
IL_001d: ldsflda ""D.Boo D.v1""
IL_0022: newobj ""D.Boo..ctor(int, __arglist) with __arglist( ref D.Boo)""
IL_0027: stsfld ""D.Boo D.v1""
IL_002c: ldsflda ""D.Boo D.v1""
IL_0031: ldfld ""int D.Boo.I1""
IL_0036: call ""void System.Console.Write(int)""
IL_003b: ret
}
");
}
[Fact]
public void InitUsed001()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(int i1)
{
this.I1 = i1;
}
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void DummyUse1(ref Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
DummyUse(v1 = default(Boo));
DummyUse(v1);
Boo v2;
DummyUse(v2 = default(Boo));
DummyUse(v2);
// TODO: no need for a temp
Boo v2a;
DummyUse(v2a = default(Boo));
DummyUse1(ref v2a);
DummyUse(rArg = default(Boo));
DummyUse(rArg);
// TODO: no need for a temp
DummyUse(vArg = default(Boo));
DummyUse(vArg);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 126 (0x7e)
.maxstack 3
.locals init (D.Boo V_0, //v2a
D.Boo V_1)
IL_0000: ldloca.s V_1
IL_0002: initobj ""D.Boo""
IL_0008: ldloc.1
IL_0009: dup
IL_000a: stsfld ""D.Boo D.v1""
IL_000f: call ""void D.DummyUse(D.Boo)""
IL_0014: ldsfld ""D.Boo D.v1""
IL_0019: call ""void D.DummyUse(D.Boo)""
IL_001e: ldloca.s V_1
IL_0020: initobj ""D.Boo""
IL_0026: ldloc.1
IL_0027: dup
IL_0028: call ""void D.DummyUse(D.Boo)""
IL_002d: call ""void D.DummyUse(D.Boo)""
IL_0032: ldloca.s V_0
IL_0034: initobj ""D.Boo""
IL_003a: ldloc.0
IL_003b: call ""void D.DummyUse(D.Boo)""
IL_0040: ldloca.s V_0
IL_0042: call ""void D.DummyUse1(ref D.Boo)""
IL_0047: ldarg.0
IL_0048: ldloca.s V_1
IL_004a: initobj ""D.Boo""
IL_0050: ldloc.1
IL_0051: dup
IL_0052: stloc.1
IL_0053: stobj ""D.Boo""
IL_0058: ldloc.1
IL_0059: call ""void D.DummyUse(D.Boo)""
IL_005e: ldarg.0
IL_005f: ldobj ""D.Boo""
IL_0064: call ""void D.DummyUse(D.Boo)""
IL_0069: ldarga.s V_1
IL_006b: initobj ""D.Boo""
IL_0071: ldarg.1
IL_0072: call ""void D.DummyUse(D.Boo)""
IL_0077: ldarg.1
IL_0078: call ""void D.DummyUse(D.Boo)""
IL_007d: ret
}
");
}
[Fact]
public void CtorUsed001()
{
string source = @"
public class D
{
public struct Boo
{
public int I1;
public Boo(int i1)
{
this.I1 = i1;
}
}
public static Boo v1;
public static void DummyUse(Boo arg)
{
}
public static void DummyUse1(ref Boo arg)
{
}
public static void Main()
{
Boo a1 = default(Boo);
Boo a2 = default(Boo);
TestInit(out a1, a2);
}
private static void TestInit(out Boo rArg, Boo vArg)
{
DummyUse(v1 = new Boo(42));
DummyUse(v1);
Boo v2;
DummyUse(v2 = new Boo(42));
DummyUse(v2);
Boo v2a;
DummyUse(v2a = new Boo(42));
DummyUse1(ref v2a);
DummyUse(rArg = new Boo(42));
DummyUse(rArg);
DummyUse(vArg = new Boo(42));
DummyUse(vArg);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "");
compilation.VerifyIL("D.TestInit",
@"
{
// Code size 122 (0x7a)
.maxstack 3
.locals init (D.Boo V_0, //v2a
D.Boo V_1)
IL_0000: ldc.i4.s 42
IL_0002: newobj ""D.Boo..ctor(int)""
IL_0007: dup
IL_0008: stsfld ""D.Boo D.v1""
IL_000d: call ""void D.DummyUse(D.Boo)""
IL_0012: ldsfld ""D.Boo D.v1""
IL_0017: call ""void D.DummyUse(D.Boo)""
IL_001c: ldc.i4.s 42
IL_001e: newobj ""D.Boo..ctor(int)""
IL_0023: dup
IL_0024: call ""void D.DummyUse(D.Boo)""
IL_0029: call ""void D.DummyUse(D.Boo)""
IL_002e: ldloca.s V_0
IL_0030: ldc.i4.s 42
IL_0032: call ""D.Boo..ctor(int)""
IL_0037: ldloc.0
IL_0038: call ""void D.DummyUse(D.Boo)""
IL_003d: ldloca.s V_0
IL_003f: call ""void D.DummyUse1(ref D.Boo)""
IL_0044: ldarg.0
IL_0045: ldc.i4.s 42
IL_0047: newobj ""D.Boo..ctor(int)""
IL_004c: dup
IL_004d: stloc.1
IL_004e: stobj ""D.Boo""
IL_0053: ldloc.1
IL_0054: call ""void D.DummyUse(D.Boo)""
IL_0059: ldarg.0
IL_005a: ldobj ""D.Boo""
IL_005f: call ""void D.DummyUse(D.Boo)""
IL_0064: ldarga.s V_1
IL_0066: ldc.i4.s 42
IL_0068: call ""D.Boo..ctor(int)""
IL_006d: ldarg.1
IL_006e: call ""void D.DummyUse(D.Boo)""
IL_0073: ldarg.1
IL_0074: call ""void D.DummyUse(D.Boo)""
IL_0079: ret
}
");
}
[Fact]
public void InheritedCallOnReadOnly()
{
string source = @"
class Program
{
static void Main()
{
var obj = new C1();
System.Console.WriteLine(obj.field.ToString());
}
}
class C1
{
public readonly S1 field;
}
struct S1
{
}
";
var compilation = CompileAndVerify(source, expectedOutput: "S1", verify: Verification.Skipped);
compilation.VerifyIL("Program.Main",
@"
{
// Code size 27 (0x1b)
.maxstack 1
IL_0000: newobj ""C1..ctor()""
IL_0005: ldflda ""S1 C1.field""
IL_000a: constrained. ""S1""
IL_0010: callvirt ""string object.ToString()""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: ret
}
");
compilation = CompileAndVerify(source, expectedOutput: "S1", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature());
compilation.VerifyIL("Program.Main",
@"
{
// Code size 30 (0x1e)
.maxstack 1
.locals init (S1 V_0)
IL_0000: newobj ""C1..ctor()""
IL_0005: ldfld ""S1 C1.field""
IL_000a: stloc.0
IL_000b: ldloca.s V_0
IL_000d: constrained. ""S1""
IL_0013: callvirt ""string object.ToString()""
IL_0018: call ""void System.Console.WriteLine(string)""
IL_001d: ret
}
");
}
[Fact]
[WorkItem(27049, "https://github.com/dotnet/roslyn/issues/27049")]
public void BoxingRefStructForBaseCall()
{
CreateCompilation(@"
ref struct S
{
public override bool Equals(object obj) => base.Equals(obj);
public override int GetHashCode() => base.GetHashCode();
public override string ToString() => base.ToString();
}").VerifyDiagnostics(
// (4,48): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType'
// public override bool Equals(object obj) => base.Equals(obj);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(4, 48),
// (6,42): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType'
// public override int GetHashCode() => base.GetHashCode();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(6, 42),
// (8,42): error CS0029: Cannot implicitly convert type 'S' to 'System.ValueType'
// public override string ToString() => base.ToString();
Diagnostic(ErrorCode.ERR_NoImplicitConv, "base").WithArguments("S", "System.ValueType").WithLocation(8, 42));
}
#endregion
#region "Enum"
[Fact]
public void TestEnum()
{
string source =
@"enum E { A, B }
class C
{
static void Main()
{
E e = E.A;
e = e + 1;
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("C.Main",
@"{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: pop
IL_0002: ret
}
");
}
[Fact]
public void BoxEnum()
{
string source =
@"enum E { A, B }
class C
{
static void Main()
{
E e = E.B;
object o = e;
e = (E)o;
System.Console.Write(e);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "B");
compilation.VerifyIL("C.Main",
@"{
// Code size 22 (0x16)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: box ""E""
IL_0006: unbox.any ""E""
IL_000b: box ""E""
IL_0010: call ""void System.Console.Write(object)""
IL_0015: ret
}
");
}
[Fact]
public void MBRO_StructField()
{
string source =
@"
using System;
class Program
{
static void Main(string[] args)
{
var v = new cls1();
v.Test();
}
}
struct S1
{
public Guid g;
}
class cls1 : MarshalByRefObject
{
public Guid g1;
public S1 s;
public void Test()
{
g1 = new Guid();
TestRef(ref g1);
g1 = new Guid(g1.ToString());
System.Console.WriteLine(g1);
System.Console.WriteLine(s.g.ToString());
var other = new cls1();
other.g1 = new Guid();
System.Console.WriteLine(other.g1);
TestRef(ref other.g1);
other.g1 = new Guid(other.g1.ToString());
System.Console.WriteLine(other.g1);
System.Console.WriteLine(other.s.g.ToString());
var gg = other.s.g;
System.Console.WriteLine(gg);
}
public void TestRef(ref Guid arg)
{
arg = new Guid(""ca761232ed4211cebacd00aa0057b223"");
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: @"ca761232-ed42-11ce-bacd-00aa0057b223
00000000-0000-0000-0000-000000000000
00000000-0000-0000-0000-000000000000
ca761232-ed42-11ce-bacd-00aa0057b223
00000000-0000-0000-0000-000000000000
00000000-0000-0000-0000-000000000000");
compilation.VerifyIL("cls1.Test",
@"
{
// Code size 237 (0xed)
.maxstack 2
.locals init (cls1 V_0, //other
System.Guid V_1)
IL_0000: ldarg.0
IL_0001: ldflda ""System.Guid cls1.g1""
IL_0006: initobj ""System.Guid""
IL_000c: ldarg.0
IL_000d: ldarg.0
IL_000e: ldflda ""System.Guid cls1.g1""
IL_0013: call ""void cls1.TestRef(ref System.Guid)""
IL_0018: ldarg.0
IL_0019: ldarg.0
IL_001a: ldflda ""System.Guid cls1.g1""
IL_001f: constrained. ""System.Guid""
IL_0025: callvirt ""string object.ToString()""
IL_002a: newobj ""System.Guid..ctor(string)""
IL_002f: stfld ""System.Guid cls1.g1""
IL_0034: ldarg.0
IL_0035: ldfld ""System.Guid cls1.g1""
IL_003a: box ""System.Guid""
IL_003f: call ""void System.Console.WriteLine(object)""
IL_0044: ldarg.0
IL_0045: ldflda ""S1 cls1.s""
IL_004a: ldflda ""System.Guid S1.g""
IL_004f: constrained. ""System.Guid""
IL_0055: callvirt ""string object.ToString()""
IL_005a: call ""void System.Console.WriteLine(string)""
IL_005f: newobj ""cls1..ctor()""
IL_0064: stloc.0
IL_0065: ldloc.0
IL_0066: ldloca.s V_1
IL_0068: initobj ""System.Guid""
IL_006e: ldloc.1
IL_006f: stfld ""System.Guid cls1.g1""
IL_0074: ldloc.0
IL_0075: ldfld ""System.Guid cls1.g1""
IL_007a: box ""System.Guid""
IL_007f: call ""void System.Console.WriteLine(object)""
IL_0084: ldarg.0
IL_0085: ldloc.0
IL_0086: ldflda ""System.Guid cls1.g1""
IL_008b: call ""void cls1.TestRef(ref System.Guid)""
IL_0090: ldloc.0
IL_0091: ldloc.0
IL_0092: ldflda ""System.Guid cls1.g1""
IL_0097: constrained. ""System.Guid""
IL_009d: callvirt ""string object.ToString()""
IL_00a2: newobj ""System.Guid..ctor(string)""
IL_00a7: stfld ""System.Guid cls1.g1""
IL_00ac: ldloc.0
IL_00ad: ldfld ""System.Guid cls1.g1""
IL_00b2: box ""System.Guid""
IL_00b7: call ""void System.Console.WriteLine(object)""
IL_00bc: ldloc.0
IL_00bd: ldflda ""S1 cls1.s""
IL_00c2: ldflda ""System.Guid S1.g""
IL_00c7: constrained. ""System.Guid""
IL_00cd: callvirt ""string object.ToString()""
IL_00d2: call ""void System.Console.WriteLine(string)""
IL_00d7: ldloc.0
IL_00d8: ldfld ""S1 cls1.s""
IL_00dd: ldfld ""System.Guid S1.g""
IL_00e2: box ""System.Guid""
IL_00e7: call ""void System.Console.WriteLine(object)""
IL_00ec: ret
}
");
}
[Fact]
public void InitTemp001()
{
string source = @"
using System;
struct S
{
int x;
static void Main()
{
Console.WriteLine(new S { x = 0 }.Equals(new S { x = 1 }));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False");
compilation.VerifyIL("S.Main",
@"
{
// Code size 57 (0x39)
.maxstack 3
.locals init (S V_0,
S V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.0
IL_000b: stfld ""int S.x""
IL_0010: ldloca.s V_0
IL_0012: ldloca.s V_1
IL_0014: initobj ""S""
IL_001a: ldloca.s V_1
IL_001c: ldc.i4.1
IL_001d: stfld ""int S.x""
IL_0022: ldloc.1
IL_0023: box ""S""
IL_0028: constrained. ""S""
IL_002e: callvirt ""bool object.Equals(object)""
IL_0033: call ""void System.Console.WriteLine(bool)""
IL_0038: ret
}
");
}
[Fact]
public void InitTemp001a()
{
string source = @"
using System;
struct S1
{
public int x;
}
struct S
{
public S1 x;
static void Main()
{
Console.WriteLine(new S { x = new S1{x=0} }.x.Equals(new S { x = new S1{x=1} }));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False");
compilation.VerifyIL("S.Main",
@"
{
// Code size 94 (0x5e)
.maxstack 4
.locals init (S V_0,
S1 V_1,
S V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldloca.s V_1
IL_000c: initobj ""S1""
IL_0012: ldloca.s V_1
IL_0014: ldc.i4.0
IL_0015: stfld ""int S1.x""
IL_001a: ldloc.1
IL_001b: stfld ""S1 S.x""
IL_0020: ldloca.s V_0
IL_0022: ldflda ""S1 S.x""
IL_0027: ldloca.s V_2
IL_0029: initobj ""S""
IL_002f: ldloca.s V_2
IL_0031: ldloca.s V_1
IL_0033: initobj ""S1""
IL_0039: ldloca.s V_1
IL_003b: ldc.i4.1
IL_003c: stfld ""int S1.x""
IL_0041: ldloc.1
IL_0042: stfld ""S1 S.x""
IL_0047: ldloc.2
IL_0048: box ""S""
IL_004d: constrained. ""S1""
IL_0053: callvirt ""bool object.Equals(object)""
IL_0058: call ""void System.Console.WriteLine(bool)""
IL_005d: ret
}
");
}
[Fact]
public void InitTemp001b()
{
string source = @"
using System;
class S1
{
public int x;
}
struct S
{
public S1 x;
static void Main()
{
Console.WriteLine(new S { x = new S1{x=0} }.x.Equals(new S { x = new S1{x=1} }));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False");
compilation.VerifyIL("S.Main",
@"
{
// Code size 77 (0x4d)
.maxstack 5
.locals init (S V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: newobj ""S1..ctor()""
IL_000f: dup
IL_0010: ldc.i4.0
IL_0011: stfld ""int S1.x""
IL_0016: stfld ""S1 S.x""
IL_001b: ldloc.0
IL_001c: ldfld ""S1 S.x""
IL_0021: ldloca.s V_0
IL_0023: initobj ""S""
IL_0029: ldloca.s V_0
IL_002b: newobj ""S1..ctor()""
IL_0030: dup
IL_0031: ldc.i4.1
IL_0032: stfld ""int S1.x""
IL_0037: stfld ""S1 S.x""
IL_003c: ldloc.0
IL_003d: box ""S""
IL_0042: callvirt ""bool object.Equals(object)""
IL_0047: call ""void System.Console.WriteLine(bool)""
IL_004c: ret
}
");
}
[Fact]
public void InitTemp002()
{
string source = @"
using System;
struct S
{
int x;
static void Main()
{
Console.WriteLine(new S { x = 0 }.Equals(new S { x = 1 }).Equals(
new S { x = 1 }.Equals(new S { x = 1 })));
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "False");
compilation.VerifyIL("S.Main",
@"
{
// Code size 116 (0x74)
.maxstack 4
.locals init (S V_0,
S V_1,
bool V_2,
S V_3)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.0
IL_000b: stfld ""int S.x""
IL_0010: ldloca.s V_0
IL_0012: ldloca.s V_1
IL_0014: initobj ""S""
IL_001a: ldloca.s V_1
IL_001c: ldc.i4.1
IL_001d: stfld ""int S.x""
IL_0022: ldloc.1
IL_0023: box ""S""
IL_0028: constrained. ""S""
IL_002e: callvirt ""bool object.Equals(object)""
IL_0033: stloc.2
IL_0034: ldloca.s V_2
IL_0036: ldloca.s V_1
IL_0038: initobj ""S""
IL_003e: ldloca.s V_1
IL_0040: ldc.i4.1
IL_0041: stfld ""int S.x""
IL_0046: ldloca.s V_1
IL_0048: ldloca.s V_3
IL_004a: initobj ""S""
IL_0050: ldloca.s V_3
IL_0052: ldc.i4.1
IL_0053: stfld ""int S.x""
IL_0058: ldloc.3
IL_0059: box ""S""
IL_005e: constrained. ""S""
IL_0064: callvirt ""bool object.Equals(object)""
IL_0069: call ""bool bool.Equals(bool)""
IL_006e: call ""void System.Console.WriteLine(bool)""
IL_0073: ret
}
");
}
[Fact]
public void InitTemp003()
{
string source = @"
using System;
readonly struct S
{
readonly int x;
public S(int x)
{
this.x = x;
}
static void Main()
{
// named argument reordering introduces a sequence with temps
// and we cannot know whether RefMethod returns a ref to a sequence local
// so we must assume that it can, and therefore must keep all the sequence the locals in use
// for the duration of the most-encompassing expression.
Console.WriteLine(RefMethod(arg2: I(5), arg1: I(3)).GreaterThan(
RefMethod(arg2: I(0), arg1: I(0))));
}
public static ref readonly S RefMethod(in S arg1, in S arg2)
{
return ref arg2;
}
public bool GreaterThan(in S arg)
{
return this.x > arg.x;
}
public static S I(int arg)
{
return new S(arg);
}
}
";
var compilation = CompileAndVerify(source, verify: Verification.Fails, expectedOutput: "True");
compilation.VerifyIL("S.Main",
@"
{
// Code size 57 (0x39)
.maxstack 3
.locals init (S V_0,
S V_1,
S V_2,
S V_3)
IL_0000: ldc.i4.5
IL_0001: call ""S S.I(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.3
IL_0008: call ""S S.I(int)""
IL_000d: stloc.1
IL_000e: ldloca.s V_1
IL_0010: ldloca.s V_0
IL_0012: call ""ref readonly S S.RefMethod(in S, in S)""
IL_0017: ldc.i4.0
IL_0018: call ""S S.I(int)""
IL_001d: stloc.2
IL_001e: ldc.i4.0
IL_001f: call ""S S.I(int)""
IL_0024: stloc.3
IL_0025: ldloca.s V_3
IL_0027: ldloca.s V_2
IL_0029: call ""ref readonly S S.RefMethod(in S, in S)""
IL_002e: call ""bool S.GreaterThan(in S)""
IL_0033: call ""void System.Console.WriteLine(bool)""
IL_0038: ret
}
");
}
[Fact]
public void InitTemp004()
{
string source = @"
using System;
readonly struct S
{
public readonly int x;
public S(int x)
{
this.x = x;
}
static void Main()
{
System.Console.Write(TestRO().x);
System.Console.WriteLine();
System.Console.Write(Test().x);
}
static ref readonly S TestRO()
{
try
{
// both args are refs
return ref RefMethodRO(arg2: I(5), arg1: I(3));
}
finally
{
// first arg is a value!!
RefMethodRO(arg2: I_Val(5), arg1: I(3));
}
}
public static ref readonly S RefMethodRO(in S arg1, in S arg2)
{
System.Console.Write(arg2.x);
return ref arg2;
}
// similar as above, but with regular (not readonly) refs for comparison
static ref S Test()
{
try
{
return ref RefMethod(arg2: ref I(5), arg1: ref I(3));
}
finally
{
var temp = I(5);
RefMethod(arg2: ref temp, arg1: ref I(3));
}
}
public static ref S RefMethod(ref S arg1, ref S arg2)
{
System.Console.Write(arg2.x);
return ref arg2;
}
private static S[] arr = new S[] { new S() };
public static ref S I(int arg)
{
arr[0] = new S(arg);
return ref arr[0];
}
public static S I_Val(int arg)
{
arr[0] = new S(arg);
return arr[0];
}
}
";
var compilation = CompileAndVerify(source, verify: Verification.Fails, expectedOutput: @"353
353");
compilation.VerifyIL("S.TestRO",
@"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (S& V_0,
S& V_1,
S V_2)
.try
{
IL_0000: ldc.i4.5
IL_0001: call ""ref S S.I(int)""
IL_0006: stloc.0
IL_0007: ldc.i4.3
IL_0008: call ""ref S S.I(int)""
IL_000d: ldloc.0
IL_000e: call ""ref readonly S S.RefMethodRO(in S, in S)""
IL_0013: stloc.1
IL_0014: leave.s IL_002c
}
finally
{
IL_0016: ldc.i4.5
IL_0017: call ""S S.I_Val(int)""
IL_001c: stloc.2
IL_001d: ldc.i4.3
IL_001e: call ""ref S S.I(int)""
IL_0023: ldloca.s V_2
IL_0025: call ""ref readonly S S.RefMethodRO(in S, in S)""
IL_002a: pop
IL_002b: endfinally
}
IL_002c: ldloc.1
IL_002d: ret
}
");
}
[WorkItem(842477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842477")]
[Fact]
public void DecimalConst()
{
string source = @"
#pragma warning disable 458, 169, 414
using System;
public class NullableTest
{
static decimal? NULL = null;
public static void EqualEqual()
{
Test.Eval((decimal?)1m == null, false);
Test.Eval((decimal?)1m == NULL, false);
Test.Eval((decimal?)0 == NULL, false);
}
}
public class Test
{
public static void Eval(object obj1, object obj2)
{
}
}
";
var compilation = CompileAndVerify(source);
compilation.VerifyIL("NullableTest.EqualEqual",
@"
{
// Code size 112 (0x70)
.maxstack 2
.locals init (decimal? V_0)
IL_0000: ldc.i4.0
IL_0001: box ""bool""
IL_0006: ldc.i4.0
IL_0007: box ""bool""
IL_000c: call ""void Test.Eval(object, object)""
IL_0011: ldsfld ""decimal decimal.One""
IL_0016: ldsfld ""decimal? NullableTest.NULL""
IL_001b: stloc.0
IL_001c: ldloca.s V_0
IL_001e: call ""decimal decimal?.GetValueOrDefault()""
IL_0023: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0028: ldloca.s V_0
IL_002a: call ""bool decimal?.HasValue.get""
IL_002f: and
IL_0030: box ""bool""
IL_0035: ldc.i4.0
IL_0036: box ""bool""
IL_003b: call ""void Test.Eval(object, object)""
IL_0040: ldsfld ""decimal decimal.Zero""
IL_0045: ldsfld ""decimal? NullableTest.NULL""
IL_004a: stloc.0
IL_004b: ldloca.s V_0
IL_004d: call ""decimal decimal?.GetValueOrDefault()""
IL_0052: call ""bool decimal.op_Equality(decimal, decimal)""
IL_0057: ldloca.s V_0
IL_0059: call ""bool decimal?.HasValue.get""
IL_005e: and
IL_005f: box ""bool""
IL_0064: ldc.i4.0
IL_0065: box ""bool""
IL_006a: call ""void Test.Eval(object, object)""
IL_006f: ret
}
");
}
[Fact]
public void FieldLoad001()
{
string source = @"
using System;
struct Point
{
public int x;
public int y;
}
class Rectangle
{
public Point topLeft;
public Point bottomRight;
}
struct C1
{
public C1(int i)
{
r = new Rectangle();
}
public Rectangle r;
}
class Program
{
static object p = new C1(1);
static void Main(string[] args)
{
System.Console.WriteLine(((C1)p).r.topLeft.x);
}
}
";
var compilation = CompileAndVerify(source, expectedOutput: "0");
compilation.VerifyIL("Program.Main",
@"
{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldsfld ""object Program.p""
IL_0005: unbox ""C1""
IL_000a: ldfld ""Rectangle C1.r""
IL_000f: ldflda ""Point Rectangle.topLeft""
IL_0014: ldfld ""int Point.x""
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ret
}
");
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Workspaces/CoreTest/LinkedFileDiffMerging/LinkedFileDiffMergingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.UnitTests.LinkedFileDiffMerging
{
[UseExportProvider]
public partial class LinkedFileDiffMergingTests
{
private static void TestLinkedFileSet(string startText, List<string> updatedTexts, string expectedMergedText, string languageName)
{
using var workspace = new AdhocWorkspace();
var solution = workspace.CurrentSolution;
var startSourceText = SourceText.From(startText);
var documentIds = new List<DocumentId>();
for (var i = 0; i < updatedTexts.Count; i++)
{
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
documentIds.Add(documentId);
var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "ProjectName" + i, "AssemblyName" + i, languageName);
solution = solution
.AddProject(projectInfo)
.AddDocument(documentId, "DocumentName", startSourceText, filePath: "FilePath");
}
var startingSolution = solution;
var updatedSolution = solution;
for (var i = 0; i < updatedTexts.Count; i++)
{
var text = updatedTexts[i];
if (text != startText)
{
updatedSolution = updatedSolution
.WithDocumentText(documentIds[i], SourceText.From(text));
}
}
var mergedSolution = updatedSolution.WithMergedLinkedFileChangesAsync(startingSolution).Result;
for (var i = 0; i < updatedTexts.Count; i++)
{
AssertEx.EqualOrDiff(expectedMergedText, mergedSolution.GetDocument(documentIds[i]).GetTextAsync().Result.ToString());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.UnitTests.LinkedFileDiffMerging
{
[UseExportProvider]
public partial class LinkedFileDiffMergingTests
{
private static void TestLinkedFileSet(string startText, List<string> updatedTexts, string expectedMergedText, string languageName)
{
using var workspace = new AdhocWorkspace();
var solution = workspace.CurrentSolution;
var startSourceText = SourceText.From(startText);
var documentIds = new List<DocumentId>();
for (var i = 0; i < updatedTexts.Count; i++)
{
var projectId = ProjectId.CreateNewId();
var documentId = DocumentId.CreateNewId(projectId);
documentIds.Add(documentId);
var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "ProjectName" + i, "AssemblyName" + i, languageName);
solution = solution
.AddProject(projectInfo)
.AddDocument(documentId, "DocumentName", startSourceText, filePath: "FilePath");
}
var startingSolution = solution;
var updatedSolution = solution;
for (var i = 0; i < updatedTexts.Count; i++)
{
var text = updatedTexts[i];
if (text != startText)
{
updatedSolution = updatedSolution
.WithDocumentText(documentIds[i], SourceText.From(text));
}
}
var mergedSolution = updatedSolution.WithMergedLinkedFileChangesAsync(startingSolution).Result;
for (var i = 0; i < updatedTexts.Count; i++)
{
AssertEx.EqualOrDiff(expectedMergedText, mergedSolution.GetDocument(documentIds[i]).GetTextAsync().Result.ToString());
}
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/WordSimilarityChecker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
namespace Roslyn.Utilities
{
internal class WordSimilarityChecker
{
private struct CacheResult
{
public readonly string CandidateText;
public readonly bool AreSimilar;
public readonly double SimilarityWeight;
public CacheResult(string candidate, bool areSimilar, double similarityWeight)
{
CandidateText = candidate;
AreSimilar = areSimilar;
SimilarityWeight = similarityWeight;
}
}
// Cache the result of the last call to AreSimilar. We'll often be called with the same
// value multiple times in a row, so we can avoid expensive computation by returning the
// same value immediately.
private CacheResult _lastAreSimilarResult;
private string _source;
private EditDistance _editDistance;
private int _threshold;
/// <summary>
/// Whether or words should be considered similar if one is contained within the other
/// (regardless of edit distance). For example if is true then IService would be considered
/// similar to IServiceFactory despite the edit distance being quite high at 7.
/// </summary>
private bool _substringsAreSimilar;
private static readonly object s_poolGate = new();
private static readonly Stack<WordSimilarityChecker> s_pool = new();
public static WordSimilarityChecker Allocate(string text, bool substringsAreSimilar)
{
WordSimilarityChecker checker;
lock (s_poolGate)
{
checker = s_pool.Count > 0
? s_pool.Pop()
: new WordSimilarityChecker();
}
checker.Initialize(text, substringsAreSimilar);
return checker;
}
private WordSimilarityChecker()
{
// These are initialized by 'Initialize'
_source = null!;
_editDistance = null!;
}
private void Initialize(string text, bool substringsAreSimilar)
{
_source = text ?? throw new ArgumentNullException(nameof(text));
_threshold = GetThreshold(_source);
_editDistance = new EditDistance(text);
_substringsAreSimilar = substringsAreSimilar;
}
public void Free()
{
_editDistance?.Dispose();
_source = null!;
_editDistance = null!;
_lastAreSimilarResult = default;
lock (s_poolGate)
{
s_pool.Push(this);
}
}
public static bool AreSimilar(string originalText, string candidateText)
=> AreSimilar(originalText, candidateText, substringsAreSimilar: false);
public static bool AreSimilar(string originalText, string candidateText, bool substringsAreSimilar)
=> AreSimilar(originalText, candidateText, substringsAreSimilar, out _);
public static bool AreSimilar(string originalText, string candidateText, out double similarityWeight)
{
return AreSimilar(
originalText, candidateText,
substringsAreSimilar: false, similarityWeight: out similarityWeight);
}
/// <summary>
/// Returns true if 'originalText' and 'candidateText' are likely a misspelling of each other.
/// Returns false otherwise. If it is a likely misspelling a similarityWeight is provided
/// to help rank the match. Lower costs mean it was a better match.
/// </summary>
public static bool AreSimilar(string originalText, string candidateText, bool substringsAreSimilar, out double similarityWeight)
{
var checker = Allocate(originalText, substringsAreSimilar);
var result = checker.AreSimilar(candidateText, out similarityWeight);
checker.Free();
return result;
}
internal static int GetThreshold(string value)
=> value.Length <= 4 ? 1 : 2;
public bool AreSimilar(string candidateText)
=> AreSimilar(candidateText, out _);
public bool AreSimilar(string candidateText, out double similarityWeight)
{
if (_source.Length < 3)
{
// If we're comparing strings that are too short, we'll find
// far too many spurious hits. Don't even bother in this case.
similarityWeight = double.MaxValue;
return false;
}
if (_lastAreSimilarResult.CandidateText == candidateText)
{
similarityWeight = _lastAreSimilarResult.SimilarityWeight;
return _lastAreSimilarResult.AreSimilar;
}
var result = AreSimilarWorker(candidateText, out similarityWeight);
_lastAreSimilarResult = new CacheResult(candidateText, result, similarityWeight);
return result;
}
private bool AreSimilarWorker(string candidateText, out double similarityWeight)
{
similarityWeight = double.MaxValue;
// If the two strings differ by more characters than the cost threshold, then there's
// no point in even computing the edit distance as it would necessarily take at least
// that many additions/deletions.
if (Math.Abs(_source.Length - candidateText.Length) <= _threshold)
{
similarityWeight = _editDistance.GetEditDistance(candidateText, _threshold);
}
if (similarityWeight > _threshold)
{
// it had a high cost. However, the string the user typed was contained
// in the string we're currently looking at. That's enough to consider it
// although we place it just at the threshold (i.e. it's worse than all
// other matches).
if (_substringsAreSimilar && candidateText.IndexOf(_source, StringComparison.OrdinalIgnoreCase) >= 0)
{
similarityWeight = _threshold;
}
else
{
return false;
}
}
Debug.Assert(similarityWeight <= _threshold);
similarityWeight += Penalty(candidateText, _source);
return true;
}
private static double Penalty(string candidateText, string originalText)
{
var lengthDifference = Math.Abs(originalText.Length - candidateText.Length);
if (lengthDifference != 0)
{
// For all items of the same edit cost, we penalize those that are
// much longer than the original text versus those that are only
// a little longer.
//
// Note: even with this penalty, all matches of cost 'X' will all still
// cost less than matches of cost 'X + 1'. i.e. the penalty is in the
// range [0, 1) and only serves to order matches of the same cost.
//
// Here's the relation of the first few values of length diff and penalty:
// LengthDiff -> Penalty
// 1 -> .5
// 2 -> .66
// 3 -> .75
// 4 -> .8
// And so on and so forth.
var penalty = 1.0 - (1.0 / (lengthDifference + 1));
return penalty;
}
return 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Roslyn.Utilities
{
internal class WordSimilarityChecker
{
private struct CacheResult
{
public readonly string CandidateText;
public readonly bool AreSimilar;
public readonly double SimilarityWeight;
public CacheResult(string candidate, bool areSimilar, double similarityWeight)
{
CandidateText = candidate;
AreSimilar = areSimilar;
SimilarityWeight = similarityWeight;
}
}
// Cache the result of the last call to AreSimilar. We'll often be called with the same
// value multiple times in a row, so we can avoid expensive computation by returning the
// same value immediately.
private CacheResult _lastAreSimilarResult;
private string _source;
private EditDistance _editDistance;
private int _threshold;
/// <summary>
/// Whether or words should be considered similar if one is contained within the other
/// (regardless of edit distance). For example if is true then IService would be considered
/// similar to IServiceFactory despite the edit distance being quite high at 7.
/// </summary>
private bool _substringsAreSimilar;
private static readonly object s_poolGate = new();
private static readonly Stack<WordSimilarityChecker> s_pool = new();
public static WordSimilarityChecker Allocate(string text, bool substringsAreSimilar)
{
WordSimilarityChecker checker;
lock (s_poolGate)
{
checker = s_pool.Count > 0
? s_pool.Pop()
: new WordSimilarityChecker();
}
checker.Initialize(text, substringsAreSimilar);
return checker;
}
private WordSimilarityChecker()
{
// These are initialized by 'Initialize'
_source = null!;
_editDistance = null!;
}
private void Initialize(string text, bool substringsAreSimilar)
{
_source = text ?? throw new ArgumentNullException(nameof(text));
_threshold = GetThreshold(_source);
_editDistance = new EditDistance(text);
_substringsAreSimilar = substringsAreSimilar;
}
public void Free()
{
_editDistance?.Dispose();
_source = null!;
_editDistance = null!;
_lastAreSimilarResult = default;
lock (s_poolGate)
{
s_pool.Push(this);
}
}
public static bool AreSimilar(string originalText, string candidateText)
=> AreSimilar(originalText, candidateText, substringsAreSimilar: false);
public static bool AreSimilar(string originalText, string candidateText, bool substringsAreSimilar)
=> AreSimilar(originalText, candidateText, substringsAreSimilar, out _);
public static bool AreSimilar(string originalText, string candidateText, out double similarityWeight)
{
return AreSimilar(
originalText, candidateText,
substringsAreSimilar: false, similarityWeight: out similarityWeight);
}
/// <summary>
/// Returns true if 'originalText' and 'candidateText' are likely a misspelling of each other.
/// Returns false otherwise. If it is a likely misspelling a similarityWeight is provided
/// to help rank the match. Lower costs mean it was a better match.
/// </summary>
public static bool AreSimilar(string originalText, string candidateText, bool substringsAreSimilar, out double similarityWeight)
{
var checker = Allocate(originalText, substringsAreSimilar);
var result = checker.AreSimilar(candidateText, out similarityWeight);
checker.Free();
return result;
}
internal static int GetThreshold(string value)
=> value.Length <= 4 ? 1 : 2;
public bool AreSimilar(string candidateText)
=> AreSimilar(candidateText, out _);
public bool AreSimilar(string candidateText, out double similarityWeight)
{
if (_source.Length < 3)
{
// If we're comparing strings that are too short, we'll find
// far too many spurious hits. Don't even bother in this case.
similarityWeight = double.MaxValue;
return false;
}
if (_lastAreSimilarResult.CandidateText == candidateText)
{
similarityWeight = _lastAreSimilarResult.SimilarityWeight;
return _lastAreSimilarResult.AreSimilar;
}
var result = AreSimilarWorker(candidateText, out similarityWeight);
_lastAreSimilarResult = new CacheResult(candidateText, result, similarityWeight);
return result;
}
private bool AreSimilarWorker(string candidateText, out double similarityWeight)
{
similarityWeight = double.MaxValue;
// If the two strings differ by more characters than the cost threshold, then there's
// no point in even computing the edit distance as it would necessarily take at least
// that many additions/deletions.
if (Math.Abs(_source.Length - candidateText.Length) <= _threshold)
{
similarityWeight = _editDistance.GetEditDistance(candidateText, _threshold);
}
if (similarityWeight > _threshold)
{
// it had a high cost. However, the string the user typed was contained
// in the string we're currently looking at. That's enough to consider it
// although we place it just at the threshold (i.e. it's worse than all
// other matches).
if (_substringsAreSimilar && candidateText.IndexOf(_source, StringComparison.OrdinalIgnoreCase) >= 0)
{
similarityWeight = _threshold;
}
else
{
return false;
}
}
Debug.Assert(similarityWeight <= _threshold);
similarityWeight += Penalty(candidateText, _source);
return true;
}
private static double Penalty(string candidateText, string originalText)
{
var lengthDifference = Math.Abs(originalText.Length - candidateText.Length);
if (lengthDifference != 0)
{
// For all items of the same edit cost, we penalize those that are
// much longer than the original text versus those that are only
// a little longer.
//
// Note: even with this penalty, all matches of cost 'X' will all still
// cost less than matches of cost 'X + 1'. i.e. the penalty is in the
// range [0, 1) and only serves to order matches of the same cost.
//
// Here's the relation of the first few values of length diff and penalty:
// LengthDiff -> Penalty
// 1 -> .5
// 2 -> .66
// 3 -> .75
// 4 -> .8
// And so on and so forth.
var penalty = 1.0 - (1.0 / (lengthDifference + 1));
return penalty;
}
return 0;
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/VisualStudio/Core/Def/Implementation/Utilities/VisualStudioNavigateToLinkService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
{
[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host)]
[Shared]
internal sealed class VisualStudioNavigateToLinkService : INavigateToLinkService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioNavigateToLinkService()
{
}
public Task<bool> TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken)
{
if (!uri.IsAbsoluteUri)
{
return SpecializedTasks.False;
}
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
{
return SpecializedTasks.False;
}
StartBrowser(uri);
return SpecializedTasks.True;
}
public static void StartBrowser(string uri)
=> VsShellUtilities.OpenSystemBrowser(uri);
public static void StartBrowser(Uri uri)
=> VsShellUtilities.OpenSystemBrowser(uri.AbsoluteUri);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
{
[ExportWorkspaceService(typeof(INavigateToLinkService), layer: ServiceLayer.Host)]
[Shared]
internal sealed class VisualStudioNavigateToLinkService : INavigateToLinkService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioNavigateToLinkService()
{
}
public Task<bool> TryNavigateToLinkAsync(Uri uri, CancellationToken cancellationToken)
{
if (!uri.IsAbsoluteUri)
{
return SpecializedTasks.False;
}
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
{
return SpecializedTasks.False;
}
StartBrowser(uri);
return SpecializedTasks.True;
}
public static void StartBrowser(string uri)
=> VsShellUtilities.OpenSystemBrowser(uri);
public static void StartBrowser(Uri uri)
=> VsShellUtilities.OpenSystemBrowser(uri.AbsoluteUri);
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/IOptionWithGroup.cs | // Licensed to the .NET Foundation under one or more 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.Options
{
/// <summary>
/// Group/sub-feature associated with an <see cref="IOption2"/>.
/// </summary>
internal interface IOptionWithGroup : IOption2
{
/// <summary>
/// Group/sub-feature for this option.
/// </summary>
OptionGroup Group { 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.
namespace Microsoft.CodeAnalysis.Options
{
/// <summary>
/// Group/sub-feature associated with an <see cref="IOption2"/>.
/// </summary>
internal interface IOptionWithGroup : IOption2
{
/// <summary>
/// Group/sub-feature for this option.
/// </summary>
OptionGroup Group { get; }
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_TupleBinaryOperator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
/// <summary>
/// Rewrite <c>GetTuple() == (1, 2)</c> to <c>tuple.Item1 == 1 && tuple.Item2 == 2</c>.
/// Also supports the != operator, nullable and nested tuples.
///
/// Note that all the side-effects for visible expressions are evaluated first and from left to right. The initialization phase
/// contains side-effects for:
/// - single elements in tuple literals, like <c>a</c> in <c>(a, ...) == (...)</c> for example
/// - nested expressions that aren't tuple literals, like <c>GetTuple()</c> in <c>(..., GetTuple()) == (..., (..., ...))</c>
/// On the other hand, <c>Item1</c> and <c>Item2</c> of <c>GetTuple()</c> are not saved as part of the initialization phase of <c>GetTuple() == (..., ...)</c>
///
/// Element-wise conversions occur late, together with the element-wise comparisons. They might not be evaluated.
/// </summary>
public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node)
{
var boolType = node.Type; // we can re-use the bool type
var initEffects = ArrayBuilder<BoundExpression>.GetInstance();
var temps = ArrayBuilder<LocalSymbol>.GetInstance();
BoundExpression newLeft = ReplaceTerminalElementsWithTemps(node.Left, node.Operators, initEffects, temps);
BoundExpression newRight = ReplaceTerminalElementsWithTemps(node.Right, node.Operators, initEffects, temps);
var returnValue = RewriteTupleNestedOperators(node.Operators, newLeft, newRight, boolType, temps, node.OperatorKind);
BoundExpression result = _factory.Sequence(temps.ToImmutableAndFree(), initEffects.ToImmutableAndFree(), returnValue);
return result;
}
private bool IsLikeTupleExpression(BoundExpression expr, [NotNullWhen(true)] out BoundTupleExpression? tuple)
{
switch (expr)
{
case BoundTupleExpression t:
tuple = t;
return true;
case BoundConversion { Conversion: { Kind: ConversionKind.Identity }, Operand: var o }:
return IsLikeTupleExpression(o, out tuple);
case BoundConversion { Conversion: { Kind: ConversionKind.ImplicitTupleLiteral }, Operand: var o }:
// The compiler produces the implicit tuple literal conversion as an identity conversion for
// the benefit of the semantic model only.
Debug.Assert(expr.Type == (object?)o.Type || expr.Type is { } && expr.Type.Equals(o.Type, TypeCompareKind.AllIgnoreOptions));
return IsLikeTupleExpression(o, out tuple);
case BoundConversion { Conversion: { Kind: var kind } c, Operand: var o } conversion when
c.IsTupleConversion || c.IsTupleLiteralConversion:
{
// Push tuple conversions down to the elements.
if (!IsLikeTupleExpression(o, out tuple)) return false;
var underlyingConversions = c.UnderlyingConversions;
var resultTypes = conversion.Type.TupleElementTypesWithAnnotations;
var builder = ArrayBuilder<BoundExpression>.GetInstance(tuple.Arguments.Length);
for (int i = 0; i < tuple.Arguments.Length; i++)
{
var element = tuple.Arguments[i];
var elementConversion = underlyingConversions[i];
var elementType = resultTypes[i].Type;
var newArgument = new BoundConversion(
syntax: expr.Syntax,
operand: element,
conversion: elementConversion,
@checked: conversion.Checked,
explicitCastInCode: conversion.ExplicitCastInCode,
conversionGroupOpt: null,
constantValueOpt: null,
type: elementType,
hasErrors: conversion.HasErrors);
builder.Add(newArgument);
}
var newArguments = builder.ToImmutableAndFree();
tuple = new BoundConvertedTupleLiteral(
tuple.Syntax, sourceTuple: null, wasTargetTyped: true, newArguments, ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, conversion.Type, conversion.HasErrors);
return true;
}
case BoundConversion { Conversion: { Kind: var kind }, Operand: var o } when
(kind == ConversionKind.ImplicitNullable || kind == ConversionKind.ExplicitNullable) &&
expr.Type is { } exprType && exprType.IsNullableType() && exprType.StrippedType().Equals(o.Type, TypeCompareKind.AllIgnoreOptions):
return IsLikeTupleExpression(o, out tuple);
default:
tuple = null;
return false;
}
}
private BoundExpression PushDownImplicitTupleConversion(
BoundExpression expr,
ArrayBuilder<BoundExpression> initEffects,
ArrayBuilder<LocalSymbol> temps)
{
if (expr is BoundConversion { ConversionKind: ConversionKind.ImplicitTuple, Conversion: var conversion } boundConversion)
{
// We push an implicit tuple converion down to its elements
var syntax = boundConversion.Syntax;
Debug.Assert(expr.Type is { });
var destElementTypes = expr.Type.TupleElementTypesWithAnnotations;
var numElements = destElementTypes.Length;
Debug.Assert(boundConversion.Operand.Type is { });
var srcElementFields = boundConversion.Operand.Type.TupleElements;
var fieldAccessorsBuilder = ArrayBuilder<BoundExpression>.GetInstance(numElements);
var savedTuple = DeferSideEffectingArgumentToTempForTupleEquality(LowerConversions(boundConversion.Operand), initEffects, temps);
var elementConversions = conversion.UnderlyingConversions;
for (int i = 0; i < numElements; i++)
{
var fieldAccess = MakeTupleFieldAccessAndReportUseSiteDiagnostics(savedTuple, syntax, srcElementFields[i]);
var convertedFieldAccess = new BoundConversion(
syntax, fieldAccess, elementConversions[i], boundConversion.Checked, boundConversion.ExplicitCastInCode, null, null, destElementTypes[i].Type, boundConversion.HasErrors);
fieldAccessorsBuilder.Add(convertedFieldAccess);
}
return new BoundConvertedTupleLiteral(
syntax, sourceTuple: null, wasTargetTyped: true, fieldAccessorsBuilder.ToImmutableAndFree(), ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, expr.Type, expr.HasErrors);
}
return expr;
}
/// <summary>
/// Walk down tuple literals and replace all the side-effecting elements that need saving with temps.
/// Expressions that are not tuple literals need saving, as are tuple literals that are involved in
/// a simple comparison rather than a tuple comparison.
/// </summary>
private BoundExpression ReplaceTerminalElementsWithTemps(
BoundExpression expr,
TupleBinaryOperatorInfo operators,
ArrayBuilder<BoundExpression> initEffects,
ArrayBuilder<LocalSymbol> temps)
{
if (operators.InfoKind == TupleBinaryOperatorInfoKind.Multiple)
{
expr = PushDownImplicitTupleConversion(expr, initEffects, temps);
if (IsLikeTupleExpression(expr, out BoundTupleExpression? tuple))
{
// Example:
// in `(expr1, expr2) == (..., ...)` we need to save `expr1` and `expr2`
var multiple = (TupleBinaryOperatorInfo.Multiple)operators;
var builder = ArrayBuilder<BoundExpression>.GetInstance(tuple.Arguments.Length);
for (int i = 0; i < tuple.Arguments.Length; i++)
{
var argument = tuple.Arguments[i];
var newArgument = ReplaceTerminalElementsWithTemps(argument, multiple.Operators[i], initEffects, temps);
builder.Add(newArgument);
}
var newArguments = builder.ToImmutableAndFree();
return new BoundConvertedTupleLiteral(
tuple.Syntax, sourceTuple: null, wasTargetTyped: false, newArguments, ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, tuple.Type, tuple.HasErrors);
}
}
// Examples:
// in `expr == (..., ...)` we need to save `expr` because it's not a tuple literal
// in `(..., expr) == (..., (..., ...))` we need to save `expr` because it is used in a simple comparison
return DeferSideEffectingArgumentToTempForTupleEquality(expr, initEffects, temps);
}
/// <summary>
/// Evaluate side effects into a temp, if necessary. If there is an implicit user-defined
/// conversion operation near the top of the arg, preserve that in the returned expression to be evaluated later.
/// Conversions at the head of the result are unlowered, though the nested arguments within it are lowered.
/// That resulting expression must be passed through <see cref="LowerConversions(BoundExpression)"/> to
/// complete the lowering.
/// </summary>
private BoundExpression DeferSideEffectingArgumentToTempForTupleEquality(
BoundExpression expr,
ArrayBuilder<BoundExpression> effects,
ArrayBuilder<LocalSymbol> temps,
bool enclosingConversionWasExplicit = false)
{
switch (expr)
{
case { ConstantValue: { } }:
return VisitExpression(expr);
case BoundConversion { Conversion: { Kind: ConversionKind.DefaultLiteral } }:
// This conversion can be performed lazily, but need not be saved. It is treated as non-side-effecting.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion { Conversion: { Kind: var conversionKind } conversion } bc when conversionMustBePerformedOnOriginalExpression(bc, conversionKind):
// Some conversions cannot be performed on a copy of the argument and must be done early.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion { Conversion: { IsUserDefined: true } } conv when conv.ExplicitCastInCode || enclosingConversionWasExplicit:
// A user-defined conversion triggered by a cast must be performed early.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion conv:
{
// other conversions are deferred
var deferredOperand = DeferSideEffectingArgumentToTempForTupleEquality(conv.Operand, effects, temps, conv.ExplicitCastInCode || enclosingConversionWasExplicit);
return conv.UpdateOperand(deferredOperand);
}
case BoundObjectCreationExpression { Arguments: { Length: 0 }, Type: { } eType } _ when eType.IsNullableType():
return new BoundLiteral(expr.Syntax, ConstantValue.Null, expr.Type);
case BoundObjectCreationExpression { Arguments: { Length: 1 }, Type: { } eType } creation when eType.IsNullableType():
{
var deferredOperand = DeferSideEffectingArgumentToTempForTupleEquality(
creation.Arguments[0], effects, temps, enclosingConversionWasExplicit: true);
return new BoundConversion(
syntax: expr.Syntax, operand: deferredOperand,
conversion: Conversion.MakeNullableConversion(ConversionKind.ImplicitNullable, Conversion.Identity),
@checked: false, explicitCastInCode: true, conversionGroupOpt: null, constantValueOpt: null,
type: eType, hasErrors: expr.HasErrors);
}
default:
// When in doubt, evaluate early to a temp.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
}
bool conversionMustBePerformedOnOriginalExpression(BoundConversion expr, ConversionKind kind)
{
// These are conversions from-expression that
// must be performed on the original expression, not on a copy of it.
switch (kind)
{
case ConversionKind.AnonymousFunction: // a lambda cannot be saved without a target type
case ConversionKind.MethodGroup: // similarly for a method group
case ConversionKind.InterpolatedString: // an interpolated string must be saved in interpolated form
case ConversionKind.SwitchExpression: // a switch expression must have its arms converted
case ConversionKind.StackAllocToPointerType: // a stack alloc is not well-defined without an enclosing conversion
case ConversionKind.ConditionalExpression: // a conditional expression must have its alternatives converted
case ConversionKind.StackAllocToSpanType:
case ConversionKind.ObjectCreation:
return true;
default:
return false;
}
}
}
private BoundExpression RewriteTupleOperator(TupleBinaryOperatorInfo @operator,
BoundExpression left, BoundExpression right, TypeSymbol boolType,
ArrayBuilder<LocalSymbol> temps, BinaryOperatorKind operatorKind)
{
switch (@operator.InfoKind)
{
case TupleBinaryOperatorInfoKind.Multiple:
return RewriteTupleNestedOperators((TupleBinaryOperatorInfo.Multiple)@operator, left, right, boolType, temps, operatorKind);
case TupleBinaryOperatorInfoKind.Single:
return RewriteTupleSingleOperator((TupleBinaryOperatorInfo.Single)@operator, left, right, boolType, operatorKind);
case TupleBinaryOperatorInfoKind.NullNull:
var nullnull = (TupleBinaryOperatorInfo.NullNull)@operator;
return new BoundLiteral(left.Syntax, ConstantValue.Create(nullnull.Kind == BinaryOperatorKind.Equal), boolType);
default:
throw ExceptionUtilities.UnexpectedValue(@operator.InfoKind);
}
}
private BoundExpression RewriteTupleNestedOperators(TupleBinaryOperatorInfo.Multiple operators, BoundExpression left, BoundExpression right,
TypeSymbol boolType, ArrayBuilder<LocalSymbol> temps, BinaryOperatorKind operatorKind)
{
// If either left or right is nullable, produce:
//
// // outer sequence
// leftHasValue = left.HasValue; (or true if !leftNullable)
// leftHasValue == right.HasValue (or true if !rightNullable)
// ? leftHasValue ? ... inner sequence ... : true/false
// : false/true
//
// where inner sequence is:
// leftValue = left.GetValueOrDefault(); (or left if !leftNullable)
// rightValue = right.GetValueOrDefault(); (or right if !rightNullable)
// ... logical expression using leftValue and rightValue ...
//
// and true/false and false/true depend on operatorKind (== vs. !=)
//
// But if neither is nullable, then just produce the inner sequence.
//
// Note: all the temps are created in a single bucket (rather than different scopes of applicability) for simplicity
var outerEffects = ArrayBuilder<BoundExpression>.GetInstance();
var innerEffects = ArrayBuilder<BoundExpression>.GetInstance();
BoundExpression leftHasValue, leftValue;
bool isLeftNullable;
MakeNullableParts(left, temps, innerEffects, outerEffects, saveHasValue: true, out leftHasValue, out leftValue, out isLeftNullable);
BoundExpression rightHasValue, rightValue;
bool isRightNullable;
// no need for local for right.HasValue since used once
MakeNullableParts(right, temps, innerEffects, outerEffects, saveHasValue: false, out rightHasValue, out rightValue, out isRightNullable);
// Produces:
// ... logical expression using leftValue and rightValue ...
BoundExpression logicalExpression = RewriteNonNullableNestedTupleOperators(operators, leftValue, rightValue, boolType, temps, innerEffects, operatorKind);
// Produces:
// leftValue = left.GetValueOrDefault(); (or left if !leftNullable)
// rightValue = right.GetValueOrDefault(); (or right if !rightNullable)
// ... logical expression using leftValue and rightValue ...
BoundExpression innerSequence = _factory.Sequence(locals: ImmutableArray<LocalSymbol>.Empty, innerEffects.ToImmutableAndFree(), logicalExpression);
if (!isLeftNullable && !isRightNullable)
{
// The outer sequence degenerates when we know that both `leftHasValue` and `rightHasValue` are true
return innerSequence;
}
bool boolValue = operatorKind == BinaryOperatorKind.Equal; // true/false
if (rightHasValue.ConstantValue == ConstantValue.False)
{
// The outer sequence degenerates when we known that `rightHasValue` is false
// Produce: !leftHasValue (or leftHasValue for inequality comparison)
return _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
result: boolValue ? _factory.Not(leftHasValue) : leftHasValue);
}
if (leftHasValue.ConstantValue == ConstantValue.False)
{
// The outer sequence degenerates when we known that `leftHasValue` is false
// Produce: !rightHasValue (or rightHasValue for inequality comparison)
return _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
result: boolValue ? _factory.Not(rightHasValue) : rightHasValue);
}
// outer sequence:
// leftHasValue == rightHasValue
// ? leftHasValue ? ... inner sequence ... : true/false
// : false/true
BoundExpression outerSequence =
_factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
_factory.Conditional(
_factory.Binary(BinaryOperatorKind.Equal, boolType, leftHasValue, rightHasValue),
_factory.Conditional(leftHasValue, innerSequence, MakeBooleanConstant(right.Syntax, boolValue), boolType),
MakeBooleanConstant(right.Syntax, !boolValue),
boolType));
return outerSequence;
}
/// <summary>
/// Produce a <c>.HasValue</c> and a <c>.GetValueOrDefault()</c> for nullable expressions that are neither always null or
/// never null, and functionally equivalent parts for other cases.
/// </summary>
private void MakeNullableParts(BoundExpression expr, ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> innerEffects,
ArrayBuilder<BoundExpression> outerEffects, bool saveHasValue, out BoundExpression hasValue, out BoundExpression value, out bool isNullable)
{
isNullable = !(expr is BoundTupleExpression) && expr.Type is { } && expr.Type.IsNullableType();
if (!isNullable)
{
hasValue = MakeBooleanConstant(expr.Syntax, true);
expr = PushDownImplicitTupleConversion(expr, innerEffects, temps);
value = expr;
return;
}
// Optimization for nullable expressions that are always null
if (NullableNeverHasValue(expr))
{
Debug.Assert(expr.Type is { });
hasValue = MakeBooleanConstant(expr.Syntax, false);
// Since there is no value in this nullable expression, we don't need to construct a `.GetValueOrDefault()`, `default(T)` will suffice
value = new BoundDefaultExpression(expr.Syntax, expr.Type.StrippedType());
return;
}
// Optimization for nullable expressions that are never null
if (NullableAlwaysHasValue(expr) is BoundExpression knownValue)
{
hasValue = MakeBooleanConstant(expr.Syntax, true);
// If a tuple conversion, keep its parts around with deferred conversions.
value = PushDownImplicitTupleConversion(knownValue, innerEffects, temps);
value = LowerConversions(value);
isNullable = false;
return;
}
// Regular nullable expressions
hasValue = makeNullableHasValue(expr);
if (saveHasValue)
{
hasValue = MakeTemp(hasValue, temps, outerEffects);
}
value = MakeValueOrDefaultTemp(expr, temps, innerEffects);
BoundExpression makeNullableHasValue(BoundExpression expr)
{
// Optimize conversions where we can use the HasValue of the underlying
Debug.Assert(expr.Type is { });
switch (expr)
{
case BoundConversion { Conversion: { IsIdentity: true }, Operand: var o }:
return makeNullableHasValue(o);
case BoundConversion { Conversion: { IsNullable: true, UnderlyingConversions: var underlying }, Operand: var o }
when expr.Type.IsNullableType() && o.Type is { } && o.Type.IsNullableType() && !underlying[0].IsUserDefined:
// Note that a user-defined conversion from K to Nullable<R> which may translate
// a non-null K to a null value gives rise to a lifted conversion from Nullable<K> to Nullable<R> with the same property.
// We therefore do not attempt to optimize nullable conversions with an underlying user-defined conversion.
return makeNullableHasValue(o);
default:
return MakeNullableHasValue(expr.Syntax, expr);
}
}
}
private BoundLocal MakeTemp(BoundExpression loweredExpression, ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> effects)
{
BoundLocal temp = _factory.StoreToTemp(loweredExpression, out BoundAssignmentOperator assignmentToTemp);
effects.Add(assignmentToTemp);
temps.Add(temp.LocalSymbol);
return temp;
}
/// <summary>
/// Returns a temp which is initialized with lowered-expression.HasValue
/// </summary>
private BoundExpression MakeValueOrDefaultTemp(
BoundExpression expr,
ArrayBuilder<LocalSymbol> temps,
ArrayBuilder<BoundExpression> effects)
{
// Optimize conversions where we can use the underlying
switch (expr)
{
case BoundConversion { Conversion: { IsIdentity: true }, Operand: var o }:
return MakeValueOrDefaultTemp(o, temps, effects);
case BoundConversion { Conversion: { IsNullable: true, UnderlyingConversions: var nested }, Operand: var o } conv when
expr.Type is { } exprType && exprType.IsNullableType() && o.Type is { } && o.Type.IsNullableType() && nested[0] is { IsTupleConversion: true } tupleConversion:
{
Debug.Assert(expr.Type is { });
var operand = MakeValueOrDefaultTemp(o, temps, effects);
Debug.Assert(operand.Type is { });
var types = expr.Type.GetNullableUnderlyingType().TupleElementTypesWithAnnotations;
int tupleCardinality = operand.Type.TupleElementTypesWithAnnotations.Length;
var underlyingConversions = tupleConversion.UnderlyingConversions;
Debug.Assert(underlyingConversions.Length == tupleCardinality);
var argumentBuilder = ArrayBuilder<BoundExpression>.GetInstance(tupleCardinality);
for (int i = 0; i < tupleCardinality; i++)
{
argumentBuilder.Add(MakeBoundConversion(GetTuplePart(operand, i), underlyingConversions[i], types[i], conv));
}
return new BoundConvertedTupleLiteral(
syntax: operand.Syntax,
sourceTuple: null,
wasTargetTyped: false,
arguments: argumentBuilder.ToImmutableAndFree(),
argumentNamesOpt: ImmutableArray<string?>.Empty,
inferredNamesOpt: ImmutableArray<bool>.Empty,
type: expr.Type,
hasErrors: expr.HasErrors).WithSuppression(expr.IsSuppressed);
throw null;
}
default:
{
BoundExpression valueOrDefaultCall = MakeOptimizedGetValueOrDefault(expr.Syntax, expr);
return MakeTemp(valueOrDefaultCall, temps, effects);
}
}
BoundExpression MakeBoundConversion(BoundExpression expr, Conversion conversion, TypeWithAnnotations type, BoundConversion enclosing)
{
return new BoundConversion(
expr.Syntax, expr, conversion, enclosing.Checked, enclosing.ExplicitCastInCode,
conversionGroupOpt: null, constantValueOpt: null, type: type.Type);
}
}
/// <summary>
/// Produces a chain of equality (or inequality) checks combined logically with AND (or OR)
/// </summary>
private BoundExpression RewriteNonNullableNestedTupleOperators(TupleBinaryOperatorInfo.Multiple operators,
BoundExpression left, BoundExpression right, TypeSymbol type,
ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> effects, BinaryOperatorKind operatorKind)
{
ImmutableArray<TupleBinaryOperatorInfo> nestedOperators = operators.Operators;
BoundExpression? currentResult = null;
for (int i = 0; i < nestedOperators.Length; i++)
{
BoundExpression leftElement = GetTuplePart(left, i);
BoundExpression rightElement = GetTuplePart(right, i);
BoundExpression nextLogicalOperand = RewriteTupleOperator(nestedOperators[i], leftElement, rightElement, type, temps, operatorKind);
if (currentResult is null)
{
currentResult = nextLogicalOperand;
}
else
{
var logicalOperator = operatorKind == BinaryOperatorKind.Equal ? BinaryOperatorKind.LogicalBoolAnd : BinaryOperatorKind.LogicalBoolOr;
currentResult = _factory.Binary(logicalOperator, type, currentResult, nextLogicalOperand);
}
}
Debug.Assert(currentResult is { });
return currentResult;
}
/// <summary>
/// For tuple literals, we just return the element.
/// For expressions with tuple type, we access <c>Item{i+1}</c>.
/// </summary>
private BoundExpression GetTuplePart(BoundExpression tuple, int i)
{
// Example:
// (1, 2) == (1, 2);
if (tuple is BoundTupleExpression tupleExpression)
{
return tupleExpression.Arguments[i];
}
Debug.Assert(tuple.Type is { IsTupleType: true });
// Example:
// t == GetTuple();
// t == ((byte, byte)) (1, 2);
// t == ((short, short))((int, int))(1L, 2L);
return MakeTupleFieldAccessAndReportUseSiteDiagnostics(tuple, tuple.Syntax, tuple.Type.TupleElements[i]);
}
/// <summary>
/// Produce an element-wise comparison and logic to ensure the result is a bool type.
///
/// If an element-wise comparison doesn't return bool, then:
/// - if it is dynamic, we'll do <c>!(comparisonResult.false)</c> or <c>comparisonResult.true</c>
/// - if it implicitly converts to bool, we'll just do the conversion
/// - otherwise, we'll do <c>!(comparisonResult.false)</c> or <c>comparisonResult.true</c> (as we'd do for <c>if</c> or <c>while</c>)
/// </summary>
private BoundExpression RewriteTupleSingleOperator(TupleBinaryOperatorInfo.Single single,
BoundExpression left, BoundExpression right, TypeSymbol boolType, BinaryOperatorKind operatorKind)
{
// We deferred lowering some of the conversions on the operand, even though the
// code below the conversions were lowered. We lower the conversion part now.
left = LowerConversions(left);
right = LowerConversions(right);
if (single.Kind.IsDynamic())
{
// Produce
// !((left == right).op_false)
// (left != right).op_true
BoundExpression dynamicResult = _dynamicFactory.MakeDynamicBinaryOperator(single.Kind, left, right, isCompoundAssignment: false, _compilation.DynamicType).ToExpression();
if (operatorKind == BinaryOperatorKind.Equal)
{
return _factory.Not(MakeUnaryOperator(UnaryOperatorKind.DynamicFalse, left.Syntax, method: null, constrainedToTypeOpt: null, dynamicResult, boolType));
}
else
{
return MakeUnaryOperator(UnaryOperatorKind.DynamicTrue, left.Syntax, method: null, constrainedToTypeOpt: null, dynamicResult, boolType);
}
}
if (left.IsLiteralNull() && right.IsLiteralNull())
{
// For `null == null` this is special-cased during initial binding
return new BoundLiteral(left.Syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.Equal), boolType);
}
BoundExpression binary = MakeBinaryOperator(_factory.Syntax, single.Kind, left, right, single.MethodSymbolOpt?.ReturnType ?? boolType, single.MethodSymbolOpt, single.ConstrainedToTypeOpt);
UnaryOperatorSignature boolOperator = single.BoolOperator;
Conversion boolConversion = single.ConversionForBool;
BoundExpression result;
if (boolOperator.Kind != UnaryOperatorKind.Error)
{
// Produce
// !((left == right).op_false)
// (left != right).op_true
BoundExpression convertedBinary = MakeConversionNode(_factory.Syntax, binary, boolConversion, boolOperator.OperandType, @checked: false);
Debug.Assert(boolOperator.ReturnType.SpecialType == SpecialType.System_Boolean);
result = MakeUnaryOperator(boolOperator.Kind, binary.Syntax, boolOperator.Method, boolOperator.ConstrainedToTypeOpt, convertedBinary, boolType);
if (operatorKind == BinaryOperatorKind.Equal)
{
result = _factory.Not(result);
}
}
else if (!boolConversion.IsIdentity)
{
// Produce
// (bool)(left == right)
// (bool)(left != right)
result = MakeConversionNode(_factory.Syntax, binary, boolConversion, boolType, @checked: false);
}
else
{
result = binary;
}
return result;
}
/// <summary>
/// Lower any conversions appearing near the top of the bound expression, assuming non-conversions
/// appearing below them have already been lowered.
/// </summary>
private BoundExpression LowerConversions(BoundExpression expr)
{
return (expr is BoundConversion conv)
? MakeConversionNode(
oldNodeOpt: conv, syntax: conv.Syntax, rewrittenOperand: LowerConversions(conv.Operand),
conversion: conv.Conversion, @checked: conv.Checked, explicitCastInCode: conv.ExplicitCastInCode,
constantValueOpt: conv.ConstantValue, rewrittenType: conv.Type)
: expr;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
/// <summary>
/// Rewrite <c>GetTuple() == (1, 2)</c> to <c>tuple.Item1 == 1 && tuple.Item2 == 2</c>.
/// Also supports the != operator, nullable and nested tuples.
///
/// Note that all the side-effects for visible expressions are evaluated first and from left to right. The initialization phase
/// contains side-effects for:
/// - single elements in tuple literals, like <c>a</c> in <c>(a, ...) == (...)</c> for example
/// - nested expressions that aren't tuple literals, like <c>GetTuple()</c> in <c>(..., GetTuple()) == (..., (..., ...))</c>
/// On the other hand, <c>Item1</c> and <c>Item2</c> of <c>GetTuple()</c> are not saved as part of the initialization phase of <c>GetTuple() == (..., ...)</c>
///
/// Element-wise conversions occur late, together with the element-wise comparisons. They might not be evaluated.
/// </summary>
public override BoundNode VisitTupleBinaryOperator(BoundTupleBinaryOperator node)
{
var boolType = node.Type; // we can re-use the bool type
var initEffects = ArrayBuilder<BoundExpression>.GetInstance();
var temps = ArrayBuilder<LocalSymbol>.GetInstance();
BoundExpression newLeft = ReplaceTerminalElementsWithTemps(node.Left, node.Operators, initEffects, temps);
BoundExpression newRight = ReplaceTerminalElementsWithTemps(node.Right, node.Operators, initEffects, temps);
var returnValue = RewriteTupleNestedOperators(node.Operators, newLeft, newRight, boolType, temps, node.OperatorKind);
BoundExpression result = _factory.Sequence(temps.ToImmutableAndFree(), initEffects.ToImmutableAndFree(), returnValue);
return result;
}
private bool IsLikeTupleExpression(BoundExpression expr, [NotNullWhen(true)] out BoundTupleExpression? tuple)
{
switch (expr)
{
case BoundTupleExpression t:
tuple = t;
return true;
case BoundConversion { Conversion: { Kind: ConversionKind.Identity }, Operand: var o }:
return IsLikeTupleExpression(o, out tuple);
case BoundConversion { Conversion: { Kind: ConversionKind.ImplicitTupleLiteral }, Operand: var o }:
// The compiler produces the implicit tuple literal conversion as an identity conversion for
// the benefit of the semantic model only.
Debug.Assert(expr.Type == (object?)o.Type || expr.Type is { } && expr.Type.Equals(o.Type, TypeCompareKind.AllIgnoreOptions));
return IsLikeTupleExpression(o, out tuple);
case BoundConversion { Conversion: { Kind: var kind } c, Operand: var o } conversion when
c.IsTupleConversion || c.IsTupleLiteralConversion:
{
// Push tuple conversions down to the elements.
if (!IsLikeTupleExpression(o, out tuple)) return false;
var underlyingConversions = c.UnderlyingConversions;
var resultTypes = conversion.Type.TupleElementTypesWithAnnotations;
var builder = ArrayBuilder<BoundExpression>.GetInstance(tuple.Arguments.Length);
for (int i = 0; i < tuple.Arguments.Length; i++)
{
var element = tuple.Arguments[i];
var elementConversion = underlyingConversions[i];
var elementType = resultTypes[i].Type;
var newArgument = new BoundConversion(
syntax: expr.Syntax,
operand: element,
conversion: elementConversion,
@checked: conversion.Checked,
explicitCastInCode: conversion.ExplicitCastInCode,
conversionGroupOpt: null,
constantValueOpt: null,
type: elementType,
hasErrors: conversion.HasErrors);
builder.Add(newArgument);
}
var newArguments = builder.ToImmutableAndFree();
tuple = new BoundConvertedTupleLiteral(
tuple.Syntax, sourceTuple: null, wasTargetTyped: true, newArguments, ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, conversion.Type, conversion.HasErrors);
return true;
}
case BoundConversion { Conversion: { Kind: var kind }, Operand: var o } when
(kind == ConversionKind.ImplicitNullable || kind == ConversionKind.ExplicitNullable) &&
expr.Type is { } exprType && exprType.IsNullableType() && exprType.StrippedType().Equals(o.Type, TypeCompareKind.AllIgnoreOptions):
return IsLikeTupleExpression(o, out tuple);
default:
tuple = null;
return false;
}
}
private BoundExpression PushDownImplicitTupleConversion(
BoundExpression expr,
ArrayBuilder<BoundExpression> initEffects,
ArrayBuilder<LocalSymbol> temps)
{
if (expr is BoundConversion { ConversionKind: ConversionKind.ImplicitTuple, Conversion: var conversion } boundConversion)
{
// We push an implicit tuple converion down to its elements
var syntax = boundConversion.Syntax;
Debug.Assert(expr.Type is { });
var destElementTypes = expr.Type.TupleElementTypesWithAnnotations;
var numElements = destElementTypes.Length;
Debug.Assert(boundConversion.Operand.Type is { });
var srcElementFields = boundConversion.Operand.Type.TupleElements;
var fieldAccessorsBuilder = ArrayBuilder<BoundExpression>.GetInstance(numElements);
var savedTuple = DeferSideEffectingArgumentToTempForTupleEquality(LowerConversions(boundConversion.Operand), initEffects, temps);
var elementConversions = conversion.UnderlyingConversions;
for (int i = 0; i < numElements; i++)
{
var fieldAccess = MakeTupleFieldAccessAndReportUseSiteDiagnostics(savedTuple, syntax, srcElementFields[i]);
var convertedFieldAccess = new BoundConversion(
syntax, fieldAccess, elementConversions[i], boundConversion.Checked, boundConversion.ExplicitCastInCode, null, null, destElementTypes[i].Type, boundConversion.HasErrors);
fieldAccessorsBuilder.Add(convertedFieldAccess);
}
return new BoundConvertedTupleLiteral(
syntax, sourceTuple: null, wasTargetTyped: true, fieldAccessorsBuilder.ToImmutableAndFree(), ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, expr.Type, expr.HasErrors);
}
return expr;
}
/// <summary>
/// Walk down tuple literals and replace all the side-effecting elements that need saving with temps.
/// Expressions that are not tuple literals need saving, as are tuple literals that are involved in
/// a simple comparison rather than a tuple comparison.
/// </summary>
private BoundExpression ReplaceTerminalElementsWithTemps(
BoundExpression expr,
TupleBinaryOperatorInfo operators,
ArrayBuilder<BoundExpression> initEffects,
ArrayBuilder<LocalSymbol> temps)
{
if (operators.InfoKind == TupleBinaryOperatorInfoKind.Multiple)
{
expr = PushDownImplicitTupleConversion(expr, initEffects, temps);
if (IsLikeTupleExpression(expr, out BoundTupleExpression? tuple))
{
// Example:
// in `(expr1, expr2) == (..., ...)` we need to save `expr1` and `expr2`
var multiple = (TupleBinaryOperatorInfo.Multiple)operators;
var builder = ArrayBuilder<BoundExpression>.GetInstance(tuple.Arguments.Length);
for (int i = 0; i < tuple.Arguments.Length; i++)
{
var argument = tuple.Arguments[i];
var newArgument = ReplaceTerminalElementsWithTemps(argument, multiple.Operators[i], initEffects, temps);
builder.Add(newArgument);
}
var newArguments = builder.ToImmutableAndFree();
return new BoundConvertedTupleLiteral(
tuple.Syntax, sourceTuple: null, wasTargetTyped: false, newArguments, ImmutableArray<string?>.Empty,
ImmutableArray<bool>.Empty, tuple.Type, tuple.HasErrors);
}
}
// Examples:
// in `expr == (..., ...)` we need to save `expr` because it's not a tuple literal
// in `(..., expr) == (..., (..., ...))` we need to save `expr` because it is used in a simple comparison
return DeferSideEffectingArgumentToTempForTupleEquality(expr, initEffects, temps);
}
/// <summary>
/// Evaluate side effects into a temp, if necessary. If there is an implicit user-defined
/// conversion operation near the top of the arg, preserve that in the returned expression to be evaluated later.
/// Conversions at the head of the result are unlowered, though the nested arguments within it are lowered.
/// That resulting expression must be passed through <see cref="LowerConversions(BoundExpression)"/> to
/// complete the lowering.
/// </summary>
private BoundExpression DeferSideEffectingArgumentToTempForTupleEquality(
BoundExpression expr,
ArrayBuilder<BoundExpression> effects,
ArrayBuilder<LocalSymbol> temps,
bool enclosingConversionWasExplicit = false)
{
switch (expr)
{
case { ConstantValue: { } }:
return VisitExpression(expr);
case BoundConversion { Conversion: { Kind: ConversionKind.DefaultLiteral } }:
// This conversion can be performed lazily, but need not be saved. It is treated as non-side-effecting.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion { Conversion: { Kind: var conversionKind } conversion } bc when conversionMustBePerformedOnOriginalExpression(bc, conversionKind):
// Some conversions cannot be performed on a copy of the argument and must be done early.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion { Conversion: { IsUserDefined: true } } conv when conv.ExplicitCastInCode || enclosingConversionWasExplicit:
// A user-defined conversion triggered by a cast must be performed early.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
case BoundConversion conv:
{
// other conversions are deferred
var deferredOperand = DeferSideEffectingArgumentToTempForTupleEquality(conv.Operand, effects, temps, conv.ExplicitCastInCode || enclosingConversionWasExplicit);
return conv.UpdateOperand(deferredOperand);
}
case BoundObjectCreationExpression { Arguments: { Length: 0 }, Type: { } eType } _ when eType.IsNullableType():
return new BoundLiteral(expr.Syntax, ConstantValue.Null, expr.Type);
case BoundObjectCreationExpression { Arguments: { Length: 1 }, Type: { } eType } creation when eType.IsNullableType():
{
var deferredOperand = DeferSideEffectingArgumentToTempForTupleEquality(
creation.Arguments[0], effects, temps, enclosingConversionWasExplicit: true);
return new BoundConversion(
syntax: expr.Syntax, operand: deferredOperand,
conversion: Conversion.MakeNullableConversion(ConversionKind.ImplicitNullable, Conversion.Identity),
@checked: false, explicitCastInCode: true, conversionGroupOpt: null, constantValueOpt: null,
type: eType, hasErrors: expr.HasErrors);
}
default:
// When in doubt, evaluate early to a temp.
return EvaluateSideEffectingArgumentToTemp(expr, effects, temps);
}
bool conversionMustBePerformedOnOriginalExpression(BoundConversion expr, ConversionKind kind)
{
// These are conversions from-expression that
// must be performed on the original expression, not on a copy of it.
switch (kind)
{
case ConversionKind.AnonymousFunction: // a lambda cannot be saved without a target type
case ConversionKind.MethodGroup: // similarly for a method group
case ConversionKind.InterpolatedString: // an interpolated string must be saved in interpolated form
case ConversionKind.SwitchExpression: // a switch expression must have its arms converted
case ConversionKind.StackAllocToPointerType: // a stack alloc is not well-defined without an enclosing conversion
case ConversionKind.ConditionalExpression: // a conditional expression must have its alternatives converted
case ConversionKind.StackAllocToSpanType:
case ConversionKind.ObjectCreation:
return true;
default:
return false;
}
}
}
private BoundExpression RewriteTupleOperator(TupleBinaryOperatorInfo @operator,
BoundExpression left, BoundExpression right, TypeSymbol boolType,
ArrayBuilder<LocalSymbol> temps, BinaryOperatorKind operatorKind)
{
switch (@operator.InfoKind)
{
case TupleBinaryOperatorInfoKind.Multiple:
return RewriteTupleNestedOperators((TupleBinaryOperatorInfo.Multiple)@operator, left, right, boolType, temps, operatorKind);
case TupleBinaryOperatorInfoKind.Single:
return RewriteTupleSingleOperator((TupleBinaryOperatorInfo.Single)@operator, left, right, boolType, operatorKind);
case TupleBinaryOperatorInfoKind.NullNull:
var nullnull = (TupleBinaryOperatorInfo.NullNull)@operator;
return new BoundLiteral(left.Syntax, ConstantValue.Create(nullnull.Kind == BinaryOperatorKind.Equal), boolType);
default:
throw ExceptionUtilities.UnexpectedValue(@operator.InfoKind);
}
}
private BoundExpression RewriteTupleNestedOperators(TupleBinaryOperatorInfo.Multiple operators, BoundExpression left, BoundExpression right,
TypeSymbol boolType, ArrayBuilder<LocalSymbol> temps, BinaryOperatorKind operatorKind)
{
// If either left or right is nullable, produce:
//
// // outer sequence
// leftHasValue = left.HasValue; (or true if !leftNullable)
// leftHasValue == right.HasValue (or true if !rightNullable)
// ? leftHasValue ? ... inner sequence ... : true/false
// : false/true
//
// where inner sequence is:
// leftValue = left.GetValueOrDefault(); (or left if !leftNullable)
// rightValue = right.GetValueOrDefault(); (or right if !rightNullable)
// ... logical expression using leftValue and rightValue ...
//
// and true/false and false/true depend on operatorKind (== vs. !=)
//
// But if neither is nullable, then just produce the inner sequence.
//
// Note: all the temps are created in a single bucket (rather than different scopes of applicability) for simplicity
var outerEffects = ArrayBuilder<BoundExpression>.GetInstance();
var innerEffects = ArrayBuilder<BoundExpression>.GetInstance();
BoundExpression leftHasValue, leftValue;
bool isLeftNullable;
MakeNullableParts(left, temps, innerEffects, outerEffects, saveHasValue: true, out leftHasValue, out leftValue, out isLeftNullable);
BoundExpression rightHasValue, rightValue;
bool isRightNullable;
// no need for local for right.HasValue since used once
MakeNullableParts(right, temps, innerEffects, outerEffects, saveHasValue: false, out rightHasValue, out rightValue, out isRightNullable);
// Produces:
// ... logical expression using leftValue and rightValue ...
BoundExpression logicalExpression = RewriteNonNullableNestedTupleOperators(operators, leftValue, rightValue, boolType, temps, innerEffects, operatorKind);
// Produces:
// leftValue = left.GetValueOrDefault(); (or left if !leftNullable)
// rightValue = right.GetValueOrDefault(); (or right if !rightNullable)
// ... logical expression using leftValue and rightValue ...
BoundExpression innerSequence = _factory.Sequence(locals: ImmutableArray<LocalSymbol>.Empty, innerEffects.ToImmutableAndFree(), logicalExpression);
if (!isLeftNullable && !isRightNullable)
{
// The outer sequence degenerates when we know that both `leftHasValue` and `rightHasValue` are true
return innerSequence;
}
bool boolValue = operatorKind == BinaryOperatorKind.Equal; // true/false
if (rightHasValue.ConstantValue == ConstantValue.False)
{
// The outer sequence degenerates when we known that `rightHasValue` is false
// Produce: !leftHasValue (or leftHasValue for inequality comparison)
return _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
result: boolValue ? _factory.Not(leftHasValue) : leftHasValue);
}
if (leftHasValue.ConstantValue == ConstantValue.False)
{
// The outer sequence degenerates when we known that `leftHasValue` is false
// Produce: !rightHasValue (or rightHasValue for inequality comparison)
return _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
result: boolValue ? _factory.Not(rightHasValue) : rightHasValue);
}
// outer sequence:
// leftHasValue == rightHasValue
// ? leftHasValue ? ... inner sequence ... : true/false
// : false/true
BoundExpression outerSequence =
_factory.Sequence(ImmutableArray<LocalSymbol>.Empty, outerEffects.ToImmutableAndFree(),
_factory.Conditional(
_factory.Binary(BinaryOperatorKind.Equal, boolType, leftHasValue, rightHasValue),
_factory.Conditional(leftHasValue, innerSequence, MakeBooleanConstant(right.Syntax, boolValue), boolType),
MakeBooleanConstant(right.Syntax, !boolValue),
boolType));
return outerSequence;
}
/// <summary>
/// Produce a <c>.HasValue</c> and a <c>.GetValueOrDefault()</c> for nullable expressions that are neither always null or
/// never null, and functionally equivalent parts for other cases.
/// </summary>
private void MakeNullableParts(BoundExpression expr, ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> innerEffects,
ArrayBuilder<BoundExpression> outerEffects, bool saveHasValue, out BoundExpression hasValue, out BoundExpression value, out bool isNullable)
{
isNullable = !(expr is BoundTupleExpression) && expr.Type is { } && expr.Type.IsNullableType();
if (!isNullable)
{
hasValue = MakeBooleanConstant(expr.Syntax, true);
expr = PushDownImplicitTupleConversion(expr, innerEffects, temps);
value = expr;
return;
}
// Optimization for nullable expressions that are always null
if (NullableNeverHasValue(expr))
{
Debug.Assert(expr.Type is { });
hasValue = MakeBooleanConstant(expr.Syntax, false);
// Since there is no value in this nullable expression, we don't need to construct a `.GetValueOrDefault()`, `default(T)` will suffice
value = new BoundDefaultExpression(expr.Syntax, expr.Type.StrippedType());
return;
}
// Optimization for nullable expressions that are never null
if (NullableAlwaysHasValue(expr) is BoundExpression knownValue)
{
hasValue = MakeBooleanConstant(expr.Syntax, true);
// If a tuple conversion, keep its parts around with deferred conversions.
value = PushDownImplicitTupleConversion(knownValue, innerEffects, temps);
value = LowerConversions(value);
isNullable = false;
return;
}
// Regular nullable expressions
hasValue = makeNullableHasValue(expr);
if (saveHasValue)
{
hasValue = MakeTemp(hasValue, temps, outerEffects);
}
value = MakeValueOrDefaultTemp(expr, temps, innerEffects);
BoundExpression makeNullableHasValue(BoundExpression expr)
{
// Optimize conversions where we can use the HasValue of the underlying
Debug.Assert(expr.Type is { });
switch (expr)
{
case BoundConversion { Conversion: { IsIdentity: true }, Operand: var o }:
return makeNullableHasValue(o);
case BoundConversion { Conversion: { IsNullable: true, UnderlyingConversions: var underlying }, Operand: var o }
when expr.Type.IsNullableType() && o.Type is { } && o.Type.IsNullableType() && !underlying[0].IsUserDefined:
// Note that a user-defined conversion from K to Nullable<R> which may translate
// a non-null K to a null value gives rise to a lifted conversion from Nullable<K> to Nullable<R> with the same property.
// We therefore do not attempt to optimize nullable conversions with an underlying user-defined conversion.
return makeNullableHasValue(o);
default:
return MakeNullableHasValue(expr.Syntax, expr);
}
}
}
private BoundLocal MakeTemp(BoundExpression loweredExpression, ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> effects)
{
BoundLocal temp = _factory.StoreToTemp(loweredExpression, out BoundAssignmentOperator assignmentToTemp);
effects.Add(assignmentToTemp);
temps.Add(temp.LocalSymbol);
return temp;
}
/// <summary>
/// Returns a temp which is initialized with lowered-expression.HasValue
/// </summary>
private BoundExpression MakeValueOrDefaultTemp(
BoundExpression expr,
ArrayBuilder<LocalSymbol> temps,
ArrayBuilder<BoundExpression> effects)
{
// Optimize conversions where we can use the underlying
switch (expr)
{
case BoundConversion { Conversion: { IsIdentity: true }, Operand: var o }:
return MakeValueOrDefaultTemp(o, temps, effects);
case BoundConversion { Conversion: { IsNullable: true, UnderlyingConversions: var nested }, Operand: var o } conv when
expr.Type is { } exprType && exprType.IsNullableType() && o.Type is { } && o.Type.IsNullableType() && nested[0] is { IsTupleConversion: true } tupleConversion:
{
Debug.Assert(expr.Type is { });
var operand = MakeValueOrDefaultTemp(o, temps, effects);
Debug.Assert(operand.Type is { });
var types = expr.Type.GetNullableUnderlyingType().TupleElementTypesWithAnnotations;
int tupleCardinality = operand.Type.TupleElementTypesWithAnnotations.Length;
var underlyingConversions = tupleConversion.UnderlyingConversions;
Debug.Assert(underlyingConversions.Length == tupleCardinality);
var argumentBuilder = ArrayBuilder<BoundExpression>.GetInstance(tupleCardinality);
for (int i = 0; i < tupleCardinality; i++)
{
argumentBuilder.Add(MakeBoundConversion(GetTuplePart(operand, i), underlyingConversions[i], types[i], conv));
}
return new BoundConvertedTupleLiteral(
syntax: operand.Syntax,
sourceTuple: null,
wasTargetTyped: false,
arguments: argumentBuilder.ToImmutableAndFree(),
argumentNamesOpt: ImmutableArray<string?>.Empty,
inferredNamesOpt: ImmutableArray<bool>.Empty,
type: expr.Type,
hasErrors: expr.HasErrors).WithSuppression(expr.IsSuppressed);
throw null;
}
default:
{
BoundExpression valueOrDefaultCall = MakeOptimizedGetValueOrDefault(expr.Syntax, expr);
return MakeTemp(valueOrDefaultCall, temps, effects);
}
}
BoundExpression MakeBoundConversion(BoundExpression expr, Conversion conversion, TypeWithAnnotations type, BoundConversion enclosing)
{
return new BoundConversion(
expr.Syntax, expr, conversion, enclosing.Checked, enclosing.ExplicitCastInCode,
conversionGroupOpt: null, constantValueOpt: null, type: type.Type);
}
}
/// <summary>
/// Produces a chain of equality (or inequality) checks combined logically with AND (or OR)
/// </summary>
private BoundExpression RewriteNonNullableNestedTupleOperators(TupleBinaryOperatorInfo.Multiple operators,
BoundExpression left, BoundExpression right, TypeSymbol type,
ArrayBuilder<LocalSymbol> temps, ArrayBuilder<BoundExpression> effects, BinaryOperatorKind operatorKind)
{
ImmutableArray<TupleBinaryOperatorInfo> nestedOperators = operators.Operators;
BoundExpression? currentResult = null;
for (int i = 0; i < nestedOperators.Length; i++)
{
BoundExpression leftElement = GetTuplePart(left, i);
BoundExpression rightElement = GetTuplePart(right, i);
BoundExpression nextLogicalOperand = RewriteTupleOperator(nestedOperators[i], leftElement, rightElement, type, temps, operatorKind);
if (currentResult is null)
{
currentResult = nextLogicalOperand;
}
else
{
var logicalOperator = operatorKind == BinaryOperatorKind.Equal ? BinaryOperatorKind.LogicalBoolAnd : BinaryOperatorKind.LogicalBoolOr;
currentResult = _factory.Binary(logicalOperator, type, currentResult, nextLogicalOperand);
}
}
Debug.Assert(currentResult is { });
return currentResult;
}
/// <summary>
/// For tuple literals, we just return the element.
/// For expressions with tuple type, we access <c>Item{i+1}</c>.
/// </summary>
private BoundExpression GetTuplePart(BoundExpression tuple, int i)
{
// Example:
// (1, 2) == (1, 2);
if (tuple is BoundTupleExpression tupleExpression)
{
return tupleExpression.Arguments[i];
}
Debug.Assert(tuple.Type is { IsTupleType: true });
// Example:
// t == GetTuple();
// t == ((byte, byte)) (1, 2);
// t == ((short, short))((int, int))(1L, 2L);
return MakeTupleFieldAccessAndReportUseSiteDiagnostics(tuple, tuple.Syntax, tuple.Type.TupleElements[i]);
}
/// <summary>
/// Produce an element-wise comparison and logic to ensure the result is a bool type.
///
/// If an element-wise comparison doesn't return bool, then:
/// - if it is dynamic, we'll do <c>!(comparisonResult.false)</c> or <c>comparisonResult.true</c>
/// - if it implicitly converts to bool, we'll just do the conversion
/// - otherwise, we'll do <c>!(comparisonResult.false)</c> or <c>comparisonResult.true</c> (as we'd do for <c>if</c> or <c>while</c>)
/// </summary>
private BoundExpression RewriteTupleSingleOperator(TupleBinaryOperatorInfo.Single single,
BoundExpression left, BoundExpression right, TypeSymbol boolType, BinaryOperatorKind operatorKind)
{
// We deferred lowering some of the conversions on the operand, even though the
// code below the conversions were lowered. We lower the conversion part now.
left = LowerConversions(left);
right = LowerConversions(right);
if (single.Kind.IsDynamic())
{
// Produce
// !((left == right).op_false)
// (left != right).op_true
BoundExpression dynamicResult = _dynamicFactory.MakeDynamicBinaryOperator(single.Kind, left, right, isCompoundAssignment: false, _compilation.DynamicType).ToExpression();
if (operatorKind == BinaryOperatorKind.Equal)
{
return _factory.Not(MakeUnaryOperator(UnaryOperatorKind.DynamicFalse, left.Syntax, method: null, constrainedToTypeOpt: null, dynamicResult, boolType));
}
else
{
return MakeUnaryOperator(UnaryOperatorKind.DynamicTrue, left.Syntax, method: null, constrainedToTypeOpt: null, dynamicResult, boolType);
}
}
if (left.IsLiteralNull() && right.IsLiteralNull())
{
// For `null == null` this is special-cased during initial binding
return new BoundLiteral(left.Syntax, ConstantValue.Create(operatorKind == BinaryOperatorKind.Equal), boolType);
}
BoundExpression binary = MakeBinaryOperator(_factory.Syntax, single.Kind, left, right, single.MethodSymbolOpt?.ReturnType ?? boolType, single.MethodSymbolOpt, single.ConstrainedToTypeOpt);
UnaryOperatorSignature boolOperator = single.BoolOperator;
Conversion boolConversion = single.ConversionForBool;
BoundExpression result;
if (boolOperator.Kind != UnaryOperatorKind.Error)
{
// Produce
// !((left == right).op_false)
// (left != right).op_true
BoundExpression convertedBinary = MakeConversionNode(_factory.Syntax, binary, boolConversion, boolOperator.OperandType, @checked: false);
Debug.Assert(boolOperator.ReturnType.SpecialType == SpecialType.System_Boolean);
result = MakeUnaryOperator(boolOperator.Kind, binary.Syntax, boolOperator.Method, boolOperator.ConstrainedToTypeOpt, convertedBinary, boolType);
if (operatorKind == BinaryOperatorKind.Equal)
{
result = _factory.Not(result);
}
}
else if (!boolConversion.IsIdentity)
{
// Produce
// (bool)(left == right)
// (bool)(left != right)
result = MakeConversionNode(_factory.Syntax, binary, boolConversion, boolType, @checked: false);
}
else
{
result = binary;
}
return result;
}
/// <summary>
/// Lower any conversions appearing near the top of the bound expression, assuming non-conversions
/// appearing below them have already been lowered.
/// </summary>
private BoundExpression LowerConversions(BoundExpression expr)
{
return (expr is BoundConversion conv)
? MakeConversionNode(
oldNodeOpt: conv, syntax: conv.Syntax, rewrittenOperand: LowerConversions(conv.Operand),
conversion: conv.Conversion, @checked: conv.Checked, explicitCastInCode: conv.ExplicitCastInCode,
constantValueOpt: conv.ConstantValue, rewrittenType: conv.Type)
: expr;
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.ReadOnly.Set.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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;
namespace Roslyn.Utilities
{
internal partial class SpecializedCollections
{
private partial class ReadOnly
{
internal class Set<TUnderlying, T> : Collection<TUnderlying, T>, ISet<T>, IReadOnlySet<T>
where TUnderlying : ISet<T>
{
public Set(TUnderlying underlying)
: base(underlying)
{
}
public new bool Add(T item)
{
throw new NotSupportedException();
}
public void ExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
public void IntersectWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
public bool IsProperSubsetOf(IEnumerable<T> other)
{
return Underlying.IsProperSubsetOf(other);
}
public bool IsProperSupersetOf(IEnumerable<T> other)
{
return Underlying.IsProperSupersetOf(other);
}
public bool IsSubsetOf(IEnumerable<T> other)
{
return Underlying.IsSubsetOf(other);
}
public bool IsSupersetOf(IEnumerable<T> other)
{
return Underlying.IsSupersetOf(other);
}
public bool Overlaps(IEnumerable<T> other)
{
return Underlying.Overlaps(other);
}
public bool SetEquals(IEnumerable<T> other)
{
return Underlying.SetEquals(other);
}
public void SymmetricExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
public void UnionWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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;
namespace Roslyn.Utilities
{
internal partial class SpecializedCollections
{
private partial class ReadOnly
{
internal class Set<TUnderlying, T> : Collection<TUnderlying, T>, ISet<T>, IReadOnlySet<T>
where TUnderlying : ISet<T>
{
public Set(TUnderlying underlying)
: base(underlying)
{
}
public new bool Add(T item)
{
throw new NotSupportedException();
}
public void ExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
public void IntersectWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
public bool IsProperSubsetOf(IEnumerable<T> other)
{
return Underlying.IsProperSubsetOf(other);
}
public bool IsProperSupersetOf(IEnumerable<T> other)
{
return Underlying.IsProperSupersetOf(other);
}
public bool IsSubsetOf(IEnumerable<T> other)
{
return Underlying.IsSubsetOf(other);
}
public bool IsSupersetOf(IEnumerable<T> other)
{
return Underlying.IsSupersetOf(other);
}
public bool Overlaps(IEnumerable<T> other)
{
return Underlying.Overlaps(other);
}
public bool SetEquals(IEnumerable<T> other)
{
return Underlying.SetEquals(other);
}
public void SymmetricExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
public void UnionWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/EditorFeatures/Core/Implementation/IntelliSense/IDocumentProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense
{
internal interface IDocumentProvider
{
Document GetDocument(ITextSnapshot snapshot, CancellationToken cancellationToken);
}
internal class DocumentProvider : ForegroundThreadAffinitizedObject, IDocumentProvider
{
public DocumentProvider(IThreadingContext threadingContext)
: base(threadingContext)
{
}
public Document GetDocument(ITextSnapshot snapshot, CancellationToken cancellationToken)
{
AssertIsBackground();
return snapshot.AsText().GetDocumentWithFrozenPartialSemantics(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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense
{
internal interface IDocumentProvider
{
Document GetDocument(ITextSnapshot snapshot, CancellationToken cancellationToken);
}
internal class DocumentProvider : ForegroundThreadAffinitizedObject, IDocumentProvider
{
public DocumentProvider(IThreadingContext threadingContext)
: base(threadingContext)
{
}
public Document GetDocument(ITextSnapshot snapshot, CancellationToken cancellationToken)
{
AssertIsBackground();
return snapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpUseImplicitTypeDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpUseImplicitTypeDiagnosticAnalyzer : CSharpTypeStyleDiagnosticAnalyzerBase
{
private static readonly LocalizableString s_Title =
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_implicit_type), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources));
private static readonly LocalizableString s_Message =
new LocalizableResourceString(nameof(CSharpAnalyzersResources.use_var_instead_of_explicit_type), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources));
protected override CSharpTypeStyleHelper Helper => CSharpUseImplicitTypeHelper.Instance;
public CSharpUseImplicitTypeDiagnosticAnalyzer()
: base(diagnosticId: IDEDiagnosticIds.UseImplicitTypeDiagnosticId,
enforceOnBuild: EnforceOnBuildValues.UseImplicitType,
title: s_Title,
message: s_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.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpUseImplicitTypeDiagnosticAnalyzer : CSharpTypeStyleDiagnosticAnalyzerBase
{
private static readonly LocalizableString s_Title =
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_implicit_type), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources));
private static readonly LocalizableString s_Message =
new LocalizableResourceString(nameof(CSharpAnalyzersResources.use_var_instead_of_explicit_type), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources));
protected override CSharpTypeStyleHelper Helper => CSharpUseImplicitTypeHelper.Instance;
public CSharpUseImplicitTypeDiagnosticAnalyzer()
: base(diagnosticId: IDEDiagnosticIds.UseImplicitTypeDiagnosticId,
enforceOnBuild: EnforceOnBuildValues.UseImplicitType,
title: s_Title,
message: s_Message)
{
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/EditorFeatures/CSharpTest2/Recommendations/AddKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class AddKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterEvent()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAttribute()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRemove()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { remove { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRemoveAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { remove { } [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRemoveBlock()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { set { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAddKeyword()
{
await VerifyAbsenceAsync(
@"class C {
event Goo Bar { add $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAddAccessor()
{
await VerifyAbsenceAsync(
@"class C {
event Goo Bar { add { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInProperty()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { $$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class AddKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterEvent()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAttribute()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRemove()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { remove { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRemoveAndAttribute()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { remove { } [Bar] $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRemoveBlock()
{
await VerifyKeywordAsync(
@"class C {
event Goo Bar { set { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAddKeyword()
{
await VerifyAbsenceAsync(
@"class C {
event Goo Bar { add $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAddAccessor()
{
await VerifyAbsenceAsync(
@"class C {
event Goo Bar { add { } $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInProperty()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { $$");
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Features/LanguageServer/Protocol/CSharpVisualBasicLanguageServerFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using StreamJsonRpc;
namespace Microsoft.CodeAnalysis.LanguageServer
{
[Export(typeof(ILanguageServerFactory)), Shared]
internal class CSharpVisualBasicLanguageServerFactory : ILanguageServerFactory
{
public const string UserVisibleName = "Roslyn Language Server Client";
private readonly RequestDispatcherFactory _dispatcherFactory;
private readonly IAsynchronousOperationListenerProvider _listenerProvider;
private readonly IGlobalOptionService _globalOptions;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpVisualBasicLanguageServerFactory(
RequestDispatcherFactory dispatcherFactory,
IAsynchronousOperationListenerProvider listenerProvider,
IGlobalOptionService globalOptions)
{
_dispatcherFactory = dispatcherFactory;
_listenerProvider = listenerProvider;
_globalOptions = globalOptions;
}
public ILanguageServerTarget Create(
JsonRpc jsonRpc,
ICapabilitiesProvider capabilitiesProvider,
ILspWorkspaceRegistrationService workspaceRegistrationService,
ILspLogger logger)
{
return new LanguageServerTarget(
_dispatcherFactory,
jsonRpc,
capabilitiesProvider,
workspaceRegistrationService,
_globalOptions,
_listenerProvider,
logger,
ProtocolConstants.RoslynLspLanguages,
clientName: null,
userVisibleServerName: UserVisibleName,
telemetryServerTypeName: this.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.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using StreamJsonRpc;
namespace Microsoft.CodeAnalysis.LanguageServer
{
[Export(typeof(ILanguageServerFactory)), Shared]
internal class CSharpVisualBasicLanguageServerFactory : ILanguageServerFactory
{
public const string UserVisibleName = "Roslyn Language Server Client";
private readonly RequestDispatcherFactory _dispatcherFactory;
private readonly IAsynchronousOperationListenerProvider _listenerProvider;
private readonly IGlobalOptionService _globalOptions;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpVisualBasicLanguageServerFactory(
RequestDispatcherFactory dispatcherFactory,
IAsynchronousOperationListenerProvider listenerProvider,
IGlobalOptionService globalOptions)
{
_dispatcherFactory = dispatcherFactory;
_listenerProvider = listenerProvider;
_globalOptions = globalOptions;
}
public ILanguageServerTarget Create(
JsonRpc jsonRpc,
ICapabilitiesProvider capabilitiesProvider,
ILspWorkspaceRegistrationService workspaceRegistrationService,
ILspLogger logger)
{
return new LanguageServerTarget(
_dispatcherFactory,
jsonRpc,
capabilitiesProvider,
workspaceRegistrationService,
_globalOptions,
_listenerProvider,
logger,
ProtocolConstants.RoslynLspLanguages,
clientName: null,
userVisibleServerName: UserVisibleName,
telemetryServerTypeName: this.GetType().Name);
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Tools/ExternalAccess/Razor/RazorAsynchronousOperationListenerWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal readonly struct RazorAsynchronousOperationListenerWrapper
{
private readonly IAsynchronousOperationListener _implementation;
public RazorAsynchronousOperationListenerWrapper(IAsynchronousOperationListener implementation)
{
_implementation = implementation;
}
public IDisposable BeginAsyncOperation(string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
=> _implementation.BeginAsyncOperation(name, tag, filePath, lineNumber);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal readonly struct RazorAsynchronousOperationListenerWrapper
{
private readonly IAsynchronousOperationListener _implementation;
public RazorAsynchronousOperationListenerWrapper(IAsynchronousOperationListener implementation)
{
_implementation = implementation;
}
public IDisposable BeginAsyncOperation(string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
=> _implementation.BeginAsyncOperation(name, tag, filePath, lineNumber);
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Compilers/Core/Portable/MetadataReader/ModuleExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Globalization;
using System.Reflection;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis
{
internal static class ModuleExtensions
{
private const string VTableGapMethodNamePrefix = "_VtblGap";
/// <summary>
/// Returns true if the nested type should be imported.
/// </summary>
public static bool ShouldImportNestedType(this PEModule module, TypeDefinitionHandle typeDef)
{
// Currently, it appears that we must import ALL types, even private ones,
// in order to maintain language semantics. This is because a class may implement
// private interfaces, and we use the interfaces (even if inaccessible) to determine
// conversions. For example:
//
// public class A: IEnumerable<A.X>
// {
// private class X: ICloneable {}
// }
//
// Code compiling against A can convert A to IEnumerable<ICloneable>. Knowing this requires
// importing the type A.X.
return true;
}
/// <summary>
/// Returns true if the field should be imported. Visibility
/// and the value of <paramref name="importOptions"/> are considered
/// </summary>
public static bool ShouldImportField(this PEModule module, FieldDefinitionHandle field, MetadataImportOptions importOptions)
{
try
{
var flags = module.GetFieldDefFlagsOrThrow(field);
return ShouldImportField(flags, importOptions);
}
catch (BadImageFormatException)
{
return true;
}
}
/// <summary>
/// Returns true if the flags represent a field that should be imported.
/// Visibility and the value of <paramref name="importOptions"/> are considered
/// </summary>
public static bool ShouldImportField(FieldAttributes flags, MetadataImportOptions importOptions)
{
switch (flags & FieldAttributes.FieldAccessMask)
{
case FieldAttributes.Private:
case FieldAttributes.PrivateScope:
return importOptions == MetadataImportOptions.All;
case FieldAttributes.Assembly:
return importOptions >= MetadataImportOptions.Internal;
default:
return true;
}
}
/// <summary>
/// Returns true if the method should be imported. Returns false for private methods that are not
/// explicit interface implementations. For other methods, visibility and the value of
/// <paramref name="importOptions"/> are considered.
/// </summary>
public static bool ShouldImportMethod(this PEModule module, TypeDefinitionHandle typeDef, MethodDefinitionHandle methodDef, MetadataImportOptions importOptions)
{
try
{
var flags = module.GetMethodDefFlagsOrThrow(methodDef);
// If the method is virtual, it must be accessible, although
// it may be an explicit (private) interface implementation.
// Otherwise, we need to check the accessibility.
if ((flags & MethodAttributes.Virtual) == 0 && !acceptBasedOnAccessibility(importOptions, flags) &&
((flags & MethodAttributes.Static) == 0 || !isMethodImpl(typeDef, methodDef)))
{
return false;
}
}
catch (BadImageFormatException)
{ }
try
{
// As in the native C# compiler (see IMPORTER::ImportMethod), drop any method prefixed
// with "_VtblGap". They should be impossible to call/implement/etc.
// BREAK: The native VB compiler does not drop such methods, but it produces unverifiable
// code when they are called, so the break is acceptable.
// TODO: Keep some record of vtable gaps (DevDiv #17472).
var name = module.GetMethodDefNameOrThrow(methodDef);
return !name.StartsWith(VTableGapMethodNamePrefix, StringComparison.Ordinal);
}
catch (BadImageFormatException)
{
return true;
}
static bool acceptBasedOnAccessibility(MetadataImportOptions importOptions, MethodAttributes flags)
{
switch (flags & MethodAttributes.MemberAccessMask)
{
case MethodAttributes.Private:
case MethodAttributes.PrivateScope:
if (importOptions != MetadataImportOptions.All)
{
return false;
}
break;
case MethodAttributes.Assembly:
if (importOptions == MetadataImportOptions.Public)
{
return false;
}
break;
}
return true;
}
bool isMethodImpl(TypeDefinitionHandle typeDef, MethodDefinitionHandle methodDef)
{
foreach (var methodImpl in module.GetMethodImplementationsOrThrow(typeDef))
{
module.GetMethodImplPropsOrThrow(methodImpl, out EntityHandle body, out _);
if (body == methodDef)
{
return true;
}
}
return false;
}
}
/// <summary>
/// Returns 0 if method name doesn't represent a v-table gap.
/// Otherwise, returns the gap size.
/// </summary>
public static int GetVTableGapSize(string emittedMethodName)
{
// From IMetaDataEmit::DefineMethod documentation (http://msdn.microsoft.com/en-us/library/ms230861(VS.100).aspx)
// ----------------------
// In the case where one or more slots need to be skipped, such as to preserve parity with a COM interface layout,
// a dummy method is defined to take up the slot or slots in the v-table; set the dwMethodFlags to the mdRTSpecialName
// value of the CorMethodAttr enumeration and specify the name as:
//
// _VtblGap<SequenceNumber><_CountOfSlots>
//
// where SequenceNumber is the sequence number of the method and CountOfSlots is the number of slots to skip in the v-table.
// If CountOfSlots is omitted, 1 is assumed.
// ----------------------
//
// From "Partition II Metadata.doc"
// ----------------------
// For COM Interop, an additional class of method names are permitted:
// _VtblGap<SequenceNumber><_CountOfSlots>
// where <SequenceNumber> and <CountOfSlots> are decimal numbers
// ----------------------
const string prefix = VTableGapMethodNamePrefix;
if (emittedMethodName.StartsWith(prefix, StringComparison.Ordinal))
{
int index;
// Skip the SequenceNumber
for (index = prefix.Length; index < emittedMethodName.Length; index++)
{
if (!char.IsDigit(emittedMethodName, index))
{
break;
}
}
if (index == prefix.Length ||
index >= emittedMethodName.Length - 1 ||
emittedMethodName[index] != '_' ||
!char.IsDigit(emittedMethodName, index + 1))
{
return 1;
}
int countOfSlots;
if (int.TryParse(emittedMethodName.Substring(index + 1), NumberStyles.None, CultureInfo.InvariantCulture, out countOfSlots)
&& countOfSlots > 0)
{
return countOfSlots;
}
return 1;
}
return 0;
}
public static string GetVTableGapName(int sequenceNumber, int countOfSlots)
{
return string.Format("_VtblGap{0}_{1}", sequenceNumber, countOfSlots);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Globalization;
using System.Reflection;
using System.Reflection.Metadata;
namespace Microsoft.CodeAnalysis
{
internal static class ModuleExtensions
{
private const string VTableGapMethodNamePrefix = "_VtblGap";
/// <summary>
/// Returns true if the nested type should be imported.
/// </summary>
public static bool ShouldImportNestedType(this PEModule module, TypeDefinitionHandle typeDef)
{
// Currently, it appears that we must import ALL types, even private ones,
// in order to maintain language semantics. This is because a class may implement
// private interfaces, and we use the interfaces (even if inaccessible) to determine
// conversions. For example:
//
// public class A: IEnumerable<A.X>
// {
// private class X: ICloneable {}
// }
//
// Code compiling against A can convert A to IEnumerable<ICloneable>. Knowing this requires
// importing the type A.X.
return true;
}
/// <summary>
/// Returns true if the field should be imported. Visibility
/// and the value of <paramref name="importOptions"/> are considered
/// </summary>
public static bool ShouldImportField(this PEModule module, FieldDefinitionHandle field, MetadataImportOptions importOptions)
{
try
{
var flags = module.GetFieldDefFlagsOrThrow(field);
return ShouldImportField(flags, importOptions);
}
catch (BadImageFormatException)
{
return true;
}
}
/// <summary>
/// Returns true if the flags represent a field that should be imported.
/// Visibility and the value of <paramref name="importOptions"/> are considered
/// </summary>
public static bool ShouldImportField(FieldAttributes flags, MetadataImportOptions importOptions)
{
switch (flags & FieldAttributes.FieldAccessMask)
{
case FieldAttributes.Private:
case FieldAttributes.PrivateScope:
return importOptions == MetadataImportOptions.All;
case FieldAttributes.Assembly:
return importOptions >= MetadataImportOptions.Internal;
default:
return true;
}
}
/// <summary>
/// Returns true if the method should be imported. Returns false for private methods that are not
/// explicit interface implementations. For other methods, visibility and the value of
/// <paramref name="importOptions"/> are considered.
/// </summary>
public static bool ShouldImportMethod(this PEModule module, TypeDefinitionHandle typeDef, MethodDefinitionHandle methodDef, MetadataImportOptions importOptions)
{
try
{
var flags = module.GetMethodDefFlagsOrThrow(methodDef);
// If the method is virtual, it must be accessible, although
// it may be an explicit (private) interface implementation.
// Otherwise, we need to check the accessibility.
if ((flags & MethodAttributes.Virtual) == 0 && !acceptBasedOnAccessibility(importOptions, flags) &&
((flags & MethodAttributes.Static) == 0 || !isMethodImpl(typeDef, methodDef)))
{
return false;
}
}
catch (BadImageFormatException)
{ }
try
{
// As in the native C# compiler (see IMPORTER::ImportMethod), drop any method prefixed
// with "_VtblGap". They should be impossible to call/implement/etc.
// BREAK: The native VB compiler does not drop such methods, but it produces unverifiable
// code when they are called, so the break is acceptable.
// TODO: Keep some record of vtable gaps (DevDiv #17472).
var name = module.GetMethodDefNameOrThrow(methodDef);
return !name.StartsWith(VTableGapMethodNamePrefix, StringComparison.Ordinal);
}
catch (BadImageFormatException)
{
return true;
}
static bool acceptBasedOnAccessibility(MetadataImportOptions importOptions, MethodAttributes flags)
{
switch (flags & MethodAttributes.MemberAccessMask)
{
case MethodAttributes.Private:
case MethodAttributes.PrivateScope:
if (importOptions != MetadataImportOptions.All)
{
return false;
}
break;
case MethodAttributes.Assembly:
if (importOptions == MetadataImportOptions.Public)
{
return false;
}
break;
}
return true;
}
bool isMethodImpl(TypeDefinitionHandle typeDef, MethodDefinitionHandle methodDef)
{
foreach (var methodImpl in module.GetMethodImplementationsOrThrow(typeDef))
{
module.GetMethodImplPropsOrThrow(methodImpl, out EntityHandle body, out _);
if (body == methodDef)
{
return true;
}
}
return false;
}
}
/// <summary>
/// Returns 0 if method name doesn't represent a v-table gap.
/// Otherwise, returns the gap size.
/// </summary>
public static int GetVTableGapSize(string emittedMethodName)
{
// From IMetaDataEmit::DefineMethod documentation (http://msdn.microsoft.com/en-us/library/ms230861(VS.100).aspx)
// ----------------------
// In the case where one or more slots need to be skipped, such as to preserve parity with a COM interface layout,
// a dummy method is defined to take up the slot or slots in the v-table; set the dwMethodFlags to the mdRTSpecialName
// value of the CorMethodAttr enumeration and specify the name as:
//
// _VtblGap<SequenceNumber><_CountOfSlots>
//
// where SequenceNumber is the sequence number of the method and CountOfSlots is the number of slots to skip in the v-table.
// If CountOfSlots is omitted, 1 is assumed.
// ----------------------
//
// From "Partition II Metadata.doc"
// ----------------------
// For COM Interop, an additional class of method names are permitted:
// _VtblGap<SequenceNumber><_CountOfSlots>
// where <SequenceNumber> and <CountOfSlots> are decimal numbers
// ----------------------
const string prefix = VTableGapMethodNamePrefix;
if (emittedMethodName.StartsWith(prefix, StringComparison.Ordinal))
{
int index;
// Skip the SequenceNumber
for (index = prefix.Length; index < emittedMethodName.Length; index++)
{
if (!char.IsDigit(emittedMethodName, index))
{
break;
}
}
if (index == prefix.Length ||
index >= emittedMethodName.Length - 1 ||
emittedMethodName[index] != '_' ||
!char.IsDigit(emittedMethodName, index + 1))
{
return 1;
}
int countOfSlots;
if (int.TryParse(emittedMethodName.Substring(index + 1), NumberStyles.None, CultureInfo.InvariantCulture, out countOfSlots)
&& countOfSlots > 0)
{
return countOfSlots;
}
return 1;
}
return 0;
}
public static string GetVTableGapName(int sequenceNumber, int countOfSlots)
{
return string.Format("_VtblGap{0}_{1}", sequenceNumber, countOfSlots);
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Features/LanguageServer/Protocol/LspOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.LanguageServer
{
[ExportOptionProvider, Shared]
internal sealed class LspOptions : IOptionProvider
{
private const string LocalRegistryPath = @"Roslyn\Internal\Lsp\";
private const string FeatureName = "LspOptions";
/// <summary>
/// This sets the max list size we will return in response to a completion request.
/// If there are more than this many items, we will set the isIncomplete flag on the returned completion list.
/// </summary>
public static readonly Option2<int> MaxCompletionListSize = new(FeatureName, nameof(MaxCompletionListSize), defaultValue: 1000,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(MaxCompletionListSize)));
// Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef.
public static readonly Option2<bool> LspCompletionFeatureFlag = new(FeatureName, nameof(LspCompletionFeatureFlag), defaultValue: false,
new FeatureFlagStorageLocation("Roslyn.LSP.Completion"));
// Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef.
public static readonly Option2<bool> LspEditorFeatureFlag = new(FeatureName, nameof(LspEditorFeatureFlag), defaultValue: false,
new FeatureFlagStorageLocation("Roslyn.LSP.Editor"));
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
MaxCompletionListSize,
LspCompletionFeatureFlag,
LspEditorFeatureFlag);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LspOptions()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.LanguageServer
{
[ExportOptionProvider, Shared]
internal sealed class LspOptions : IOptionProvider
{
private const string LocalRegistryPath = @"Roslyn\Internal\Lsp\";
private const string FeatureName = "LspOptions";
/// <summary>
/// This sets the max list size we will return in response to a completion request.
/// If there are more than this many items, we will set the isIncomplete flag on the returned completion list.
/// </summary>
public static readonly Option2<int> MaxCompletionListSize = new(FeatureName, nameof(MaxCompletionListSize), defaultValue: 1000,
storageLocation: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(MaxCompletionListSize)));
// Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef.
public static readonly Option2<bool> LspCompletionFeatureFlag = new(FeatureName, nameof(LspCompletionFeatureFlag), defaultValue: false,
new FeatureFlagStorageLocation("Roslyn.LSP.Completion"));
// Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef.
public static readonly Option2<bool> LspEditorFeatureFlag = new(FeatureName, nameof(LspEditorFeatureFlag), defaultValue: false,
new FeatureFlagStorageLocation("Roslyn.LSP.Editor"));
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
MaxCompletionListSize,
LspCompletionFeatureFlag,
LspEditorFeatureFlag);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LspOptions()
{
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/SuppressMessageAttributeState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class SuppressMessageAttributeState
{
private static readonly SmallDictionary<string, TargetScope> s_suppressMessageScopeTypes = new SmallDictionary<string, TargetScope>(StringComparer.OrdinalIgnoreCase)
{
{ string.Empty, TargetScope.None },
{ "module", TargetScope.Module },
{ "namespace", TargetScope.Namespace },
{ "resource", TargetScope.Resource },
{ "type", TargetScope.Type },
{ "member", TargetScope.Member },
{ "namespaceanddescendants", TargetScope.NamespaceAndDescendants }
};
private static bool TryGetTargetScope(SuppressMessageInfo info, out TargetScope scope)
=> s_suppressMessageScopeTypes.TryGetValue(info.Scope ?? string.Empty, out scope);
private readonly Compilation _compilation;
private GlobalSuppressions? _lazyGlobalSuppressions;
private readonly ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>> _localSuppressionsBySymbol;
private StrongBox<ISymbol?>? _lazySuppressMessageAttribute;
private StrongBox<ISymbol?>? _lazyUnconditionalSuppressMessageAttribute;
private class GlobalSuppressions
{
private readonly Dictionary<string, SuppressMessageInfo> _compilationWideSuppressions = new Dictionary<string, SuppressMessageInfo>();
private readonly Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>> _globalSymbolSuppressions = new Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>>();
public void AddCompilationWideSuppression(SuppressMessageInfo info)
{
AddOrUpdate(info, _compilationWideSuppressions);
}
public void AddGlobalSymbolSuppression(ISymbol symbol, SuppressMessageInfo info)
{
Dictionary<string, SuppressMessageInfo>? suppressions;
if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions))
{
AddOrUpdate(info, suppressions);
}
else
{
suppressions = new Dictionary<string, SuppressMessageInfo>() { { info.Id, info } };
_globalSymbolSuppressions.Add(symbol, suppressions);
}
}
public bool HasCompilationWideSuppression(string id, out SuppressMessageInfo info)
{
return _compilationWideSuppressions.TryGetValue(id, out info);
}
public bool HasGlobalSymbolSuppression(ISymbol symbol, string id, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info)
{
Debug.Assert(symbol != null);
Dictionary<string, SuppressMessageInfo>? suppressions;
if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions) &&
suppressions.TryGetValue(id, out info))
{
if (symbol.Kind != SymbolKind.Namespace)
{
return true;
}
if (TryGetTargetScope(info, out TargetScope targetScope))
{
switch (targetScope)
{
case TargetScope.Namespace:
// Special case: Only suppress syntax diagnostics in namespace declarations if the namespace is the closest containing symbol.
// In other words, only apply suppression to the immediately containing namespace declaration and not to its children or parents.
return isImmediatelyContainingSymbol;
case TargetScope.NamespaceAndDescendants:
return true;
}
}
}
info = default(SuppressMessageInfo);
return false;
}
}
internal SuppressMessageAttributeState(Compilation compilation)
{
_compilation = compilation;
_localSuppressionsBySymbol = new ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>>();
}
public Diagnostic ApplySourceSuppressions(Diagnostic diagnostic)
{
if (diagnostic.IsSuppressed)
{
// Diagnostic already has a source suppression.
return diagnostic;
}
SuppressMessageInfo info;
if (IsDiagnosticSuppressed(diagnostic, out info))
{
// Attach the suppression info to the diagnostic.
diagnostic = diagnostic.WithIsSuppressed(true);
}
return diagnostic;
}
public bool IsDiagnosticSuppressed(Diagnostic diagnostic, [NotNullWhen(true)] out AttributeData? suppressingAttribute)
{
SuppressMessageInfo info;
if (IsDiagnosticSuppressed(diagnostic, out info))
{
suppressingAttribute = info.Attribute;
return true;
}
suppressingAttribute = null;
return false;
}
private bool IsDiagnosticSuppressed(Diagnostic diagnostic, out SuppressMessageInfo info)
{
info = default;
if (diagnostic.CustomTags.Contains(WellKnownDiagnosticTags.Compiler))
{
// SuppressMessage attributes do not apply to compiler diagnostics.
return false;
}
var id = diagnostic.Id;
var location = diagnostic.Location;
if (IsDiagnosticGloballySuppressed(id, symbolOpt: null, isImmediatelyContainingSymbol: false, info: out info))
{
return true;
}
// Walk up the syntax tree checking for suppression by any declared symbols encountered
if (location.IsInSource)
{
var model = _compilation.GetSemanticModel(location.SourceTree);
bool inImmediatelyContainingSymbol = true;
for (var node = location.SourceTree.GetRoot().FindNode(location.SourceSpan, getInnermostNodeForTie: true);
node != null;
node = node.Parent)
{
var declaredSymbols = model.GetDeclaredSymbolsForNode(node);
Debug.Assert(declaredSymbols != null);
foreach (var symbol in declaredSymbols)
{
if (symbol.Kind == SymbolKind.Namespace)
{
return hasNamespaceSuppression((INamespaceSymbol)symbol, inImmediatelyContainingSymbol);
}
else if (IsDiagnosticLocallySuppressed(id, symbol, out info) || IsDiagnosticGloballySuppressed(id, symbol, inImmediatelyContainingSymbol, out info))
{
return true;
}
}
if (!declaredSymbols.IsEmpty)
{
inImmediatelyContainingSymbol = false;
}
}
}
return false;
bool hasNamespaceSuppression(INamespaceSymbol namespaceSymbol, bool inImmediatelyContainingSymbol)
{
do
{
if (IsDiagnosticGloballySuppressed(id, namespaceSymbol, inImmediatelyContainingSymbol, out _))
{
return true;
}
namespaceSymbol = namespaceSymbol.ContainingNamespace;
inImmediatelyContainingSymbol = false;
}
while (namespaceSymbol != null);
return false;
}
}
private bool IsDiagnosticGloballySuppressed(string id, ISymbol? symbolOpt, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info)
{
var globalSuppressions = this.DecodeGlobalSuppressMessageAttributes();
return globalSuppressions.HasCompilationWideSuppression(id, out info) ||
symbolOpt != null && globalSuppressions.HasGlobalSymbolSuppression(symbolOpt, id, isImmediatelyContainingSymbol, out info);
}
private bool IsDiagnosticLocallySuppressed(string id, ISymbol symbol, out SuppressMessageInfo info)
{
var suppressions = _localSuppressionsBySymbol.GetOrAdd(symbol, this.DecodeLocalSuppressMessageAttributes);
return suppressions.TryGetValue(id, out info);
}
private ISymbol? SuppressMessageAttribute
{
get
{
if (_lazySuppressMessageAttribute is null)
{
Interlocked.CompareExchange(
ref _lazySuppressMessageAttribute,
new StrongBox<ISymbol?>(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SuppressMessageAttribute")),
null);
}
return _lazySuppressMessageAttribute.Value;
}
}
private ISymbol? UnconditionalSuppressMessageAttribute
{
get
{
if (_lazyUnconditionalSuppressMessageAttribute is null)
{
Interlocked.CompareExchange(
ref _lazyUnconditionalSuppressMessageAttribute,
new StrongBox<ISymbol?>(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute")),
null);
}
return _lazyUnconditionalSuppressMessageAttribute.Value;
}
}
private GlobalSuppressions DecodeGlobalSuppressMessageAttributes()
{
if (_lazyGlobalSuppressions == null)
{
var suppressions = new GlobalSuppressions();
DecodeGlobalSuppressMessageAttributes(_compilation, _compilation.Assembly, suppressions);
foreach (var module in _compilation.Assembly.Modules)
{
DecodeGlobalSuppressMessageAttributes(_compilation, module, suppressions);
}
Interlocked.CompareExchange(ref _lazyGlobalSuppressions, suppressions, null);
}
return _lazyGlobalSuppressions;
}
private bool IsSuppressionAttribute(AttributeData a)
=> a.AttributeClass == SuppressMessageAttribute || a.AttributeClass == UnconditionalSuppressMessageAttribute;
private ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol)
{
var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a));
return DecodeLocalSuppressMessageAttributes(symbol, attributes);
}
private static ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol, IEnumerable<AttributeData> attributes)
{
var builder = ImmutableDictionary.CreateBuilder<string, SuppressMessageInfo>();
foreach (var attribute in attributes)
{
SuppressMessageInfo info;
if (!TryDecodeSuppressMessageAttributeData(attribute, out info))
{
continue;
}
AddOrUpdate(info, builder);
}
return builder.ToImmutable();
}
private static void AddOrUpdate(SuppressMessageInfo info, IDictionary<string, SuppressMessageInfo> builder)
{
// TODO: How should we deal with multiple SuppressMessage attributes, with different suppression info/states?
// For now, we just pick the last attribute, if not suppressed.
SuppressMessageInfo currentInfo;
if (!builder.TryGetValue(info.Id, out currentInfo))
{
builder[info.Id] = info;
}
}
private void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions)
{
Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol);
var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a));
DecodeGlobalSuppressMessageAttributes(compilation, symbol, globalSuppressions, attributes);
}
private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions, IEnumerable<AttributeData> attributes)
{
foreach (var instance in attributes)
{
SuppressMessageInfo info;
if (!TryDecodeSuppressMessageAttributeData(instance, out info))
{
continue;
}
if (TryGetTargetScope(info, out TargetScope scope))
{
if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null)
{
// This suppression is applies to the entire compilation
globalSuppressions.AddCompilationWideSuppression(info);
continue;
}
}
else
{
// Invalid value for scope
continue;
}
// Decode Target
if (info.Target == null)
{
continue;
}
foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope))
{
globalSuppressions.AddGlobalSymbolSuppression(target, info);
}
}
}
internal static ImmutableArray<ISymbol> ResolveTargetSymbols(Compilation compilation, string target, TargetScope scope)
{
switch (scope)
{
case TargetScope.Namespace:
case TargetScope.Type:
case TargetScope.Member:
return new TargetSymbolResolver(compilation, scope, target).Resolve(out _);
case TargetScope.NamespaceAndDescendants:
return ResolveTargetSymbols(compilation, target, TargetScope.Namespace);
default:
return ImmutableArray<ISymbol>.Empty;
}
}
private static bool TryDecodeSuppressMessageAttributeData(AttributeData attribute, out SuppressMessageInfo info)
{
info = default(SuppressMessageInfo);
// We need at least the Category and Id to decode the diagnostic to suppress.
// The only SuppressMessageAttribute constructor requires those two parameters.
if (attribute.CommonConstructorArguments.Length < 2)
{
return false;
}
// Ignore the category parameter because it does not identify the diagnostic
// and category information can be obtained from diagnostics themselves.
info.Id = attribute.CommonConstructorArguments[1].ValueInternal as string;
if (info.Id == null)
{
return false;
}
// Allow an optional human-readable descriptive name on the end of an Id.
// See http://msdn.microsoft.com/en-us/library/ms244717.aspx
var separatorIndex = info.Id.IndexOf(':');
if (separatorIndex != -1)
{
info.Id = info.Id.Remove(separatorIndex);
}
info.Scope = attribute.DecodeNamedArgument<string>("Scope", SpecialType.System_String);
info.Target = attribute.DecodeNamedArgument<string>("Target", SpecialType.System_String);
info.MessageId = attribute.DecodeNamedArgument<string>("MessageId", SpecialType.System_String);
info.Attribute = attribute;
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class SuppressMessageAttributeState
{
private static readonly SmallDictionary<string, TargetScope> s_suppressMessageScopeTypes = new SmallDictionary<string, TargetScope>(StringComparer.OrdinalIgnoreCase)
{
{ string.Empty, TargetScope.None },
{ "module", TargetScope.Module },
{ "namespace", TargetScope.Namespace },
{ "resource", TargetScope.Resource },
{ "type", TargetScope.Type },
{ "member", TargetScope.Member },
{ "namespaceanddescendants", TargetScope.NamespaceAndDescendants }
};
private static bool TryGetTargetScope(SuppressMessageInfo info, out TargetScope scope)
=> s_suppressMessageScopeTypes.TryGetValue(info.Scope ?? string.Empty, out scope);
private readonly Compilation _compilation;
private GlobalSuppressions? _lazyGlobalSuppressions;
private readonly ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>> _localSuppressionsBySymbol;
private StrongBox<ISymbol?>? _lazySuppressMessageAttribute;
private StrongBox<ISymbol?>? _lazyUnconditionalSuppressMessageAttribute;
private class GlobalSuppressions
{
private readonly Dictionary<string, SuppressMessageInfo> _compilationWideSuppressions = new Dictionary<string, SuppressMessageInfo>();
private readonly Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>> _globalSymbolSuppressions = new Dictionary<ISymbol, Dictionary<string, SuppressMessageInfo>>();
public void AddCompilationWideSuppression(SuppressMessageInfo info)
{
AddOrUpdate(info, _compilationWideSuppressions);
}
public void AddGlobalSymbolSuppression(ISymbol symbol, SuppressMessageInfo info)
{
Dictionary<string, SuppressMessageInfo>? suppressions;
if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions))
{
AddOrUpdate(info, suppressions);
}
else
{
suppressions = new Dictionary<string, SuppressMessageInfo>() { { info.Id, info } };
_globalSymbolSuppressions.Add(symbol, suppressions);
}
}
public bool HasCompilationWideSuppression(string id, out SuppressMessageInfo info)
{
return _compilationWideSuppressions.TryGetValue(id, out info);
}
public bool HasGlobalSymbolSuppression(ISymbol symbol, string id, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info)
{
Debug.Assert(symbol != null);
Dictionary<string, SuppressMessageInfo>? suppressions;
if (_globalSymbolSuppressions.TryGetValue(symbol, out suppressions) &&
suppressions.TryGetValue(id, out info))
{
if (symbol.Kind != SymbolKind.Namespace)
{
return true;
}
if (TryGetTargetScope(info, out TargetScope targetScope))
{
switch (targetScope)
{
case TargetScope.Namespace:
// Special case: Only suppress syntax diagnostics in namespace declarations if the namespace is the closest containing symbol.
// In other words, only apply suppression to the immediately containing namespace declaration and not to its children or parents.
return isImmediatelyContainingSymbol;
case TargetScope.NamespaceAndDescendants:
return true;
}
}
}
info = default(SuppressMessageInfo);
return false;
}
}
internal SuppressMessageAttributeState(Compilation compilation)
{
_compilation = compilation;
_localSuppressionsBySymbol = new ConcurrentDictionary<ISymbol, ImmutableDictionary<string, SuppressMessageInfo>>();
}
public Diagnostic ApplySourceSuppressions(Diagnostic diagnostic)
{
if (diagnostic.IsSuppressed)
{
// Diagnostic already has a source suppression.
return diagnostic;
}
SuppressMessageInfo info;
if (IsDiagnosticSuppressed(diagnostic, out info))
{
// Attach the suppression info to the diagnostic.
diagnostic = diagnostic.WithIsSuppressed(true);
}
return diagnostic;
}
public bool IsDiagnosticSuppressed(Diagnostic diagnostic, [NotNullWhen(true)] out AttributeData? suppressingAttribute)
{
SuppressMessageInfo info;
if (IsDiagnosticSuppressed(diagnostic, out info))
{
suppressingAttribute = info.Attribute;
return true;
}
suppressingAttribute = null;
return false;
}
private bool IsDiagnosticSuppressed(Diagnostic diagnostic, out SuppressMessageInfo info)
{
info = default;
if (diagnostic.CustomTags.Contains(WellKnownDiagnosticTags.Compiler))
{
// SuppressMessage attributes do not apply to compiler diagnostics.
return false;
}
var id = diagnostic.Id;
var location = diagnostic.Location;
if (IsDiagnosticGloballySuppressed(id, symbolOpt: null, isImmediatelyContainingSymbol: false, info: out info))
{
return true;
}
// Walk up the syntax tree checking for suppression by any declared symbols encountered
if (location.IsInSource)
{
var model = _compilation.GetSemanticModel(location.SourceTree);
bool inImmediatelyContainingSymbol = true;
for (var node = location.SourceTree.GetRoot().FindNode(location.SourceSpan, getInnermostNodeForTie: true);
node != null;
node = node.Parent)
{
var declaredSymbols = model.GetDeclaredSymbolsForNode(node);
Debug.Assert(declaredSymbols != null);
foreach (var symbol in declaredSymbols)
{
if (symbol.Kind == SymbolKind.Namespace)
{
return hasNamespaceSuppression((INamespaceSymbol)symbol, inImmediatelyContainingSymbol);
}
else if (IsDiagnosticLocallySuppressed(id, symbol, out info) || IsDiagnosticGloballySuppressed(id, symbol, inImmediatelyContainingSymbol, out info))
{
return true;
}
}
if (!declaredSymbols.IsEmpty)
{
inImmediatelyContainingSymbol = false;
}
}
}
return false;
bool hasNamespaceSuppression(INamespaceSymbol namespaceSymbol, bool inImmediatelyContainingSymbol)
{
do
{
if (IsDiagnosticGloballySuppressed(id, namespaceSymbol, inImmediatelyContainingSymbol, out _))
{
return true;
}
namespaceSymbol = namespaceSymbol.ContainingNamespace;
inImmediatelyContainingSymbol = false;
}
while (namespaceSymbol != null);
return false;
}
}
private bool IsDiagnosticGloballySuppressed(string id, ISymbol? symbolOpt, bool isImmediatelyContainingSymbol, out SuppressMessageInfo info)
{
var globalSuppressions = this.DecodeGlobalSuppressMessageAttributes();
return globalSuppressions.HasCompilationWideSuppression(id, out info) ||
symbolOpt != null && globalSuppressions.HasGlobalSymbolSuppression(symbolOpt, id, isImmediatelyContainingSymbol, out info);
}
private bool IsDiagnosticLocallySuppressed(string id, ISymbol symbol, out SuppressMessageInfo info)
{
var suppressions = _localSuppressionsBySymbol.GetOrAdd(symbol, this.DecodeLocalSuppressMessageAttributes);
return suppressions.TryGetValue(id, out info);
}
private ISymbol? SuppressMessageAttribute
{
get
{
if (_lazySuppressMessageAttribute is null)
{
Interlocked.CompareExchange(
ref _lazySuppressMessageAttribute,
new StrongBox<ISymbol?>(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.SuppressMessageAttribute")),
null);
}
return _lazySuppressMessageAttribute.Value;
}
}
private ISymbol? UnconditionalSuppressMessageAttribute
{
get
{
if (_lazyUnconditionalSuppressMessageAttribute is null)
{
Interlocked.CompareExchange(
ref _lazyUnconditionalSuppressMessageAttribute,
new StrongBox<ISymbol?>(_compilation.GetTypeByMetadataName("System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute")),
null);
}
return _lazyUnconditionalSuppressMessageAttribute.Value;
}
}
private GlobalSuppressions DecodeGlobalSuppressMessageAttributes()
{
if (_lazyGlobalSuppressions == null)
{
var suppressions = new GlobalSuppressions();
DecodeGlobalSuppressMessageAttributes(_compilation, _compilation.Assembly, suppressions);
foreach (var module in _compilation.Assembly.Modules)
{
DecodeGlobalSuppressMessageAttributes(_compilation, module, suppressions);
}
Interlocked.CompareExchange(ref _lazyGlobalSuppressions, suppressions, null);
}
return _lazyGlobalSuppressions;
}
private bool IsSuppressionAttribute(AttributeData a)
=> a.AttributeClass == SuppressMessageAttribute || a.AttributeClass == UnconditionalSuppressMessageAttribute;
private ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol)
{
var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a));
return DecodeLocalSuppressMessageAttributes(symbol, attributes);
}
private static ImmutableDictionary<string, SuppressMessageInfo> DecodeLocalSuppressMessageAttributes(ISymbol symbol, IEnumerable<AttributeData> attributes)
{
var builder = ImmutableDictionary.CreateBuilder<string, SuppressMessageInfo>();
foreach (var attribute in attributes)
{
SuppressMessageInfo info;
if (!TryDecodeSuppressMessageAttributeData(attribute, out info))
{
continue;
}
AddOrUpdate(info, builder);
}
return builder.ToImmutable();
}
private static void AddOrUpdate(SuppressMessageInfo info, IDictionary<string, SuppressMessageInfo> builder)
{
// TODO: How should we deal with multiple SuppressMessage attributes, with different suppression info/states?
// For now, we just pick the last attribute, if not suppressed.
SuppressMessageInfo currentInfo;
if (!builder.TryGetValue(info.Id, out currentInfo))
{
builder[info.Id] = info;
}
}
private void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions)
{
Debug.Assert(symbol is IAssemblySymbol || symbol is IModuleSymbol);
var attributes = symbol.GetAttributes().Where(a => IsSuppressionAttribute(a));
DecodeGlobalSuppressMessageAttributes(compilation, symbol, globalSuppressions, attributes);
}
private static void DecodeGlobalSuppressMessageAttributes(Compilation compilation, ISymbol symbol, GlobalSuppressions globalSuppressions, IEnumerable<AttributeData> attributes)
{
foreach (var instance in attributes)
{
SuppressMessageInfo info;
if (!TryDecodeSuppressMessageAttributeData(instance, out info))
{
continue;
}
if (TryGetTargetScope(info, out TargetScope scope))
{
if ((scope == TargetScope.Module || scope == TargetScope.None) && info.Target == null)
{
// This suppression is applies to the entire compilation
globalSuppressions.AddCompilationWideSuppression(info);
continue;
}
}
else
{
// Invalid value for scope
continue;
}
// Decode Target
if (info.Target == null)
{
continue;
}
foreach (var target in ResolveTargetSymbols(compilation, info.Target, scope))
{
globalSuppressions.AddGlobalSymbolSuppression(target, info);
}
}
}
internal static ImmutableArray<ISymbol> ResolveTargetSymbols(Compilation compilation, string target, TargetScope scope)
{
switch (scope)
{
case TargetScope.Namespace:
case TargetScope.Type:
case TargetScope.Member:
return new TargetSymbolResolver(compilation, scope, target).Resolve(out _);
case TargetScope.NamespaceAndDescendants:
return ResolveTargetSymbols(compilation, target, TargetScope.Namespace);
default:
return ImmutableArray<ISymbol>.Empty;
}
}
private static bool TryDecodeSuppressMessageAttributeData(AttributeData attribute, out SuppressMessageInfo info)
{
info = default(SuppressMessageInfo);
// We need at least the Category and Id to decode the diagnostic to suppress.
// The only SuppressMessageAttribute constructor requires those two parameters.
if (attribute.CommonConstructorArguments.Length < 2)
{
return false;
}
// Ignore the category parameter because it does not identify the diagnostic
// and category information can be obtained from diagnostics themselves.
info.Id = attribute.CommonConstructorArguments[1].ValueInternal as string;
if (info.Id == null)
{
return false;
}
// Allow an optional human-readable descriptive name on the end of an Id.
// See http://msdn.microsoft.com/en-us/library/ms244717.aspx
var separatorIndex = info.Id.IndexOf(':');
if (separatorIndex != -1)
{
info.Id = info.Id.Remove(separatorIndex);
}
info.Scope = attribute.DecodeNamedArgument<string>("Scope", SpecialType.System_String);
info.Target = attribute.DecodeNamedArgument<string>("Target", SpecialType.System_String);
info.MessageId = attribute.DecodeNamedArgument<string>("MessageId", SpecialType.System_String);
info.Attribute = attribute;
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Compilers/Core/Portable/StrongName/StrongNameKeys.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
namespace Microsoft.CodeAnalysis
{
internal sealed class StrongNameKeys
{
/// <summary>
/// The strong name key associated with the identity of this assembly.
/// This contains the contents of the user-supplied key file exactly as extracted.
/// </summary>
internal readonly ImmutableArray<byte> KeyPair;
/// <summary>
/// Determines source assembly identity.
/// </summary>
internal readonly ImmutableArray<byte> PublicKey;
/// <summary>
/// The Private key information that will exist if it was a private key file that was parsed.
/// </summary>
internal readonly RSAParameters? PrivateKey;
/// <summary>
/// A diagnostic created in the process of determining the key.
/// </summary>
internal readonly Diagnostic? DiagnosticOpt;
/// <summary>
/// The CSP key container containing the public key used to produce the key,
/// or null if the key was retrieved from <see cref="KeyFilePath"/>.
/// </summary>
/// <remarks>
/// The original value as specified by <see cref="System.Reflection.AssemblyKeyNameAttribute"/> or
/// <see cref="CompilationOptions.CryptoKeyContainer"/>.
/// </remarks>
internal readonly string? KeyContainer;
/// <summary>
/// Original key file path, or null if the key is provided by the <see cref="KeyContainer"/>.
/// </summary>
/// <remarks>
/// The original value as specified by <see cref="System.Reflection.AssemblyKeyFileAttribute"/> or
/// <see cref="CompilationOptions.CryptoKeyFile"/>
/// </remarks>
internal readonly string? KeyFilePath;
/// <summary>
/// True when the assembly contains a <see cref="System.Reflection.AssemblySignatureKeyAttribute"/> value
/// and hence signing requires counter signature verification.
/// </summary>
internal readonly bool HasCounterSignature;
internal static readonly StrongNameKeys None = new StrongNameKeys();
private StrongNameKeys()
{
}
internal StrongNameKeys(Diagnostic diagnostic)
{
Debug.Assert(diagnostic != null);
this.DiagnosticOpt = diagnostic;
}
internal StrongNameKeys(ImmutableArray<byte> keyPair, ImmutableArray<byte> publicKey, RSAParameters? privateKey, string? keyContainerName, string? keyFilePath, bool hasCounterSignature)
{
Debug.Assert(keyContainerName == null || keyPair.IsDefault);
Debug.Assert(keyPair.IsDefault || keyFilePath != null);
this.KeyPair = keyPair;
this.PublicKey = publicKey;
this.PrivateKey = privateKey;
this.KeyContainer = keyContainerName;
this.KeyFilePath = keyFilePath;
this.HasCounterSignature = hasCounterSignature;
}
internal static StrongNameKeys Create(ImmutableArray<byte> publicKey, RSAParameters? privateKey, bool hasCounterSignature, CommonMessageProvider messageProvider)
{
Debug.Assert(!publicKey.IsDefaultOrEmpty);
if (MetadataHelpers.IsValidPublicKey(publicKey))
{
return new StrongNameKeys(keyPair: default, publicKey, privateKey, keyContainerName: null, keyFilePath: null, hasCounterSignature);
}
else
{
return new StrongNameKeys(messageProvider.CreateDiagnostic(messageProvider.ERR_BadCompilationOptionValue, Location.None,
nameof(CompilationOptions.CryptoPublicKey), BitConverter.ToString(publicKey.ToArray())));
}
}
internal static StrongNameKeys Create(string? keyFilePath, CommonMessageProvider messageProvider)
{
if (string.IsNullOrEmpty(keyFilePath))
{
return None;
}
try
{
var fileContent = ImmutableArray.Create(File.ReadAllBytes(keyFilePath));
return CreateHelper(fileContent, keyFilePath, hasCounterSignature: false);
}
catch (IOException ex)
{
return new StrongNameKeys(GetKeyFileError(messageProvider, keyFilePath, ex.Message));
}
}
//Last seen key file blob and corresponding public key.
//In IDE typing scenarios we often need to infer public key from the same
//key file blob repeatedly and it is relatively expensive.
//So we will store last seen blob and corresponding key here.
private static Tuple<ImmutableArray<byte>, ImmutableArray<byte>, RSAParameters?>? s_lastSeenKeyPair;
// Note: Errors are reported by throwing an IOException
internal static StrongNameKeys CreateHelper(ImmutableArray<byte> keyFileContent, string keyFilePath, bool hasCounterSignature)
{
ImmutableArray<byte> keyPair;
ImmutableArray<byte> publicKey;
RSAParameters? privateKey = null;
// Check the key pair cache
var cachedKeyPair = s_lastSeenKeyPair;
if (cachedKeyPair != null && keyFileContent == cachedKeyPair.Item1)
{
keyPair = cachedKeyPair.Item1;
publicKey = cachedKeyPair.Item2;
privateKey = cachedKeyPair.Item3;
}
else
{
if (MetadataHelpers.IsValidPublicKey(keyFileContent))
{
publicKey = keyFileContent;
keyPair = default;
}
else if (CryptoBlobParser.TryParseKey(keyFileContent, out publicKey, out privateKey))
{
keyPair = keyFileContent;
}
else
{
throw new IOException(CodeAnalysisResources.InvalidPublicKey);
}
// Cache the key pair
cachedKeyPair = new Tuple<ImmutableArray<byte>, ImmutableArray<byte>, RSAParameters?>(keyPair, publicKey, privateKey);
Interlocked.Exchange(ref s_lastSeenKeyPair, cachedKeyPair);
}
return new StrongNameKeys(keyPair, publicKey, privateKey, null, keyFilePath, hasCounterSignature);
}
internal static StrongNameKeys Create(StrongNameProvider? providerOpt, string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider)
{
if (string.IsNullOrEmpty(keyFilePath) && string.IsNullOrEmpty(keyContainerName))
{
return None;
}
if (providerOpt == null)
{
var diagnostic = GetError(keyFilePath, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)), messageProvider);
return new StrongNameKeys(diagnostic);
}
return providerOpt.CreateKeys(keyFilePath, keyContainerName, hasCounterSignature, messageProvider);
}
/// <summary>
/// True if the compilation can be signed using these keys.
/// </summary>
internal bool CanSign
{
get
{
return !KeyPair.IsDefault || KeyContainer != null;
}
}
/// <summary>
/// True if a strong name can be created for the compilation using these keys.
/// </summary>
internal bool CanProvideStrongName
{
get
{
return CanSign || !PublicKey.IsDefault;
}
}
internal static Diagnostic GetError(string? keyFilePath, string? keyContainerName, object message, CommonMessageProvider messageProvider)
{
if (keyContainerName != null)
{
return GetContainerError(messageProvider, keyContainerName, message);
}
else
{
Debug.Assert(keyFilePath is object);
return GetKeyFileError(messageProvider, keyFilePath, message);
}
}
internal static Diagnostic GetContainerError(CommonMessageProvider messageProvider, string name, object message)
{
return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyContainerFailure, Location.None, name, message);
}
internal static Diagnostic GetKeyFileError(CommonMessageProvider messageProvider, string path, object message)
{
return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyFileFailure, Location.None, path, message);
}
internal static bool IsValidPublicKeyString(string? publicKey)
{
if (string.IsNullOrEmpty(publicKey) || publicKey.Length % 2 != 0)
{
return false;
}
foreach (char c in publicKey)
{
if (!(c >= '0' && c <= '9') &&
!(c >= 'a' && c <= 'f') &&
!(c >= 'A' && c <= 'F'))
{
return false;
}
}
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
namespace Microsoft.CodeAnalysis
{
internal sealed class StrongNameKeys
{
/// <summary>
/// The strong name key associated with the identity of this assembly.
/// This contains the contents of the user-supplied key file exactly as extracted.
/// </summary>
internal readonly ImmutableArray<byte> KeyPair;
/// <summary>
/// Determines source assembly identity.
/// </summary>
internal readonly ImmutableArray<byte> PublicKey;
/// <summary>
/// The Private key information that will exist if it was a private key file that was parsed.
/// </summary>
internal readonly RSAParameters? PrivateKey;
/// <summary>
/// A diagnostic created in the process of determining the key.
/// </summary>
internal readonly Diagnostic? DiagnosticOpt;
/// <summary>
/// The CSP key container containing the public key used to produce the key,
/// or null if the key was retrieved from <see cref="KeyFilePath"/>.
/// </summary>
/// <remarks>
/// The original value as specified by <see cref="System.Reflection.AssemblyKeyNameAttribute"/> or
/// <see cref="CompilationOptions.CryptoKeyContainer"/>.
/// </remarks>
internal readonly string? KeyContainer;
/// <summary>
/// Original key file path, or null if the key is provided by the <see cref="KeyContainer"/>.
/// </summary>
/// <remarks>
/// The original value as specified by <see cref="System.Reflection.AssemblyKeyFileAttribute"/> or
/// <see cref="CompilationOptions.CryptoKeyFile"/>
/// </remarks>
internal readonly string? KeyFilePath;
/// <summary>
/// True when the assembly contains a <see cref="System.Reflection.AssemblySignatureKeyAttribute"/> value
/// and hence signing requires counter signature verification.
/// </summary>
internal readonly bool HasCounterSignature;
internal static readonly StrongNameKeys None = new StrongNameKeys();
private StrongNameKeys()
{
}
internal StrongNameKeys(Diagnostic diagnostic)
{
Debug.Assert(diagnostic != null);
this.DiagnosticOpt = diagnostic;
}
internal StrongNameKeys(ImmutableArray<byte> keyPair, ImmutableArray<byte> publicKey, RSAParameters? privateKey, string? keyContainerName, string? keyFilePath, bool hasCounterSignature)
{
Debug.Assert(keyContainerName == null || keyPair.IsDefault);
Debug.Assert(keyPair.IsDefault || keyFilePath != null);
this.KeyPair = keyPair;
this.PublicKey = publicKey;
this.PrivateKey = privateKey;
this.KeyContainer = keyContainerName;
this.KeyFilePath = keyFilePath;
this.HasCounterSignature = hasCounterSignature;
}
internal static StrongNameKeys Create(ImmutableArray<byte> publicKey, RSAParameters? privateKey, bool hasCounterSignature, CommonMessageProvider messageProvider)
{
Debug.Assert(!publicKey.IsDefaultOrEmpty);
if (MetadataHelpers.IsValidPublicKey(publicKey))
{
return new StrongNameKeys(keyPair: default, publicKey, privateKey, keyContainerName: null, keyFilePath: null, hasCounterSignature);
}
else
{
return new StrongNameKeys(messageProvider.CreateDiagnostic(messageProvider.ERR_BadCompilationOptionValue, Location.None,
nameof(CompilationOptions.CryptoPublicKey), BitConverter.ToString(publicKey.ToArray())));
}
}
internal static StrongNameKeys Create(string? keyFilePath, CommonMessageProvider messageProvider)
{
if (string.IsNullOrEmpty(keyFilePath))
{
return None;
}
try
{
var fileContent = ImmutableArray.Create(File.ReadAllBytes(keyFilePath));
return CreateHelper(fileContent, keyFilePath, hasCounterSignature: false);
}
catch (IOException ex)
{
return new StrongNameKeys(GetKeyFileError(messageProvider, keyFilePath, ex.Message));
}
}
//Last seen key file blob and corresponding public key.
//In IDE typing scenarios we often need to infer public key from the same
//key file blob repeatedly and it is relatively expensive.
//So we will store last seen blob and corresponding key here.
private static Tuple<ImmutableArray<byte>, ImmutableArray<byte>, RSAParameters?>? s_lastSeenKeyPair;
// Note: Errors are reported by throwing an IOException
internal static StrongNameKeys CreateHelper(ImmutableArray<byte> keyFileContent, string keyFilePath, bool hasCounterSignature)
{
ImmutableArray<byte> keyPair;
ImmutableArray<byte> publicKey;
RSAParameters? privateKey = null;
// Check the key pair cache
var cachedKeyPair = s_lastSeenKeyPair;
if (cachedKeyPair != null && keyFileContent == cachedKeyPair.Item1)
{
keyPair = cachedKeyPair.Item1;
publicKey = cachedKeyPair.Item2;
privateKey = cachedKeyPair.Item3;
}
else
{
if (MetadataHelpers.IsValidPublicKey(keyFileContent))
{
publicKey = keyFileContent;
keyPair = default;
}
else if (CryptoBlobParser.TryParseKey(keyFileContent, out publicKey, out privateKey))
{
keyPair = keyFileContent;
}
else
{
throw new IOException(CodeAnalysisResources.InvalidPublicKey);
}
// Cache the key pair
cachedKeyPair = new Tuple<ImmutableArray<byte>, ImmutableArray<byte>, RSAParameters?>(keyPair, publicKey, privateKey);
Interlocked.Exchange(ref s_lastSeenKeyPair, cachedKeyPair);
}
return new StrongNameKeys(keyPair, publicKey, privateKey, null, keyFilePath, hasCounterSignature);
}
internal static StrongNameKeys Create(StrongNameProvider? providerOpt, string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider)
{
if (string.IsNullOrEmpty(keyFilePath) && string.IsNullOrEmpty(keyContainerName))
{
return None;
}
if (providerOpt == null)
{
var diagnostic = GetError(keyFilePath, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)), messageProvider);
return new StrongNameKeys(diagnostic);
}
return providerOpt.CreateKeys(keyFilePath, keyContainerName, hasCounterSignature, messageProvider);
}
/// <summary>
/// True if the compilation can be signed using these keys.
/// </summary>
internal bool CanSign
{
get
{
return !KeyPair.IsDefault || KeyContainer != null;
}
}
/// <summary>
/// True if a strong name can be created for the compilation using these keys.
/// </summary>
internal bool CanProvideStrongName
{
get
{
return CanSign || !PublicKey.IsDefault;
}
}
internal static Diagnostic GetError(string? keyFilePath, string? keyContainerName, object message, CommonMessageProvider messageProvider)
{
if (keyContainerName != null)
{
return GetContainerError(messageProvider, keyContainerName, message);
}
else
{
Debug.Assert(keyFilePath is object);
return GetKeyFileError(messageProvider, keyFilePath, message);
}
}
internal static Diagnostic GetContainerError(CommonMessageProvider messageProvider, string name, object message)
{
return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyContainerFailure, Location.None, name, message);
}
internal static Diagnostic GetKeyFileError(CommonMessageProvider messageProvider, string path, object message)
{
return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyFileFailure, Location.None, path, message);
}
internal static bool IsValidPublicKeyString(string? publicKey)
{
if (string.IsNullOrEmpty(publicKey) || publicKey.Length % 2 != 0)
{
return false;
}
foreach (char c in publicKey)
{
if (!(c >= '0' && c <= '9') &&
!(c >= 'a' && c <= 'f') &&
!(c >= 'A' && c <= 'F'))
{
return false;
}
}
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Tools/IdeCoreBenchmarks/SegmentedListBenchmarks_InsertRange.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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 BenchmarkDotNet.Attributes;
using Microsoft.CodeAnalysis.Collections;
namespace IdeCoreBenchmarks
{
[DisassemblyDiagnoser]
public class SegmentedListBenchmarks_InsertRange
{
private List<int> _values = null!;
private int[] _insertValues = null!;
private List<object?> _valuesObject = null!;
private object?[] _insertValuesObject = null!;
private Microsoft.CodeAnalysis.Collections.SegmentedList<int> _segmentedValues = null!;
private SegmentedArray<int> _segmentedInsertValues;
private Microsoft.CodeAnalysis.Collections.SegmentedList<object?> _segmentedValuesObject = null!;
private SegmentedArray<object?> _segmentedInsertValuesObject;
[Params(100000)]
public int Count { get; set; }
[GlobalSetup]
public void GlobalSetup()
{
_values = new List<int>(Count);
_valuesObject = new List<object?>(Count);
_segmentedValues = new Microsoft.CodeAnalysis.Collections.SegmentedList<int>(Count);
_segmentedValuesObject = new Microsoft.CodeAnalysis.Collections.SegmentedList<object?>(Count);
_insertValues = new int[100];
_insertValuesObject = new object?[100];
_segmentedInsertValues = new SegmentedArray<int>(100);
_segmentedInsertValuesObject = new SegmentedArray<object?>(100);
}
[Benchmark(Description = "List<int>", Baseline = true)]
public void InsertRangeList()
{
var iterations = Count / 100;
for (var i = 0; i < iterations; i++)
{
_values.InsertRange(0, _insertValues);
}
_values.Clear();
}
[Benchmark(Description = "List<object>")]
public void InsertRangeListObject()
{
var iterations = Count / 100;
for (var i = 0; i < iterations; i++)
{
_valuesObject.InsertRange(0, _insertValuesObject);
}
_valuesObject.Clear();
}
[Benchmark(Description = "SegmentedList<int>")]
public void InsertRangeSegmented()
{
var iterations = Count / 100;
for (var i = 0; i < iterations; i++)
{
_segmentedValues.InsertRange(0, _segmentedInsertValues);
}
_segmentedValues.Clear();
}
[Benchmark(Description = "SegmentedList<object>")]
public void InsertRangeSegmentedObject()
{
var iterations = Count / 100;
for (var i = 0; i < iterations; i++)
{
_segmentedValuesObject.InsertRange(0, _segmentedInsertValuesObject);
}
_segmentedValuesObject.Clear();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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 BenchmarkDotNet.Attributes;
using Microsoft.CodeAnalysis.Collections;
namespace IdeCoreBenchmarks
{
[DisassemblyDiagnoser]
public class SegmentedListBenchmarks_InsertRange
{
private List<int> _values = null!;
private int[] _insertValues = null!;
private List<object?> _valuesObject = null!;
private object?[] _insertValuesObject = null!;
private Microsoft.CodeAnalysis.Collections.SegmentedList<int> _segmentedValues = null!;
private SegmentedArray<int> _segmentedInsertValues;
private Microsoft.CodeAnalysis.Collections.SegmentedList<object?> _segmentedValuesObject = null!;
private SegmentedArray<object?> _segmentedInsertValuesObject;
[Params(100000)]
public int Count { get; set; }
[GlobalSetup]
public void GlobalSetup()
{
_values = new List<int>(Count);
_valuesObject = new List<object?>(Count);
_segmentedValues = new Microsoft.CodeAnalysis.Collections.SegmentedList<int>(Count);
_segmentedValuesObject = new Microsoft.CodeAnalysis.Collections.SegmentedList<object?>(Count);
_insertValues = new int[100];
_insertValuesObject = new object?[100];
_segmentedInsertValues = new SegmentedArray<int>(100);
_segmentedInsertValuesObject = new SegmentedArray<object?>(100);
}
[Benchmark(Description = "List<int>", Baseline = true)]
public void InsertRangeList()
{
var iterations = Count / 100;
for (var i = 0; i < iterations; i++)
{
_values.InsertRange(0, _insertValues);
}
_values.Clear();
}
[Benchmark(Description = "List<object>")]
public void InsertRangeListObject()
{
var iterations = Count / 100;
for (var i = 0; i < iterations; i++)
{
_valuesObject.InsertRange(0, _insertValuesObject);
}
_valuesObject.Clear();
}
[Benchmark(Description = "SegmentedList<int>")]
public void InsertRangeSegmented()
{
var iterations = Count / 100;
for (var i = 0; i < iterations; i++)
{
_segmentedValues.InsertRange(0, _segmentedInsertValues);
}
_segmentedValues.Clear();
}
[Benchmark(Description = "SegmentedList<object>")]
public void InsertRangeSegmentedObject()
{
var iterations = Count / 100;
for (var i = 0; i < iterations; i++)
{
_segmentedValuesObject.InsertRange(0, _segmentedInsertValuesObject);
}
_segmentedValuesObject.Clear();
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Compilers/Core/Portable/CodeGen/ArrayMembers.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.PooledObjects;
using Roslyn.Utilities;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
// Contains support for pseudo-methods on multidimensional arrays.
//
// Opcodes such as newarr, ldelem, ldelema, stelem do not work with
// multidimensional arrays and same functionality is available in
// a form of well known pseudo-methods "Get", "Set", "Address" and ".ctor"
//
//=========================
//
// 14.2 Arrays (From partition II) -
//The class that the VES creates for arrays contains several methods whose implementation is supplied by the
//VES:
//
//* A constructor that takes a sequence of int32 arguments, one for each dimension of the array, that specify
//the number of elements in each dimension beginning with the first dimension. A lower bound of zero is
//assumed.
//
//* A constructor that takes twice as many int32 arguments as there are dimensions of the array. These
//arguments occur in pairs—one pair per dimension—with the first argument of each pair specifying the
//lower bound for that dimension, and the second argument specifying the total number of elements in that
//dimension. Note that vectors are not created with this constructor, since a zero lower bound is assumed for
//vectors.
//
//* A Get method that takes a sequence of int32 arguments, one for each dimension of the array, and returns
//a value whose type is the element type of the array. This method is used to access a specific element of the
//array where the arguments specify the index into each dimension, beginning with the first, of the element
//to be returned.
//
//* A Set method that takes a sequence of int32 arguments, one for each dimension of the array, followed by
//a value whose type is the element type of the array. The return type of Set is void. This method is used to
//set a specific element of the array where the arguments specify the index into each dimension, beginning
//with the first, of the element to be set and the final argument specifies the value to be stored into the target
//element.
//
//* An Address method that takes a sequence of int32 arguments, one for each dimension of the array, and
//has a return type that is a managed pointer to the array's element type. This method is used to return a
//managed pointer to a specific element of the array where the arguments specify the index into each
//dimension, beginning with the first, of the element whose address is to be returned.
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Constructs and caches already created pseudo-methods.
/// Every compiled module is supposed to have one of this, created lazily
/// (multidimensional arrays are not common).
/// </summary>
internal class ArrayMethods
{
// There are four kinds of array pseudo-methods
// They are specific to a given array type
private enum ArrayMethodKind : byte
{
GET,
SET,
ADDRESS,
CTOR,
}
/// <summary>
/// Acquires an array constructor for a given array type
/// </summary>
public ArrayMethod GetArrayConstructor(Cci.IArrayTypeReference arrayType)
{
return GetArrayMethod(arrayType, ArrayMethodKind.CTOR);
}
/// <summary>
/// Acquires an element getter method for a given array type
/// </summary>
public ArrayMethod GetArrayGet(Cci.IArrayTypeReference arrayType)
=> GetArrayMethod(arrayType, ArrayMethodKind.GET);
/// <summary>
/// Acquires an element setter method for a given array type
/// </summary>
public ArrayMethod GetArraySet(Cci.IArrayTypeReference arrayType)
=> GetArrayMethod(arrayType, ArrayMethodKind.SET);
/// <summary>
/// Acquires an element referencer method for a given array type
/// </summary>
public ArrayMethod GetArrayAddress(Cci.IArrayTypeReference arrayType)
=> GetArrayMethod(arrayType, ArrayMethodKind.ADDRESS);
/// <summary>
/// Maps {array type, method kind} tuples to implementing pseudo-methods.
/// </summary>
private readonly ConcurrentDictionary<(byte methodKind, IReferenceOrISignature arrayType), ArrayMethod> _dict =
new ConcurrentDictionary<(byte, IReferenceOrISignature), ArrayMethod>();
/// <summary>
/// lazily fetches or creates a new array method.
/// </summary>
private ArrayMethod GetArrayMethod(Cci.IArrayTypeReference arrayType, ArrayMethodKind id)
{
var key = ((byte)id, new IReferenceOrISignature(arrayType));
ArrayMethod? result;
var dict = _dict;
if (!dict.TryGetValue(key, out result))
{
result = MakeArrayMethod(arrayType, id);
result = dict.GetOrAdd(key, result);
}
return result;
}
private static ArrayMethod MakeArrayMethod(Cci.IArrayTypeReference arrayType, ArrayMethodKind id)
{
switch (id)
{
case ArrayMethodKind.CTOR:
return new ArrayConstructor(arrayType);
case ArrayMethodKind.GET:
return new ArrayGet(arrayType);
case ArrayMethodKind.SET:
return new ArraySet(arrayType);
case ArrayMethodKind.ADDRESS:
return new ArrayAddress(arrayType);
}
throw ExceptionUtilities.UnexpectedValue(id);
}
/// <summary>
/// "newobj ArrayConstructor" is equivalent of "newarr ElementType"
/// when working with multidimensional arrays
/// </summary>
private sealed class ArrayConstructor : ArrayMethod
{
public ArrayConstructor(Cci.IArrayTypeReference arrayType) : base(arrayType) { }
public override string Name => ".ctor";
public override Cci.ITypeReference GetType(EmitContext context)
=> context.Module.GetPlatformType(Cci.PlatformType.SystemVoid, context);
}
/// <summary>
/// "call ArrayGet" is equivalent of "ldelem ElementType"
/// when working with multidimensional arrays
/// </summary>
private sealed class ArrayGet : ArrayMethod
{
public ArrayGet(Cci.IArrayTypeReference arrayType) : base(arrayType) { }
public override string Name => "Get";
public override Cci.ITypeReference GetType(EmitContext context)
=> arrayType.GetElementType(context);
}
/// <summary>
/// "call ArrayAddress" is equivalent of "ldelema ElementType"
/// when working with multidimensional arrays
/// </summary>
private sealed class ArrayAddress : ArrayMethod
{
public ArrayAddress(Cci.IArrayTypeReference arrayType) : base(arrayType) { }
public override bool ReturnValueIsByRef => true;
public override Cci.ITypeReference GetType(EmitContext context)
=> arrayType.GetElementType(context);
public override string Name => "Address";
}
/// <summary>
/// "call ArraySet" is equivalent of "stelem ElementType"
/// when working with multidimensional arrays
/// </summary>
private sealed class ArraySet : ArrayMethod
{
public ArraySet(Cci.IArrayTypeReference arrayType) : base(arrayType) { }
public override string Name => "Set";
public override Cci.ITypeReference GetType(EmitContext context)
=> context.Module.GetPlatformType(Cci.PlatformType.SystemVoid, context);
protected override ImmutableArray<ArrayMethodParameterInfo> MakeParameters()
{
int rank = (int)arrayType.Rank;
var parameters = ArrayBuilder<ArrayMethodParameterInfo>.GetInstance(rank + 1);
for (int i = 0; i < rank; i++)
{
parameters.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i));
}
parameters.Add(new ArraySetValueParameterInfo((ushort)rank, arrayType));
return parameters.ToImmutableAndFree();
}
}
}
/// <summary>
/// Represents a parameter in an array pseudo-method.
///
/// NOTE: It appears that only number of indices is used for verification,
/// types just have to be Int32.
/// Even though actual arguments can be native ints.
/// </summary>
internal class ArrayMethodParameterInfo : Cci.IParameterTypeInformation
{
// position in the signature
private readonly ushort _index;
// cache common parameter instances
// (we can do this since the only data we have is the index)
private static readonly ArrayMethodParameterInfo s_index0 = new ArrayMethodParameterInfo(0);
private static readonly ArrayMethodParameterInfo s_index1 = new ArrayMethodParameterInfo(1);
private static readonly ArrayMethodParameterInfo s_index2 = new ArrayMethodParameterInfo(2);
private static readonly ArrayMethodParameterInfo s_index3 = new ArrayMethodParameterInfo(3);
protected ArrayMethodParameterInfo(ushort index)
{
_index = index;
}
public static ArrayMethodParameterInfo GetIndexParameter(ushort index)
{
switch (index)
{
case 0: return s_index0;
case 1: return s_index1;
case 2: return s_index2;
case 3: return s_index3;
}
return new ArrayMethodParameterInfo(index);
}
public ImmutableArray<Cci.ICustomModifier> RefCustomModifiers
=> ImmutableArray<Cci.ICustomModifier>.Empty;
public ImmutableArray<Cci.ICustomModifier> CustomModifiers
=> ImmutableArray<Cci.ICustomModifier>.Empty;
public bool IsByReference => false;
public virtual Cci.ITypeReference GetType(EmitContext context)
=> context.Module.GetPlatformType(Cci.PlatformType.SystemInt32, context);
public ushort Index => _index;
}
/// <summary>
/// Represents the "value" parameter of the Set pseudo-method.
///
/// NOTE: unlike index parameters, type of the value parameter must match
/// the actual element type.
/// </summary>
internal sealed class ArraySetValueParameterInfo : ArrayMethodParameterInfo
{
private readonly Cci.IArrayTypeReference _arrayType;
internal ArraySetValueParameterInfo(ushort index, Cci.IArrayTypeReference arrayType)
: base(index)
{
_arrayType = arrayType;
}
public override Cci.ITypeReference GetType(EmitContext context)
=> _arrayType.GetElementType(context);
}
/// <summary>
/// Base of all array methods. They have a lot in common.
/// </summary>
internal abstract class ArrayMethod : Cci.IMethodReference
{
private readonly ImmutableArray<ArrayMethodParameterInfo> _parameters;
protected readonly Cci.IArrayTypeReference arrayType;
protected ArrayMethod(Cci.IArrayTypeReference arrayType)
{
this.arrayType = arrayType;
_parameters = MakeParameters();
}
public abstract string Name { get; }
public abstract Cci.ITypeReference GetType(EmitContext context);
// Address overrides this to "true"
public virtual bool ReturnValueIsByRef => false;
// Set overrides this to include "value" parameter.
protected virtual ImmutableArray<ArrayMethodParameterInfo> MakeParameters()
{
int rank = (int)arrayType.Rank;
var parameters = ArrayBuilder<ArrayMethodParameterInfo>.GetInstance(rank);
for (int i = 0; i < rank; i++)
{
parameters.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i));
}
return parameters.ToImmutableAndFree();
}
public ImmutableArray<Cci.IParameterTypeInformation> GetParameters(EmitContext context)
=> StaticCast<Cci.IParameterTypeInformation>.From(_parameters);
public bool AcceptsExtraArguments => false;
public ushort GenericParameterCount => 0;
public bool IsGeneric => false;
public Cci.IMethodDefinition? GetResolvedMethod(EmitContext context) => null;
public ImmutableArray<Cci.IParameterTypeInformation> ExtraParameters
=> ImmutableArray<Cci.IParameterTypeInformation>.Empty;
public Cci.IGenericMethodInstanceReference? AsGenericMethodInstanceReference => null;
public Cci.ISpecializedMethodReference? AsSpecializedMethodReference => null;
public Cci.CallingConvention CallingConvention => Cci.CallingConvention.HasThis;
public ushort ParameterCount => (ushort)_parameters.Length;
public ImmutableArray<Cci.ICustomModifier> RefCustomModifiers
=> ImmutableArray<Cci.ICustomModifier>.Empty;
public ImmutableArray<Cci.ICustomModifier> ReturnValueCustomModifiers
=> ImmutableArray<Cci.ICustomModifier>.Empty;
public Cci.ITypeReference GetContainingType(EmitContext context)
{
// We are not translating arrayType.
// It is an array type and it is never generic or contained in a generic.
return this.arrayType;
}
public IEnumerable<Cci.ICustomAttribute> GetAttributes(EmitContext context)
=> SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
public void Dispatch(Cci.MetadataVisitor visitor)
=> visitor.Visit(this);
public Cci.IDefinition? AsDefinition(EmitContext context)
=> null;
public override string ToString()
=> ((object?)arrayType.GetInternalSymbol() ?? arrayType).ToString() + "." + Name;
Symbols.ISymbolInternal? Cci.IReference.GetInternalSymbol() => null;
public sealed override bool Equals(object? obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
// Contains support for pseudo-methods on multidimensional arrays.
//
// Opcodes such as newarr, ldelem, ldelema, stelem do not work with
// multidimensional arrays and same functionality is available in
// a form of well known pseudo-methods "Get", "Set", "Address" and ".ctor"
//
//=========================
//
// 14.2 Arrays (From partition II) -
//The class that the VES creates for arrays contains several methods whose implementation is supplied by the
//VES:
//
//* A constructor that takes a sequence of int32 arguments, one for each dimension of the array, that specify
//the number of elements in each dimension beginning with the first dimension. A lower bound of zero is
//assumed.
//
//* A constructor that takes twice as many int32 arguments as there are dimensions of the array. These
//arguments occur in pairs—one pair per dimension—with the first argument of each pair specifying the
//lower bound for that dimension, and the second argument specifying the total number of elements in that
//dimension. Note that vectors are not created with this constructor, since a zero lower bound is assumed for
//vectors.
//
//* A Get method that takes a sequence of int32 arguments, one for each dimension of the array, and returns
//a value whose type is the element type of the array. This method is used to access a specific element of the
//array where the arguments specify the index into each dimension, beginning with the first, of the element
//to be returned.
//
//* A Set method that takes a sequence of int32 arguments, one for each dimension of the array, followed by
//a value whose type is the element type of the array. The return type of Set is void. This method is used to
//set a specific element of the array where the arguments specify the index into each dimension, beginning
//with the first, of the element to be set and the final argument specifies the value to be stored into the target
//element.
//
//* An Address method that takes a sequence of int32 arguments, one for each dimension of the array, and
//has a return type that is a managed pointer to the array's element type. This method is used to return a
//managed pointer to a specific element of the array where the arguments specify the index into each
//dimension, beginning with the first, of the element whose address is to be returned.
namespace Microsoft.CodeAnalysis.CodeGen
{
/// <summary>
/// Constructs and caches already created pseudo-methods.
/// Every compiled module is supposed to have one of this, created lazily
/// (multidimensional arrays are not common).
/// </summary>
internal class ArrayMethods
{
// There are four kinds of array pseudo-methods
// They are specific to a given array type
private enum ArrayMethodKind : byte
{
GET,
SET,
ADDRESS,
CTOR,
}
/// <summary>
/// Acquires an array constructor for a given array type
/// </summary>
public ArrayMethod GetArrayConstructor(Cci.IArrayTypeReference arrayType)
{
return GetArrayMethod(arrayType, ArrayMethodKind.CTOR);
}
/// <summary>
/// Acquires an element getter method for a given array type
/// </summary>
public ArrayMethod GetArrayGet(Cci.IArrayTypeReference arrayType)
=> GetArrayMethod(arrayType, ArrayMethodKind.GET);
/// <summary>
/// Acquires an element setter method for a given array type
/// </summary>
public ArrayMethod GetArraySet(Cci.IArrayTypeReference arrayType)
=> GetArrayMethod(arrayType, ArrayMethodKind.SET);
/// <summary>
/// Acquires an element referencer method for a given array type
/// </summary>
public ArrayMethod GetArrayAddress(Cci.IArrayTypeReference arrayType)
=> GetArrayMethod(arrayType, ArrayMethodKind.ADDRESS);
/// <summary>
/// Maps {array type, method kind} tuples to implementing pseudo-methods.
/// </summary>
private readonly ConcurrentDictionary<(byte methodKind, IReferenceOrISignature arrayType), ArrayMethod> _dict =
new ConcurrentDictionary<(byte, IReferenceOrISignature), ArrayMethod>();
/// <summary>
/// lazily fetches or creates a new array method.
/// </summary>
private ArrayMethod GetArrayMethod(Cci.IArrayTypeReference arrayType, ArrayMethodKind id)
{
var key = ((byte)id, new IReferenceOrISignature(arrayType));
ArrayMethod? result;
var dict = _dict;
if (!dict.TryGetValue(key, out result))
{
result = MakeArrayMethod(arrayType, id);
result = dict.GetOrAdd(key, result);
}
return result;
}
private static ArrayMethod MakeArrayMethod(Cci.IArrayTypeReference arrayType, ArrayMethodKind id)
{
switch (id)
{
case ArrayMethodKind.CTOR:
return new ArrayConstructor(arrayType);
case ArrayMethodKind.GET:
return new ArrayGet(arrayType);
case ArrayMethodKind.SET:
return new ArraySet(arrayType);
case ArrayMethodKind.ADDRESS:
return new ArrayAddress(arrayType);
}
throw ExceptionUtilities.UnexpectedValue(id);
}
/// <summary>
/// "newobj ArrayConstructor" is equivalent of "newarr ElementType"
/// when working with multidimensional arrays
/// </summary>
private sealed class ArrayConstructor : ArrayMethod
{
public ArrayConstructor(Cci.IArrayTypeReference arrayType) : base(arrayType) { }
public override string Name => ".ctor";
public override Cci.ITypeReference GetType(EmitContext context)
=> context.Module.GetPlatformType(Cci.PlatformType.SystemVoid, context);
}
/// <summary>
/// "call ArrayGet" is equivalent of "ldelem ElementType"
/// when working with multidimensional arrays
/// </summary>
private sealed class ArrayGet : ArrayMethod
{
public ArrayGet(Cci.IArrayTypeReference arrayType) : base(arrayType) { }
public override string Name => "Get";
public override Cci.ITypeReference GetType(EmitContext context)
=> arrayType.GetElementType(context);
}
/// <summary>
/// "call ArrayAddress" is equivalent of "ldelema ElementType"
/// when working with multidimensional arrays
/// </summary>
private sealed class ArrayAddress : ArrayMethod
{
public ArrayAddress(Cci.IArrayTypeReference arrayType) : base(arrayType) { }
public override bool ReturnValueIsByRef => true;
public override Cci.ITypeReference GetType(EmitContext context)
=> arrayType.GetElementType(context);
public override string Name => "Address";
}
/// <summary>
/// "call ArraySet" is equivalent of "stelem ElementType"
/// when working with multidimensional arrays
/// </summary>
private sealed class ArraySet : ArrayMethod
{
public ArraySet(Cci.IArrayTypeReference arrayType) : base(arrayType) { }
public override string Name => "Set";
public override Cci.ITypeReference GetType(EmitContext context)
=> context.Module.GetPlatformType(Cci.PlatformType.SystemVoid, context);
protected override ImmutableArray<ArrayMethodParameterInfo> MakeParameters()
{
int rank = (int)arrayType.Rank;
var parameters = ArrayBuilder<ArrayMethodParameterInfo>.GetInstance(rank + 1);
for (int i = 0; i < rank; i++)
{
parameters.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i));
}
parameters.Add(new ArraySetValueParameterInfo((ushort)rank, arrayType));
return parameters.ToImmutableAndFree();
}
}
}
/// <summary>
/// Represents a parameter in an array pseudo-method.
///
/// NOTE: It appears that only number of indices is used for verification,
/// types just have to be Int32.
/// Even though actual arguments can be native ints.
/// </summary>
internal class ArrayMethodParameterInfo : Cci.IParameterTypeInformation
{
// position in the signature
private readonly ushort _index;
// cache common parameter instances
// (we can do this since the only data we have is the index)
private static readonly ArrayMethodParameterInfo s_index0 = new ArrayMethodParameterInfo(0);
private static readonly ArrayMethodParameterInfo s_index1 = new ArrayMethodParameterInfo(1);
private static readonly ArrayMethodParameterInfo s_index2 = new ArrayMethodParameterInfo(2);
private static readonly ArrayMethodParameterInfo s_index3 = new ArrayMethodParameterInfo(3);
protected ArrayMethodParameterInfo(ushort index)
{
_index = index;
}
public static ArrayMethodParameterInfo GetIndexParameter(ushort index)
{
switch (index)
{
case 0: return s_index0;
case 1: return s_index1;
case 2: return s_index2;
case 3: return s_index3;
}
return new ArrayMethodParameterInfo(index);
}
public ImmutableArray<Cci.ICustomModifier> RefCustomModifiers
=> ImmutableArray<Cci.ICustomModifier>.Empty;
public ImmutableArray<Cci.ICustomModifier> CustomModifiers
=> ImmutableArray<Cci.ICustomModifier>.Empty;
public bool IsByReference => false;
public virtual Cci.ITypeReference GetType(EmitContext context)
=> context.Module.GetPlatformType(Cci.PlatformType.SystemInt32, context);
public ushort Index => _index;
}
/// <summary>
/// Represents the "value" parameter of the Set pseudo-method.
///
/// NOTE: unlike index parameters, type of the value parameter must match
/// the actual element type.
/// </summary>
internal sealed class ArraySetValueParameterInfo : ArrayMethodParameterInfo
{
private readonly Cci.IArrayTypeReference _arrayType;
internal ArraySetValueParameterInfo(ushort index, Cci.IArrayTypeReference arrayType)
: base(index)
{
_arrayType = arrayType;
}
public override Cci.ITypeReference GetType(EmitContext context)
=> _arrayType.GetElementType(context);
}
/// <summary>
/// Base of all array methods. They have a lot in common.
/// </summary>
internal abstract class ArrayMethod : Cci.IMethodReference
{
private readonly ImmutableArray<ArrayMethodParameterInfo> _parameters;
protected readonly Cci.IArrayTypeReference arrayType;
protected ArrayMethod(Cci.IArrayTypeReference arrayType)
{
this.arrayType = arrayType;
_parameters = MakeParameters();
}
public abstract string Name { get; }
public abstract Cci.ITypeReference GetType(EmitContext context);
// Address overrides this to "true"
public virtual bool ReturnValueIsByRef => false;
// Set overrides this to include "value" parameter.
protected virtual ImmutableArray<ArrayMethodParameterInfo> MakeParameters()
{
int rank = (int)arrayType.Rank;
var parameters = ArrayBuilder<ArrayMethodParameterInfo>.GetInstance(rank);
for (int i = 0; i < rank; i++)
{
parameters.Add(ArrayMethodParameterInfo.GetIndexParameter((ushort)i));
}
return parameters.ToImmutableAndFree();
}
public ImmutableArray<Cci.IParameterTypeInformation> GetParameters(EmitContext context)
=> StaticCast<Cci.IParameterTypeInformation>.From(_parameters);
public bool AcceptsExtraArguments => false;
public ushort GenericParameterCount => 0;
public bool IsGeneric => false;
public Cci.IMethodDefinition? GetResolvedMethod(EmitContext context) => null;
public ImmutableArray<Cci.IParameterTypeInformation> ExtraParameters
=> ImmutableArray<Cci.IParameterTypeInformation>.Empty;
public Cci.IGenericMethodInstanceReference? AsGenericMethodInstanceReference => null;
public Cci.ISpecializedMethodReference? AsSpecializedMethodReference => null;
public Cci.CallingConvention CallingConvention => Cci.CallingConvention.HasThis;
public ushort ParameterCount => (ushort)_parameters.Length;
public ImmutableArray<Cci.ICustomModifier> RefCustomModifiers
=> ImmutableArray<Cci.ICustomModifier>.Empty;
public ImmutableArray<Cci.ICustomModifier> ReturnValueCustomModifiers
=> ImmutableArray<Cci.ICustomModifier>.Empty;
public Cci.ITypeReference GetContainingType(EmitContext context)
{
// We are not translating arrayType.
// It is an array type and it is never generic or contained in a generic.
return this.arrayType;
}
public IEnumerable<Cci.ICustomAttribute> GetAttributes(EmitContext context)
=> SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>();
public void Dispatch(Cci.MetadataVisitor visitor)
=> visitor.Visit(this);
public Cci.IDefinition? AsDefinition(EmitContext context)
=> null;
public override string ToString()
=> ((object?)arrayType.GetInternalSymbol() ?? arrayType).ToString() + "." + Name;
Symbols.ISymbolInternal? Cci.IReference.GetInternalSymbol() => null;
public sealed override bool Equals(object? obj)
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
public sealed override int GetHashCode()
{
// It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used.
throw Roslyn.Utilities.ExceptionUtilities.Unreachable;
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicEESymbolProvider.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend NotInheritable Class VisualBasicEESymbolProvider
Inherits EESymbolProvider(Of TypeSymbol, LocalSymbol)
Private ReadOnly _metadataDecoder As MetadataDecoder
Private ReadOnly _method As PEMethodSymbol
Public Sub New([module] As PEModuleSymbol, method As PEMethodSymbol)
_metadataDecoder = New MetadataDecoder([module], method)
_method = method
End Sub
Public Overrides Function GetLocalVariable(
name As String,
slotIndex As Integer,
info As LocalInfo(Of TypeSymbol),
dynamicFlagsOpt As ImmutableArray(Of Boolean),
tupleElementNamesOpt As ImmutableArray(Of String)) As LocalSymbol
' Custom modifiers can be dropped since binding ignores custom
' modifiers from locals and since we only need to preserve
' the type of the original local in the generated method.
Dim kind = If(name = _method.Name, LocalDeclarationKind.FunctionValue, LocalDeclarationKind.Variable)
Dim type = IncludeTupleElementNamesIfAny(info.Type, tupleElementNamesOpt)
Return New EELocalSymbol(_method, EELocalSymbol.NoLocations, name, slotIndex, kind, type, info.IsByRef, info.IsPinned, canScheduleToStack:=False)
End Function
Public Overrides Function GetLocalConstant(
name As String,
type As TypeSymbol,
value As ConstantValue,
dynamicFlagsOpt As ImmutableArray(Of Boolean),
tupleElementNamesOpt As ImmutableArray(Of String)) As LocalSymbol
type = IncludeTupleElementNamesIfAny(type, tupleElementNamesOpt)
Return New EELocalConstantSymbol(_method, name, type, value)
End Function
''' <exception cref="BadImageFormatException"></exception>
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Function DecodeLocalVariableType(signature As ImmutableArray(Of Byte)) As TypeSymbol
Return _metadataDecoder.DecodeLocalVariableTypeOrThrow(signature)
End Function
Public Overrides Function GetTypeSymbolForSerializedType(typeName As String) As TypeSymbol
Return _metadataDecoder.GetTypeSymbolForSerializedType(typeName)
End Function
''' <exception cref="BadImageFormatException"></exception>
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Sub DecodeLocalConstant(ByRef reader As BlobReader, ByRef type As TypeSymbol, ByRef value As ConstantValue)
_metadataDecoder.DecodeLocalConstantBlobOrThrow(reader, type, value)
End Sub
''' <exception cref="BadImageFormatException"></exception>
Public Overrides Function GetReferencedAssembly(handle As AssemblyReferenceHandle) As IAssemblySymbolInternal
Dim index As Integer = _metadataDecoder.Module.GetAssemblyReferenceIndexOrThrow(handle)
Dim assembly = _metadataDecoder.ModuleSymbol.GetReferencedAssemblySymbol(index)
' GetReferencedAssemblySymbol should not return Nothing since this method is
' only used for import aliases in the PDB which are not supported from VB.
Return assembly
End Function
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Function [GetType](handle As EntityHandle) As TypeSymbol
Dim isNoPiaLocalType As Boolean
Return _metadataDecoder.GetSymbolForTypeHandleOrThrow(handle, isNoPiaLocalType, allowTypeSpec:=True, requireShortForm:=False)
End Function
Private Function IncludeTupleElementNamesIfAny(type As TypeSymbol, tupleElementNamesOpt As ImmutableArray(Of String)) As TypeSymbol
Return TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNamesOpt)
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
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend NotInheritable Class VisualBasicEESymbolProvider
Inherits EESymbolProvider(Of TypeSymbol, LocalSymbol)
Private ReadOnly _metadataDecoder As MetadataDecoder
Private ReadOnly _method As PEMethodSymbol
Public Sub New([module] As PEModuleSymbol, method As PEMethodSymbol)
_metadataDecoder = New MetadataDecoder([module], method)
_method = method
End Sub
Public Overrides Function GetLocalVariable(
name As String,
slotIndex As Integer,
info As LocalInfo(Of TypeSymbol),
dynamicFlagsOpt As ImmutableArray(Of Boolean),
tupleElementNamesOpt As ImmutableArray(Of String)) As LocalSymbol
' Custom modifiers can be dropped since binding ignores custom
' modifiers from locals and since we only need to preserve
' the type of the original local in the generated method.
Dim kind = If(name = _method.Name, LocalDeclarationKind.FunctionValue, LocalDeclarationKind.Variable)
Dim type = IncludeTupleElementNamesIfAny(info.Type, tupleElementNamesOpt)
Return New EELocalSymbol(_method, EELocalSymbol.NoLocations, name, slotIndex, kind, type, info.IsByRef, info.IsPinned, canScheduleToStack:=False)
End Function
Public Overrides Function GetLocalConstant(
name As String,
type As TypeSymbol,
value As ConstantValue,
dynamicFlagsOpt As ImmutableArray(Of Boolean),
tupleElementNamesOpt As ImmutableArray(Of String)) As LocalSymbol
type = IncludeTupleElementNamesIfAny(type, tupleElementNamesOpt)
Return New EELocalConstantSymbol(_method, name, type, value)
End Function
''' <exception cref="BadImageFormatException"></exception>
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Function DecodeLocalVariableType(signature As ImmutableArray(Of Byte)) As TypeSymbol
Return _metadataDecoder.DecodeLocalVariableTypeOrThrow(signature)
End Function
Public Overrides Function GetTypeSymbolForSerializedType(typeName As String) As TypeSymbol
Return _metadataDecoder.GetTypeSymbolForSerializedType(typeName)
End Function
''' <exception cref="BadImageFormatException"></exception>
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Sub DecodeLocalConstant(ByRef reader As BlobReader, ByRef type As TypeSymbol, ByRef value As ConstantValue)
_metadataDecoder.DecodeLocalConstantBlobOrThrow(reader, type, value)
End Sub
''' <exception cref="BadImageFormatException"></exception>
Public Overrides Function GetReferencedAssembly(handle As AssemblyReferenceHandle) As IAssemblySymbolInternal
Dim index As Integer = _metadataDecoder.Module.GetAssemblyReferenceIndexOrThrow(handle)
Dim assembly = _metadataDecoder.ModuleSymbol.GetReferencedAssemblySymbol(index)
' GetReferencedAssemblySymbol should not return Nothing since this method is
' only used for import aliases in the PDB which are not supported from VB.
Return assembly
End Function
''' <exception cref="UnsupportedSignatureContent"></exception>
Public Overrides Function [GetType](handle As EntityHandle) As TypeSymbol
Dim isNoPiaLocalType As Boolean
Return _metadataDecoder.GetSymbolForTypeHandleOrThrow(handle, isNoPiaLocalType, allowTypeSpec:=True, requireShortForm:=False)
End Function
Private Function IncludeTupleElementNamesIfAny(type As TypeSymbol, tupleElementNamesOpt As ImmutableArray(Of String)) As TypeSymbol
Return TupleTypeDecoder.DecodeTupleTypesIfApplicable(type, tupleElementNamesOpt)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// A symbol set used when the find refs caller does not want cascading. This is a trivial impl that basically
/// just wraps the initial symbol provided and doesn't need to do anything beyond that.
/// </summary>
private sealed class NonCascadingSymbolSet : SymbolSet
{
private readonly ImmutableArray<ISymbol> _symbols;
public NonCascadingSymbolSet(FindReferencesSearchEngine engine, ISymbol searchSymbol) : base(engine)
{
_symbols = ImmutableArray.Create(searchSymbol);
}
public override ImmutableArray<ISymbol> GetAllSymbols()
=> _symbols;
public override Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Nothing to do here. We're in a non-cascading scenario, so even as we encounter a new project we
// don't have to figure out what new symbols may be found.
return Task.CompletedTask;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// A symbol set used when the find refs caller does not want cascading. This is a trivial impl that basically
/// just wraps the initial symbol provided and doesn't need to do anything beyond that.
/// </summary>
private sealed class NonCascadingSymbolSet : SymbolSet
{
private readonly ImmutableArray<ISymbol> _symbols;
public NonCascadingSymbolSet(FindReferencesSearchEngine engine, ISymbol searchSymbol) : base(engine)
{
_symbols = ImmutableArray.Create(searchSymbol);
}
public override ImmutableArray<ISymbol> GetAllSymbols()
=> _symbols;
public override Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Nothing to do here. We're in a non-cascading scenario, so even as we encounter a new project we
// don't have to figure out what new symbols may be found.
return Task.CompletedTask;
}
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/InvalidGenericType.il | // ilasm InvalidGenericType.il /dll
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly InvalidGenericType
{
}
.class public auto ansi beforefieldinit C`2<T1,T2>
extends [mscorlib]System.Object
{
.class auto ansi nested public beforefieldinit D<S1>
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
| // ilasm InvalidGenericType.il /dll
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly InvalidGenericType
{
}
.class public auto ansi beforefieldinit C`2<T1,T2>
extends [mscorlib]System.Object
{
.class auto ansi nested public beforefieldinit D<S1>
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Features/CSharp/Portable/EditAndContinue/SyntaxUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue
{
internal static class SyntaxUtilities
{
public static SyntaxNode TryGetMethodDeclarationBody(SyntaxNode node)
{
static SyntaxNode BlockOrExpression(BlockSyntax blockBodyOpt, ArrowExpressionClauseSyntax expressionBodyOpt)
=> (SyntaxNode)blockBodyOpt ?? expressionBodyOpt?.Expression;
SyntaxNode result;
switch (node.Kind())
{
case SyntaxKind.MethodDeclaration:
var methodDeclaration = (MethodDeclarationSyntax)node;
result = BlockOrExpression(methodDeclaration.Body, methodDeclaration.ExpressionBody);
break;
case SyntaxKind.ConversionOperatorDeclaration:
var conversionDeclaration = (ConversionOperatorDeclarationSyntax)node;
result = BlockOrExpression(conversionDeclaration.Body, conversionDeclaration.ExpressionBody);
break;
case SyntaxKind.OperatorDeclaration:
var operatorDeclaration = (OperatorDeclarationSyntax)node;
result = BlockOrExpression(operatorDeclaration.Body, operatorDeclaration.ExpressionBody);
break;
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
var accessorDeclaration = (AccessorDeclarationSyntax)node;
result = BlockOrExpression(accessorDeclaration.Body, accessorDeclaration.ExpressionBody);
break;
case SyntaxKind.ConstructorDeclaration:
var constructorDeclaration = (ConstructorDeclarationSyntax)node;
result = BlockOrExpression(constructorDeclaration.Body, constructorDeclaration.ExpressionBody);
break;
case SyntaxKind.DestructorDeclaration:
var destructorDeclaration = (DestructorDeclarationSyntax)node;
result = BlockOrExpression(destructorDeclaration.Body, destructorDeclaration.ExpressionBody);
break;
case SyntaxKind.PropertyDeclaration:
var propertyDeclaration = (PropertyDeclarationSyntax)node;
result = propertyDeclaration.Initializer?.Value;
break;
case SyntaxKind.ArrowExpressionClause:
// We associate the body of expression-bodied property/indexer with the ArrowExpressionClause
// since that's the syntax node associated with the getter symbol.
// The property/indexer itself is considered to not have a body unless the property has an initializer.
result = node.Parent.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration) ?
((ArrowExpressionClauseSyntax)node).Expression : null;
break;
default:
return null;
}
if (result != null)
{
AssertIsBody(result, allowLambda: false);
}
return result;
}
[Conditional("DEBUG")]
public static void AssertIsBody(SyntaxNode syntax, bool allowLambda)
{
// lambda/query
if (LambdaUtilities.IsLambdaBody(syntax))
{
Debug.Assert(allowLambda);
Debug.Assert(syntax is ExpressionSyntax or BlockSyntax);
return;
}
// block body
if (syntax is BlockSyntax)
{
return;
}
// expression body
if (syntax is ExpressionSyntax && syntax.Parent is ArrowExpressionClauseSyntax)
{
return;
}
// field initializer
if (syntax is ExpressionSyntax && syntax.Parent.Parent is VariableDeclaratorSyntax)
{
return;
}
// property initializer
if (syntax is ExpressionSyntax && syntax.Parent.Parent is PropertyDeclarationSyntax)
{
return;
}
// special case for top level statements, which have no containing block other than the compilation unit
if (syntax is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements())
{
return;
}
Debug.Assert(false);
}
public static bool ContainsTopLevelStatements(this CompilationUnitSyntax compilationUnit)
{
if (compilationUnit.Members.Count == 0)
{
return false;
}
return compilationUnit.Members[0] is GlobalStatementSyntax;
}
public static void FindLeafNodeAndPartner(SyntaxNode leftRoot, int leftPosition, SyntaxNode rightRoot, out SyntaxNode leftNode, out SyntaxNode rightNodeOpt)
{
leftNode = leftRoot;
rightNodeOpt = rightRoot;
while (true)
{
if (rightNodeOpt != null && leftNode.RawKind != rightNodeOpt.RawKind)
{
rightNodeOpt = null;
}
var leftChild = leftNode.ChildThatContainsPosition(leftPosition, out var childIndex);
if (leftChild.IsToken)
{
return;
}
if (rightNodeOpt != null)
{
var rightNodeChildNodesAndTokens = rightNodeOpt.ChildNodesAndTokens();
if (childIndex >= 0 && childIndex < rightNodeChildNodesAndTokens.Count)
{
rightNodeOpt = rightNodeChildNodesAndTokens[childIndex].AsNode();
}
else
{
rightNodeOpt = null;
}
}
leftNode = leftChild.AsNode();
}
}
public static SyntaxNode FindPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode)
{
// Finding a partner of a zero-width node is complicated and not supported atm:
Debug.Assert(leftNode.FullSpan.Length > 0);
Debug.Assert(leftNode.SyntaxTree == leftRoot.SyntaxTree);
var originalLeftNode = leftNode;
var leftPosition = leftNode.SpanStart;
leftNode = leftRoot;
var rightNode = rightRoot;
while (leftNode != originalLeftNode)
{
Debug.Assert(leftNode.RawKind == rightNode.RawKind);
var leftChild = leftNode.ChildThatContainsPosition(leftPosition, out var childIndex);
// Can only happen when searching for zero-width node.
Debug.Assert(!leftChild.IsToken);
rightNode = rightNode.ChildNodesAndTokens()[childIndex].AsNode();
leftNode = leftChild.AsNode();
}
return rightNode;
}
public static bool Any(TypeParameterListSyntax listOpt)
=> listOpt != null && listOpt.ChildNodesAndTokens().Count != 0;
public static SyntaxNode TryGetEffectiveGetterBody(SyntaxNode declaration)
{
if (declaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax property))
{
return TryGetEffectiveGetterBody(property.ExpressionBody, property.AccessorList);
}
if (declaration.IsKind(SyntaxKind.IndexerDeclaration, out IndexerDeclarationSyntax indexer))
{
return TryGetEffectiveGetterBody(indexer.ExpressionBody, indexer.AccessorList);
}
return null;
}
public static SyntaxNode TryGetEffectiveGetterBody(ArrowExpressionClauseSyntax propertyBody, AccessorListSyntax accessorList)
{
if (propertyBody != null)
{
return propertyBody.Expression;
}
var firstGetter = accessorList?.Accessors.Where(a => a.IsKind(SyntaxKind.GetAccessorDeclaration)).FirstOrDefault();
if (firstGetter == null)
{
return null;
}
return (SyntaxNode)firstGetter.Body ?? firstGetter.ExpressionBody?.Expression;
}
public static SyntaxTokenList? TryGetFieldOrPropertyModifiers(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax fieldDecl))
return fieldDecl.Modifiers;
if (node.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax propertyDecl))
return propertyDecl.Modifiers;
return null;
}
public static bool IsParameterlessConstructor(SyntaxNode declaration)
{
if (!declaration.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax ctor))
{
return false;
}
return ctor.ParameterList.Parameters.Count == 0;
}
public static bool HasBackingField(PropertyDeclarationSyntax property)
{
if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) ||
property.Modifiers.Any(SyntaxKind.ExternKeyword))
{
return false;
}
return property.ExpressionBody == null
&& property.AccessorList.Accessors.Any(e => e.Body == null);
}
/// <summary>
/// True if the specified declaration node is an async method, anonymous function, lambda, local function.
/// </summary>
public static bool IsAsyncDeclaration(SyntaxNode declaration)
{
// lambdas and anonymous functions
if (declaration is AnonymousFunctionExpressionSyntax anonymousFunction)
{
return anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword);
}
// expression bodied methods/local functions:
if (declaration.IsKind(SyntaxKind.ArrowExpressionClause))
{
declaration = declaration.Parent;
}
return declaration switch
{
MethodDeclarationSyntax method => method.Modifiers.Any(SyntaxKind.AsyncKeyword),
LocalFunctionStatementSyntax localFunction => localFunction.Modifiers.Any(SyntaxKind.AsyncKeyword),
_ => false
};
}
/// <summary>
/// Returns a list of all await expressions, await foreach statements, await using declarations and yield statements in the given body,
/// in the order in which they occur.
/// </summary>
/// <returns>
/// <see cref="AwaitExpressionSyntax"/> for await expressions,
/// <see cref="YieldStatementSyntax"/> for yield break and yield return statements,
/// <see cref="CommonForEachStatementSyntax"/> for await foreach statements,
/// <see cref="VariableDeclaratorSyntax"/> for await using declarators.
/// </returns>
public static IEnumerable<SyntaxNode> GetSuspensionPoints(SyntaxNode body)
=> body.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda).Where(IsSuspensionPoint);
public static bool IsSuspensionPoint(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.AwaitExpression) || node.IsKind(SyntaxKind.YieldBreakStatement) || node.IsKind(SyntaxKind.YieldReturnStatement))
{
return true;
}
// await foreach statement translates to two suspension points: await MoveNextAsync and await DisposeAsync
if (node is CommonForEachStatementSyntax foreachStatement && foreachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
{
return true;
}
// each declarator in the declaration translates to a suspension point: await DisposeAsync
if (node.IsKind(SyntaxKind.VariableDeclarator) &&
node.Parent.Parent.IsKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax localDecl) &&
localDecl.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
{
return true;
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue
{
internal static class SyntaxUtilities
{
public static SyntaxNode TryGetMethodDeclarationBody(SyntaxNode node)
{
static SyntaxNode BlockOrExpression(BlockSyntax blockBodyOpt, ArrowExpressionClauseSyntax expressionBodyOpt)
=> (SyntaxNode)blockBodyOpt ?? expressionBodyOpt?.Expression;
SyntaxNode result;
switch (node.Kind())
{
case SyntaxKind.MethodDeclaration:
var methodDeclaration = (MethodDeclarationSyntax)node;
result = BlockOrExpression(methodDeclaration.Body, methodDeclaration.ExpressionBody);
break;
case SyntaxKind.ConversionOperatorDeclaration:
var conversionDeclaration = (ConversionOperatorDeclarationSyntax)node;
result = BlockOrExpression(conversionDeclaration.Body, conversionDeclaration.ExpressionBody);
break;
case SyntaxKind.OperatorDeclaration:
var operatorDeclaration = (OperatorDeclarationSyntax)node;
result = BlockOrExpression(operatorDeclaration.Body, operatorDeclaration.ExpressionBody);
break;
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
var accessorDeclaration = (AccessorDeclarationSyntax)node;
result = BlockOrExpression(accessorDeclaration.Body, accessorDeclaration.ExpressionBody);
break;
case SyntaxKind.ConstructorDeclaration:
var constructorDeclaration = (ConstructorDeclarationSyntax)node;
result = BlockOrExpression(constructorDeclaration.Body, constructorDeclaration.ExpressionBody);
break;
case SyntaxKind.DestructorDeclaration:
var destructorDeclaration = (DestructorDeclarationSyntax)node;
result = BlockOrExpression(destructorDeclaration.Body, destructorDeclaration.ExpressionBody);
break;
case SyntaxKind.PropertyDeclaration:
var propertyDeclaration = (PropertyDeclarationSyntax)node;
result = propertyDeclaration.Initializer?.Value;
break;
case SyntaxKind.ArrowExpressionClause:
// We associate the body of expression-bodied property/indexer with the ArrowExpressionClause
// since that's the syntax node associated with the getter symbol.
// The property/indexer itself is considered to not have a body unless the property has an initializer.
result = node.Parent.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration) ?
((ArrowExpressionClauseSyntax)node).Expression : null;
break;
default:
return null;
}
if (result != null)
{
AssertIsBody(result, allowLambda: false);
}
return result;
}
[Conditional("DEBUG")]
public static void AssertIsBody(SyntaxNode syntax, bool allowLambda)
{
// lambda/query
if (LambdaUtilities.IsLambdaBody(syntax))
{
Debug.Assert(allowLambda);
Debug.Assert(syntax is ExpressionSyntax or BlockSyntax);
return;
}
// block body
if (syntax is BlockSyntax)
{
return;
}
// expression body
if (syntax is ExpressionSyntax && syntax.Parent is ArrowExpressionClauseSyntax)
{
return;
}
// field initializer
if (syntax is ExpressionSyntax && syntax.Parent.Parent is VariableDeclaratorSyntax)
{
return;
}
// property initializer
if (syntax is ExpressionSyntax && syntax.Parent.Parent is PropertyDeclarationSyntax)
{
return;
}
// special case for top level statements, which have no containing block other than the compilation unit
if (syntax is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements())
{
return;
}
Debug.Assert(false);
}
public static bool ContainsTopLevelStatements(this CompilationUnitSyntax compilationUnit)
{
if (compilationUnit.Members.Count == 0)
{
return false;
}
return compilationUnit.Members[0] is GlobalStatementSyntax;
}
public static void FindLeafNodeAndPartner(SyntaxNode leftRoot, int leftPosition, SyntaxNode rightRoot, out SyntaxNode leftNode, out SyntaxNode rightNodeOpt)
{
leftNode = leftRoot;
rightNodeOpt = rightRoot;
while (true)
{
if (rightNodeOpt != null && leftNode.RawKind != rightNodeOpt.RawKind)
{
rightNodeOpt = null;
}
var leftChild = leftNode.ChildThatContainsPosition(leftPosition, out var childIndex);
if (leftChild.IsToken)
{
return;
}
if (rightNodeOpt != null)
{
var rightNodeChildNodesAndTokens = rightNodeOpt.ChildNodesAndTokens();
if (childIndex >= 0 && childIndex < rightNodeChildNodesAndTokens.Count)
{
rightNodeOpt = rightNodeChildNodesAndTokens[childIndex].AsNode();
}
else
{
rightNodeOpt = null;
}
}
leftNode = leftChild.AsNode();
}
}
public static SyntaxNode FindPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode)
{
// Finding a partner of a zero-width node is complicated and not supported atm:
Debug.Assert(leftNode.FullSpan.Length > 0);
Debug.Assert(leftNode.SyntaxTree == leftRoot.SyntaxTree);
var originalLeftNode = leftNode;
var leftPosition = leftNode.SpanStart;
leftNode = leftRoot;
var rightNode = rightRoot;
while (leftNode != originalLeftNode)
{
Debug.Assert(leftNode.RawKind == rightNode.RawKind);
var leftChild = leftNode.ChildThatContainsPosition(leftPosition, out var childIndex);
// Can only happen when searching for zero-width node.
Debug.Assert(!leftChild.IsToken);
rightNode = rightNode.ChildNodesAndTokens()[childIndex].AsNode();
leftNode = leftChild.AsNode();
}
return rightNode;
}
public static bool Any(TypeParameterListSyntax listOpt)
=> listOpt != null && listOpt.ChildNodesAndTokens().Count != 0;
public static SyntaxNode TryGetEffectiveGetterBody(SyntaxNode declaration)
{
if (declaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax property))
{
return TryGetEffectiveGetterBody(property.ExpressionBody, property.AccessorList);
}
if (declaration.IsKind(SyntaxKind.IndexerDeclaration, out IndexerDeclarationSyntax indexer))
{
return TryGetEffectiveGetterBody(indexer.ExpressionBody, indexer.AccessorList);
}
return null;
}
public static SyntaxNode TryGetEffectiveGetterBody(ArrowExpressionClauseSyntax propertyBody, AccessorListSyntax accessorList)
{
if (propertyBody != null)
{
return propertyBody.Expression;
}
var firstGetter = accessorList?.Accessors.Where(a => a.IsKind(SyntaxKind.GetAccessorDeclaration)).FirstOrDefault();
if (firstGetter == null)
{
return null;
}
return (SyntaxNode)firstGetter.Body ?? firstGetter.ExpressionBody?.Expression;
}
public static SyntaxTokenList? TryGetFieldOrPropertyModifiers(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax fieldDecl))
return fieldDecl.Modifiers;
if (node.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax propertyDecl))
return propertyDecl.Modifiers;
return null;
}
public static bool IsParameterlessConstructor(SyntaxNode declaration)
{
if (!declaration.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax ctor))
{
return false;
}
return ctor.ParameterList.Parameters.Count == 0;
}
public static bool HasBackingField(PropertyDeclarationSyntax property)
{
if (property.Modifiers.Any(SyntaxKind.AbstractKeyword) ||
property.Modifiers.Any(SyntaxKind.ExternKeyword))
{
return false;
}
return property.ExpressionBody == null
&& property.AccessorList.Accessors.Any(e => e.Body == null);
}
/// <summary>
/// True if the specified declaration node is an async method, anonymous function, lambda, local function.
/// </summary>
public static bool IsAsyncDeclaration(SyntaxNode declaration)
{
// lambdas and anonymous functions
if (declaration is AnonymousFunctionExpressionSyntax anonymousFunction)
{
return anonymousFunction.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword);
}
// expression bodied methods/local functions:
if (declaration.IsKind(SyntaxKind.ArrowExpressionClause))
{
declaration = declaration.Parent;
}
return declaration switch
{
MethodDeclarationSyntax method => method.Modifiers.Any(SyntaxKind.AsyncKeyword),
LocalFunctionStatementSyntax localFunction => localFunction.Modifiers.Any(SyntaxKind.AsyncKeyword),
_ => false
};
}
/// <summary>
/// Returns a list of all await expressions, await foreach statements, await using declarations and yield statements in the given body,
/// in the order in which they occur.
/// </summary>
/// <returns>
/// <see cref="AwaitExpressionSyntax"/> for await expressions,
/// <see cref="YieldStatementSyntax"/> for yield break and yield return statements,
/// <see cref="CommonForEachStatementSyntax"/> for await foreach statements,
/// <see cref="VariableDeclaratorSyntax"/> for await using declarators.
/// </returns>
public static IEnumerable<SyntaxNode> GetSuspensionPoints(SyntaxNode body)
=> body.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda).Where(IsSuspensionPoint);
public static bool IsSuspensionPoint(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.AwaitExpression) || node.IsKind(SyntaxKind.YieldBreakStatement) || node.IsKind(SyntaxKind.YieldReturnStatement))
{
return true;
}
// await foreach statement translates to two suspension points: await MoveNextAsync and await DisposeAsync
if (node is CommonForEachStatementSyntax foreachStatement && foreachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
{
return true;
}
// each declarator in the declaration translates to a suspension point: await DisposeAsync
if (node.IsKind(SyntaxKind.VariableDeclarator) &&
node.Parent.Parent.IsKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax localDecl) &&
localDecl.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword))
{
return true;
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Workspaces/Remote/ServiceHub/Services/TodoCommentsDiscovery/RemoteTodoCommentsDiscoveryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.SolutionCrawler;
using Microsoft.CodeAnalysis.TodoComments;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class RemoteTodoCommentsDiscoveryService : BrokeredServiceBase, IRemoteTodoCommentsDiscoveryService
{
internal sealed class Factory : FactoryBase<IRemoteTodoCommentsDiscoveryService, IRemoteTodoCommentsDiscoveryService.ICallback>
{
protected override IRemoteTodoCommentsDiscoveryService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback)
=> new RemoteTodoCommentsDiscoveryService(arguments, callback);
}
private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback;
public RemoteTodoCommentsDiscoveryService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback)
: base(arguments)
{
_callback = callback;
}
public ValueTask ComputeTodoCommentsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
var workspace = GetWorkspace();
var registrationService = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>();
var analyzerProvider = new RemoteTodoCommentsIncrementalAnalyzerProvider(_callback, callbackId);
registrationService.AddAnalyzerProvider(
analyzerProvider,
new IncrementalAnalyzerProviderMetadata(
nameof(RemoteTodoCommentsIncrementalAnalyzerProvider),
highPriorityForActiveFile: false,
workspaceKinds: WorkspaceKind.RemoteWorkspace));
return default;
}, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.TodoComments;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class RemoteTodoCommentsDiscoveryService : BrokeredServiceBase, IRemoteTodoCommentsDiscoveryService
{
internal sealed class Factory : FactoryBase<IRemoteTodoCommentsDiscoveryService, IRemoteTodoCommentsDiscoveryService.ICallback>
{
protected override IRemoteTodoCommentsDiscoveryService CreateService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback)
=> new RemoteTodoCommentsDiscoveryService(arguments, callback);
}
private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback;
public RemoteTodoCommentsDiscoveryService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback)
: base(arguments)
{
_callback = callback;
}
public ValueTask ComputeTodoCommentsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken)
{
return RunServiceAsync(cancellationToken =>
{
var workspace = GetWorkspace();
var registrationService = workspace.Services.GetRequiredService<ISolutionCrawlerRegistrationService>();
var analyzerProvider = new RemoteTodoCommentsIncrementalAnalyzerProvider(_callback, callbackId);
registrationService.AddAnalyzerProvider(
analyzerProvider,
new IncrementalAnalyzerProviderMetadata(
nameof(RemoteTodoCommentsIncrementalAnalyzerProvider),
highPriorityForActiveFile: false,
workspaceKinds: WorkspaceKind.RemoteWorkspace));
return default;
}, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Workspaces/Core/Portable/Storage/ISQLiteStorageServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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
{
/// <summary>
/// Factory for SQLite storage service - intentionally not included under SQLite directory since all sources under it are excluded from source build.
/// </summary>
internal interface ISQLiteStorageServiceFactory : IWorkspaceService
{
IChecksummedPersistentStorageService Create(IPersistentStorageConfiguration configuration);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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
{
/// <summary>
/// Factory for SQLite storage service - intentionally not included under SQLite directory since all sources under it are excluded from source build.
/// </summary>
internal interface ISQLiteStorageServiceFactory : IWorkspaceService
{
IChecksummedPersistentStorageService Create(IPersistentStorageConfiguration configuration);
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Features/LanguageServer/Protocol/Handler/BufferedProgress.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Helper type to allow command handlers to report data either in a streaming fashion (if a client supports that),
/// or as an array of results. This type is thread-safe in the same manner that <see cref="IProgress{T}"/> is
/// expected to be. Namely, multiple client can be calling <see cref="IProgress{T}.Report(T)"/> on it at the same
/// time. This is safe, though the order that the items are reported in when called concurrently is not specified.
/// </summary>
internal struct BufferedProgress<T> : IProgress<T[]>, IProgress<T>, IDisposable
{
/// <summary>
/// The progress stream to report results to. May be <see langword="null"/> for clients that do not support streaming.
/// If <see langword="null"/> then <see cref="_buffer"/> will be non null and will contain all the produced values.
/// </summary>
private readonly IProgress<T[]>? _underlyingProgress;
/// <summary>
/// A buffer that results are held in if the client does not support streaming. Values of this can be retrieved
/// using <see cref="GetValues"/>.
/// </summary>
private readonly ArrayBuilder<T>? _buffer;
public BufferedProgress(IProgress<T[]>? underlyingProgress)
{
_underlyingProgress = underlyingProgress;
_buffer = underlyingProgress == null ? ArrayBuilder<T>.GetInstance() : null;
}
public void Dispose()
=> _buffer?.Free();
/// <summary>
/// Report a value either in a streaming or buffered fashion depending on what the client supports.
/// </summary>
public void Report(T value)
{
// Don't need to lock _underlyingProgress. It is inherently thread-safe itself being an IProgress implementation.
_underlyingProgress?.Report(new[] { value });
if (_buffer != null)
{
lock (_buffer)
{
_buffer.Add(value);
}
}
}
public void Report(T[] values)
{
// Don't need to lock _underlyingProgress. It is inherently thread-safe itself being an IProgress implementation.
_underlyingProgress?.Report(values);
if (_buffer != null)
{
lock (_buffer)
{
_buffer.AddRange(values);
}
}
}
/// <summary>
/// Gets the set of buffered values. Will return null if the client supports streaming. Must be called after
/// all calls to <see cref="Report(T)"/> have been made. Not safe to call concurrently with any call to <see
/// cref="Report(T)"/>.
/// </summary>
public T[]? GetValues()
=> _buffer?.ToArray();
}
internal static class BufferedProgress
{
public static BufferedProgress<T> Create<T>(IProgress<T[]>? progress)
=> new BufferedProgress<T>(progress);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Helper type to allow command handlers to report data either in a streaming fashion (if a client supports that),
/// or as an array of results. This type is thread-safe in the same manner that <see cref="IProgress{T}"/> is
/// expected to be. Namely, multiple client can be calling <see cref="IProgress{T}.Report(T)"/> on it at the same
/// time. This is safe, though the order that the items are reported in when called concurrently is not specified.
/// </summary>
internal struct BufferedProgress<T> : IProgress<T[]>, IProgress<T>, IDisposable
{
/// <summary>
/// The progress stream to report results to. May be <see langword="null"/> for clients that do not support streaming.
/// If <see langword="null"/> then <see cref="_buffer"/> will be non null and will contain all the produced values.
/// </summary>
private readonly IProgress<T[]>? _underlyingProgress;
/// <summary>
/// A buffer that results are held in if the client does not support streaming. Values of this can be retrieved
/// using <see cref="GetValues"/>.
/// </summary>
private readonly ArrayBuilder<T>? _buffer;
public BufferedProgress(IProgress<T[]>? underlyingProgress)
{
_underlyingProgress = underlyingProgress;
_buffer = underlyingProgress == null ? ArrayBuilder<T>.GetInstance() : null;
}
public void Dispose()
=> _buffer?.Free();
/// <summary>
/// Report a value either in a streaming or buffered fashion depending on what the client supports.
/// </summary>
public void Report(T value)
{
// Don't need to lock _underlyingProgress. It is inherently thread-safe itself being an IProgress implementation.
_underlyingProgress?.Report(new[] { value });
if (_buffer != null)
{
lock (_buffer)
{
_buffer.Add(value);
}
}
}
public void Report(T[] values)
{
// Don't need to lock _underlyingProgress. It is inherently thread-safe itself being an IProgress implementation.
_underlyingProgress?.Report(values);
if (_buffer != null)
{
lock (_buffer)
{
_buffer.AddRange(values);
}
}
}
/// <summary>
/// Gets the set of buffered values. Will return null if the client supports streaming. Must be called after
/// all calls to <see cref="Report(T)"/> have been made. Not safe to call concurrently with any call to <see
/// cref="Report(T)"/>.
/// </summary>
public T[]? GetValues()
=> _buffer?.ToArray();
}
internal static class BufferedProgress
{
public static BufferedProgress<T> Create<T>(IProgress<T[]>? progress)
=> new BufferedProgress<T>(progress);
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/VisualStudio/Core/Def/ColorSchemes/VisualStudio2019.pkgdef | [$RootKey$\Themes\{de3dbbcd-f642-433c-8353-8f1df4370aba}\Roslyn Text Editor MEF Items]
"Data"=hex:f3,05,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,2f,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,01,00,00,00,ff,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,01,00,00,00,ff,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,01,80,00,00,ff,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,01,8f,08,c4,ff,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,01,74,53,1f,ff,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,01,2b,91,af,ff,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,01,2b,91,af,ff,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,01,2b,91,af,ff,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,01,2b,91,af,ff,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,01,2b,91,af,ff,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,01,2b,91,af,ff,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,2b,91,af,ff,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,01,1f,37,7f,ff,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,1f,37,7f,ff,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,01,e6,e6,fa,ff,01,68,68,68,ff,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,80,80,80,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,80,80,80,ff,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,80,80,80,ff,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,80,80,80,ff,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,80,80,80,ff,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,80,80,80,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,00,80,00,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,01,80,80,80,ff,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,80,80,80,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,01,00,80,00,ff,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,00,80,00,ff,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,01,00,73,ff,ff,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,01,ff,00,c1,ff,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,01,ff,00,c1,ff,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,01,05,c3,ba,ff,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,01,05,c3,ba,ff,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,01,80,00,00,ff,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,01,80,00,00,ff,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,01,9e,5b,71,ff,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,b9,64,64,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,55,55,55,ff,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,64,64,b9,ff,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,80,80,80,ff,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,62,97,55,ff,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,64,64,b9,ff,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,01,ff,fe,bf,ff,01,55,55,55,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,b9,64,64,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,01,84,46,46,ff,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,c0,c0,c0,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,01,55,55,55,ff
[$RootKey$\Themes\{1ded0138-47ce-435e-84ef-9ec1f439b749}\Roslyn Text Editor MEF Items]
"Data"=hex:f3,05,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,2f,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,01,dc,dc,dc,ff,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,01,dc,dc,dc,ff,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,01,d6,9d,85,ff,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,01,d8,a0,df,ff,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,01,dc,dc,aa,ff,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,01,4e,c9,b0,ff,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,01,4e,c9,b0,ff,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,01,b8,d7,a3,ff,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,01,b8,d7,a3,ff,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,01,4e,c9,b0,ff,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,01,86,c6,91,ff,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,b8,d7,a3,ff,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,01,9c,dc,fe,ff,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,9c,dc,fe,ff,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,dc,dc,aa,ff,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,dc,dc,aa,ff,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,01,2d,2c,2c,ff,01,95,94,93,ff,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,c8,c8,c8,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,c8,c8,c8,ff,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,c8,c8,c8,ff,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,e9,d5,85,ff,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,60,8b,4e,ff,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,60,8b,4e,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,60,8b,4e,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,01,60,8b,4e,ff,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,60,8b,4e,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,01,60,8b,4e,ff,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,57,a6,4a,ff,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,01,2e,ab,fe,ff,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,01,f9,79,ae,ff,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,01,f9,79,ae,ff,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,01,05,c3,ba,ff,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,01,05,c3,ba,ff,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,01,d6,9d,85,ff,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,01,d6,9d,85,ff,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,01,ff,d6,8f,ff,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,c8,c8,c8,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,92,ca,f4,ff,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,c8,c8,c8,ff,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,e9,d5,85,ff,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,60,8b,4e,ff,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,89,bb,82,ff,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,01,ed,e0,d1,ff,01,71,71,71,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,92,ca,f4,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,01,56,9c,d6,ff,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,ae,ae,ae,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,01,c8,c8,c8,ff
[$RootKey$\Themes\{a4d6a176-b948-4b29-8c66-53c97a1ed7d0}\Roslyn Text Editor MEF Items]
"Data"=hex:f3,05,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,2f,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,01,00,00,00,ff,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,01,00,00,00,ff,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,01,80,00,00,ff,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,01,8f,08,c4,ff,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,01,74,53,1f,ff,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,01,2b,91,af,ff,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,01,2b,91,af,ff,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,01,2b,91,af,ff,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,01,2b,91,af,ff,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,01,2b,91,af,ff,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,01,2b,91,af,ff,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,2b,91,af,ff,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,01,1f,37,7f,ff,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,1f,37,7f,ff,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,01,e6,e6,fa,ff,01,68,68,68,ff,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,80,80,80,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,80,80,80,ff,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,80,80,80,ff,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,80,80,80,ff,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,80,80,80,ff,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,80,80,80,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,00,80,00,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,01,80,80,80,ff,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,80,80,80,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,01,00,80,00,ff,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,00,80,00,ff,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,01,00,73,ff,ff,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,01,ff,00,c1,ff,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,01,ff,00,c1,ff,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,01,05,c3,ba,ff,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,01,05,c3,ba,ff,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,01,80,00,00,ff,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,01,80,00,00,ff,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,01,9e,5b,71,ff,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,b9,64,64,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,55,55,55,ff,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,64,64,b9,ff,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,80,80,80,ff,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,62,97,55,ff,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,64,64,b9,ff,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,01,ff,fe,bf,ff,01,55,55,55,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,b9,64,64,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,01,84,46,46,ff,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,c0,c0,c0,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,01,55,55,55,ff
[$RootKey$\Themes\{ce94d289-8481-498b-8ca9-9b6191a315b9}\Roslyn Text Editor MEF Items]
"Data"=hex:f3,05,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,2f,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,01,00,00,00,ff,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,01,00,00,00,ff,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,01,80,00,00,ff,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,01,8f,08,c4,ff,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,01,74,53,1f,ff,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,01,06,65,55,ff,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,01,06,65,55,ff,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,01,06,65,55,ff,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,01,06,65,55,ff,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,01,06,65,55,ff,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,01,06,65,55,ff,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,06,65,55,ff,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,01,1f,37,7f,ff,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,1f,37,7f,ff,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,01,e6,e6,fa,ff,01,50,48,48,ff,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,5b,5b,5b,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,5b,5b,5b,ff,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,5b,5b,5b,ff,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,5b,5b,5b,ff,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,5b,5b,5b,ff,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,5b,5b,5b,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,06,65,55,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,01,5b,5b,5b,ff,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,5b,5b,5b,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,01,06,65,55,ff,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,06,65,55,ff,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,01,04,3b,b3,ff,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,01,83,14,6c,ff,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,01,83,14,6c,ff,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,01,20,4f,4b,ff,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,01,20,4f,4b,ff,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,01,80,00,00,ff,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,01,80,00,00,ff,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,01,72,32,4e,ff,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,86,34,34,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,3f,3f,3f,ff,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,52,45,a9,ff,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,5b,5b,5b,ff,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,06,65,55,ff,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,52,45,a9,ff,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,01,ed,e0,d1,ff,01,3f,3f,3f,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,86,34,34,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,01,86,34,34,ff,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,5b,5b,5b,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,01,3f,3f,3f,ff
[$RootKey$\Themes\{a5c004b4-2d4b-494e-bf01-45fc492522c7}\Roslyn Text Editor MEF Items]
"Data"=hex:87,06,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,36,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,03,08,00,00,00,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,03,08,00,00,00,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,03,08,00,00,00,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,03,08,00,00,00,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,03,08,00,00,00,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,03,08,00,00,00,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,03,08,00,00,00,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,03,08,00,00,00,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,03,08,00,00,00,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,03,08,00,00,00,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,03,08,00,00,00,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,03,08,00,00,00,0a,00,00,00,66,69,65,6c,64,20,6e,61,6d,65,00,03,08,00,00,00,10,00,00,00,65,6e,75,6d,20,6d,65,6d,62,65,72,20,6e,61,6d,65,00,03,08,00,00,00,0d,00,00,00,63,6f,6e,73,74,61,6e,74,20,6e,61,6d,65,00,03,08,00,00,00,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,03,08,00,00,00,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,03,08,00,00,00,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,03,08,00,00,00,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,03,08,00,00,00,0d,00,00,00,70,72,6f,70,65,72,74,79,20,6e,61,6d,65,00,03,08,00,00,00,0a,00,00,00,65,76,65,6e,74,20,6e,61,6d,65,00,03,08,00,00,00,0e,00,00,00,6e,61,6d,65,73,70,61,63,65,20,6e,61,6d,65,00,03,08,00,00,00,0a,00,00,00,6c,61,62,65,6c,20,6e,61,6d,65,00,03,08,00,00,00,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,00,03,08,00,00,00,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,03,08,00,00,00,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,03,08,00,00,00,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,03,08,00,00,00,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,03,08,00,00,00,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,03,08,00,00,00,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,03,08,00,00,00,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,03,08,00,00,00,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,03,08,00,00,00,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,03,08,00,00,00,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,03,08,00,00,00,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,03,08,00,00,00,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,03,08,00,00,00,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,03,08,00,00,00,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,03,08,00,00,00,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,03,08,00,00,00,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,03,08,00,00,00,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,03,08,00,00,00,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,03,08,00,00,00,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,03,08,00,00,00,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,03,08,00,00,00,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,03,08,00,00,00,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,03,08,00,00,00,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,03,08,00,00,00,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,03,08,00,00,00,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,03,08,00,00,00,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,00,03,08,00,00,00,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,03,08,00,00,00,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,03,08,00,00,00,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,03,08,00,00,00,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,03,08,00,00,00
| [$RootKey$\Themes\{de3dbbcd-f642-433c-8353-8f1df4370aba}\Roslyn Text Editor MEF Items]
"Data"=hex:f3,05,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,2f,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,01,00,00,00,ff,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,01,00,00,00,ff,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,01,80,00,00,ff,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,01,8f,08,c4,ff,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,01,74,53,1f,ff,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,01,2b,91,af,ff,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,01,2b,91,af,ff,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,01,2b,91,af,ff,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,01,2b,91,af,ff,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,01,2b,91,af,ff,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,01,2b,91,af,ff,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,2b,91,af,ff,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,01,1f,37,7f,ff,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,1f,37,7f,ff,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,01,e6,e6,fa,ff,01,68,68,68,ff,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,80,80,80,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,80,80,80,ff,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,80,80,80,ff,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,80,80,80,ff,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,80,80,80,ff,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,80,80,80,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,00,80,00,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,01,80,80,80,ff,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,80,80,80,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,01,00,80,00,ff,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,00,80,00,ff,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,01,00,73,ff,ff,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,01,ff,00,c1,ff,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,01,ff,00,c1,ff,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,01,05,c3,ba,ff,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,01,05,c3,ba,ff,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,01,80,00,00,ff,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,01,80,00,00,ff,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,01,9e,5b,71,ff,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,b9,64,64,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,55,55,55,ff,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,64,64,b9,ff,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,80,80,80,ff,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,62,97,55,ff,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,64,64,b9,ff,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,01,ff,fe,bf,ff,01,55,55,55,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,b9,64,64,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,01,84,46,46,ff,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,c0,c0,c0,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,01,55,55,55,ff
[$RootKey$\Themes\{1ded0138-47ce-435e-84ef-9ec1f439b749}\Roslyn Text Editor MEF Items]
"Data"=hex:f3,05,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,2f,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,01,dc,dc,dc,ff,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,01,dc,dc,dc,ff,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,01,d6,9d,85,ff,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,01,d8,a0,df,ff,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,01,dc,dc,aa,ff,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,01,4e,c9,b0,ff,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,01,4e,c9,b0,ff,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,01,b8,d7,a3,ff,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,01,b8,d7,a3,ff,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,01,4e,c9,b0,ff,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,01,86,c6,91,ff,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,b8,d7,a3,ff,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,01,9c,dc,fe,ff,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,9c,dc,fe,ff,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,dc,dc,aa,ff,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,dc,dc,aa,ff,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,01,2d,2c,2c,ff,01,95,94,93,ff,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,c8,c8,c8,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,c8,c8,c8,ff,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,c8,c8,c8,ff,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,e9,d5,85,ff,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,60,8b,4e,ff,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,60,8b,4e,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,60,8b,4e,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,01,60,8b,4e,ff,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,60,8b,4e,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,01,60,8b,4e,ff,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,57,a6,4a,ff,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,01,2e,ab,fe,ff,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,01,f9,79,ae,ff,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,01,f9,79,ae,ff,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,01,05,c3,ba,ff,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,01,05,c3,ba,ff,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,01,d6,9d,85,ff,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,01,d6,9d,85,ff,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,01,ff,d6,8f,ff,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,c8,c8,c8,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,92,ca,f4,ff,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,c8,c8,c8,ff,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,e9,d5,85,ff,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,60,8b,4e,ff,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,89,bb,82,ff,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,01,ed,e0,d1,ff,01,71,71,71,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,92,ca,f4,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,01,56,9c,d6,ff,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,ae,ae,ae,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,01,c8,c8,c8,ff
[$RootKey$\Themes\{a4d6a176-b948-4b29-8c66-53c97a1ed7d0}\Roslyn Text Editor MEF Items]
"Data"=hex:f3,05,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,2f,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,01,00,00,00,ff,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,01,00,00,00,ff,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,01,80,00,00,ff,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,01,8f,08,c4,ff,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,01,74,53,1f,ff,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,01,2b,91,af,ff,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,01,2b,91,af,ff,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,01,2b,91,af,ff,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,01,2b,91,af,ff,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,01,2b,91,af,ff,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,01,2b,91,af,ff,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,2b,91,af,ff,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,01,1f,37,7f,ff,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,1f,37,7f,ff,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,01,e6,e6,fa,ff,01,68,68,68,ff,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,80,80,80,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,80,80,80,ff,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,80,80,80,ff,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,80,80,80,ff,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,80,80,80,ff,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,80,80,80,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,00,80,00,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,01,80,80,80,ff,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,80,80,80,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,01,00,80,00,ff,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,00,80,00,ff,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,01,00,73,ff,ff,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,01,ff,00,c1,ff,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,01,ff,00,c1,ff,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,01,05,c3,ba,ff,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,01,05,c3,ba,ff,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,01,80,00,00,ff,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,01,80,00,00,ff,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,01,9e,5b,71,ff,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,b9,64,64,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,55,55,55,ff,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,64,64,b9,ff,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,80,80,80,ff,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,62,97,55,ff,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,64,64,b9,ff,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,01,ff,fe,bf,ff,01,55,55,55,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,b9,64,64,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,01,84,46,46,ff,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,c0,c0,c0,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,01,55,55,55,ff
[$RootKey$\Themes\{ce94d289-8481-498b-8ca9-9b6191a315b9}\Roslyn Text Editor MEF Items]
"Data"=hex:f3,05,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,2f,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,01,00,00,00,ff,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,01,00,00,00,ff,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,01,80,00,00,ff,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,01,8f,08,c4,ff,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,01,74,53,1f,ff,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,01,06,65,55,ff,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,01,06,65,55,ff,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,01,06,65,55,ff,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,01,06,65,55,ff,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,01,06,65,55,ff,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,01,06,65,55,ff,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,06,65,55,ff,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,01,1f,37,7f,ff,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,01,1f,37,7f,ff,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,01,74,53,1f,ff,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,01,e6,e6,fa,ff,01,50,48,48,ff,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,5b,5b,5b,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,5b,5b,5b,ff,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,5b,5b,5b,ff,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,5b,5b,5b,ff,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,5b,5b,5b,ff,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,5b,5b,5b,ff,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,06,65,55,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,01,5b,5b,5b,ff,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,5b,5b,5b,ff,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,01,06,65,55,ff,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,06,65,55,ff,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,01,04,3b,b3,ff,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,01,83,14,6c,ff,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,01,83,14,6c,ff,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,01,20,4f,4b,ff,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,01,20,4f,4b,ff,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,01,80,00,00,ff,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,01,80,00,00,ff,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,01,72,32,4e,ff,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,01,86,34,34,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,01,3f,3f,3f,ff,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,01,52,45,a9,ff,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,01,5b,5b,5b,ff,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,01,06,65,55,ff,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,01,52,45,a9,ff,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,01,ed,e0,d1,ff,01,3f,3f,3f,ff,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,01,86,34,34,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,01,86,34,34,ff,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,01,5b,5b,5b,ff,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,01,3f,3f,3f,ff
[$RootKey$\Themes\{a5c004b4-2d4b-494e-bf01-45fc492522c7}\Roslyn Text Editor MEF Items]
"Data"=hex:87,06,00,00,0b,00,00,00,01,00,00,00,85,56,a0,75,a8,00,ed,4d,ba,e5,e7,a5,0b,fa,92,9a,36,00,00,00,11,00,00,00,70,72,65,70,72,6f,63,65,73,73,6f,72,20,74,65,78,74,00,03,08,00,00,00,0b,00,00,00,70,75,6e,63,74,75,61,74,69,6f,6e,00,03,08,00,00,00,11,00,00,00,73,74,72,69,6e,67,20,2d,20,76,65,72,62,61,74,69,6d,00,03,08,00,00,00,11,00,00,00,6b,65,79,77,6f,72,64,20,2d,20,63,6f,6e,74,72,6f,6c,00,03,08,00,00,00,15,00,00,00,6f,70,65,72,61,74,6f,72,20,2d,20,6f,76,65,72,6c,6f,61,64,65,64,00,03,08,00,00,00,0a,00,00,00,63,6c,61,73,73,20,6e,61,6d,65,00,03,08,00,00,00,0d,00,00,00,64,65,6c,65,67,61,74,65,20,6e,61,6d,65,00,03,08,00,00,00,09,00,00,00,65,6e,75,6d,20,6e,61,6d,65,00,03,08,00,00,00,0e,00,00,00,69,6e,74,65,72,66,61,63,65,20,6e,61,6d,65,00,03,08,00,00,00,0b,00,00,00,6d,6f,64,75,6c,65,20,6e,61,6d,65,00,03,08,00,00,00,0b,00,00,00,73,74,72,75,63,74,20,6e,61,6d,65,00,03,08,00,00,00,13,00,00,00,74,79,70,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,03,08,00,00,00,0a,00,00,00,66,69,65,6c,64,20,6e,61,6d,65,00,03,08,00,00,00,10,00,00,00,65,6e,75,6d,20,6d,65,6d,62,65,72,20,6e,61,6d,65,00,03,08,00,00,00,0d,00,00,00,63,6f,6e,73,74,61,6e,74,20,6e,61,6d,65,00,03,08,00,00,00,0a,00,00,00,6c,6f,63,61,6c,20,6e,61,6d,65,00,03,08,00,00,00,0e,00,00,00,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,00,03,08,00,00,00,0b,00,00,00,6d,65,74,68,6f,64,20,6e,61,6d,65,00,03,08,00,00,00,15,00,00,00,65,78,74,65,6e,73,69,6f,6e,20,6d,65,74,68,6f,64,20,6e,61,6d,65,00,03,08,00,00,00,0d,00,00,00,70,72,6f,70,65,72,74,79,20,6e,61,6d,65,00,03,08,00,00,00,0a,00,00,00,65,76,65,6e,74,20,6e,61,6d,65,00,03,08,00,00,00,0e,00,00,00,6e,61,6d,65,73,70,61,63,65,20,6e,61,6d,65,00,03,08,00,00,00,0a,00,00,00,6c,61,62,65,6c,20,6e,61,6d,65,00,03,08,00,00,00,1b,00,00,00,69,6e,6c,69,6e,65,20,70,61,72,61,6d,65,74,65,72,20,6e,61,6d,65,20,68,69,6e,74,73,00,03,08,00,00,00,20,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,03,08,00,00,00,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,03,08,00,00,00,21,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,03,08,00,00,00,1f,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,03,08,00,00,00,19,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,63,6f,6d,6d,65,6e,74,00,03,08,00,00,00,1b,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,03,08,00,00,00,22,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,03,08,00,00,00,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,6e,61,6d,65,00,03,08,00,00,00,28,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,03,08,00,00,00,16,00,00,00,78,6d,6c,20,64,6f,63,20,63,6f,6d,6d,65,6e,74,20,2d,20,74,65,78,74,00,03,08,00,00,00,0f,00,00,00,72,65,67,65,78,20,2d,20,63,6f,6d,6d,65,6e,74,00,03,08,00,00,00,17,00,00,00,72,65,67,65,78,20,2d,20,63,68,61,72,61,63,74,65,72,20,63,6c,61,73,73,00,03,08,00,00,00,0e,00,00,00,72,65,67,65,78,20,2d,20,61,6e,63,68,6f,72,00,03,08,00,00,00,12,00,00,00,72,65,67,65,78,20,2d,20,71,75,61,6e,74,69,66,69,65,72,00,03,08,00,00,00,10,00,00,00,72,65,67,65,78,20,2d,20,67,72,6f,75,70,69,6e,67,00,03,08,00,00,00,13,00,00,00,72,65,67,65,78,20,2d,20,61,6c,74,65,72,6e,61,74,69,6f,6e,00,03,08,00,00,00,0c,00,00,00,72,65,67,65,78,20,2d,20,74,65,78,74,00,03,08,00,00,00,1e,00,00,00,72,65,67,65,78,20,2d,20,73,65,6c,66,20,65,73,63,61,70,65,64,20,63,68,61,72,61,63,74,65,72,00,03,08,00,00,00,14,00,00,00,72,65,67,65,78,20,2d,20,6f,74,68,65,72,20,65,73,63,61,70,65,00,03,08,00,00,00,1c,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,6e,61,6d,65,00,03,08,00,00,00,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,71,75,6f,74,65,73,00,03,08,00,00,00,1d,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,61,74,74,72,69,62,75,74,65,20,76,61,6c,75,65,00,03,08,00,00,00,1b,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,64,61,74,61,20,73,65,63,74,69,6f,6e,00,03,08,00,00,00,15,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,63,6f,6d,6d,65,6e,74,00,03,08,00,00,00,17,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,64,65,6c,69,6d,69,74,65,72,00,03,08,00,00,00,21,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6d,62,65,64,64,65,64,20,65,78,70,72,65,73,73,69,6f,6e,00,03,08,00,00,00,1e,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,65,6e,74,69,74,79,20,72,65,66,65,72,65,6e,63,65,00,03,08,00,00,00,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,6e,61,6d,65,00,03,08,00,00,00,24,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,70,72,6f,63,65,73,73,69,6e,67,20,69,6e,73,74,72,75,63,74,69,6f,6e,00,03,08,00,00,00,12,00,00,00,78,6d,6c,20,6c,69,74,65,72,61,6c,20,2d,20,74,65,78,74,00,03,08,00,00,00
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Utilities/PossibleDeclarationTypes.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
<Flags()>
Friend Enum PossibleDeclarationTypes As UInteger
Method = 1 << 0
[Class] = 1 << 1
[Structure] = 1 << 2
[Interface] = 1 << 3
[Enum] = 1 << 4
[Delegate] = 1 << 5
[Module] = 1 << 6
AllTypes = [Class] Or [Structure] Or [Interface] Or [Enum] Or [Delegate] Or [Module]
[Operator] = 1 << 7
[Property] = 1 << 8
Field = 1 << 9
[Event] = 1 << 10
ExternalMethod = 1 << 11
ProtectedMember = 1 << 12
OverridableMethod = 1 << 13
Accessor = 1 << 14
IteratorFunction = 1 << 15
IteratorProperty = 1 << 16
End Enum
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities
<Flags()>
Friend Enum PossibleDeclarationTypes As UInteger
Method = 1 << 0
[Class] = 1 << 1
[Structure] = 1 << 2
[Interface] = 1 << 3
[Enum] = 1 << 4
[Delegate] = 1 << 5
[Module] = 1 << 6
AllTypes = [Class] Or [Structure] Or [Interface] Or [Enum] Or [Delegate] Or [Module]
[Operator] = 1 << 7
[Property] = 1 << 8
Field = 1 << 9
[Event] = 1 << 10
ExternalMethod = 1 << 11
ProtectedMember = 1 << 12
OverridableMethod = 1 << 13
Accessor = 1 << 14
IteratorFunction = 1 << 15
IteratorProperty = 1 << 16
End Enum
End Namespace
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Workspaces/CSharp/Portable/CodeGeneration/EventGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class EventGenerator
{
private static MemberDeclarationSyntax AfterMember(
SyntaxList<MemberDeclarationSyntax> members,
MemberDeclarationSyntax eventDeclaration)
{
if (eventDeclaration.Kind() == SyntaxKind.EventFieldDeclaration)
{
// Field style events go after the last field event, or after the last field.
var lastEvent = members.LastOrDefault(m => m is EventFieldDeclarationSyntax);
return lastEvent ?? LastField(members);
}
if (eventDeclaration.Kind() == SyntaxKind.EventDeclaration)
{
// Property style events go after existing events, then after existing constructors.
var lastEvent = members.LastOrDefault(m => m is EventDeclarationSyntax);
return lastEvent ?? LastConstructor(members);
}
return null;
}
private static MemberDeclarationSyntax BeforeMember(
SyntaxList<MemberDeclarationSyntax> members,
MemberDeclarationSyntax eventDeclaration)
{
// If it's a field style event, then it goes before everything else if we don't have any
// existing fields/events.
if (eventDeclaration.Kind() == SyntaxKind.FieldDeclaration)
{
return members.FirstOrDefault();
}
// Otherwise just place it before the methods.
return FirstMethod(members);
}
internal static CompilationUnitSyntax AddEventTo(
CompilationUnitSyntax destination,
IEventSymbol @event,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateEventDeclaration(@event, CodeGenerationDestination.CompilationUnit, options);
// Place the event depending on its shape. Field style events go with fields, property
// style events go with properties. If there
var members = Insert(destination.Members, declaration, options, availableIndices,
after: list => AfterMember(list, declaration), before: list => BeforeMember(list, declaration));
return destination.WithMembers(members.ToSyntaxList());
}
internal static TypeDeclarationSyntax AddEventTo(
TypeDeclarationSyntax destination,
IEventSymbol @event,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateEventDeclaration(@event, GetDestination(destination), options);
var members = Insert(destination.Members, declaration, options, availableIndices,
after: list => AfterMember(list, declaration),
before: list => BeforeMember(list, declaration));
// Find the best place to put the field. It should go after the last field if we already
// have fields, or at the beginning of the file if we don't.
return AddMembersTo(destination, members);
}
public static MemberDeclarationSyntax GenerateEventDeclaration(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(@event, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
var declaration = !options.GenerateMethodBodies || @event.IsAbstract || @event.AddMethod == null || @event.RemoveMethod == null
? GenerateEventFieldDeclaration(@event, destination, options)
: GenerateEventDeclarationWorker(@event, destination, options);
return ConditionallyAddDocumentationCommentTo(declaration, @event, options);
}
private static MemberDeclarationSyntax GenerateEventFieldDeclaration(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
return AddFormatterAndCodeGeneratorAnnotationsTo(
AddAnnotationsTo(@event,
SyntaxFactory.EventFieldDeclaration(
AttributeGenerator.GenerateAttributeLists(@event.GetAttributes(), options),
GenerateModifiers(@event, destination, options),
SyntaxFactory.VariableDeclaration(
@event.Type.GenerateTypeSyntax(),
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(@event.Name.ToIdentifierToken()))))));
}
private static MemberDeclarationSyntax GenerateEventDeclarationWorker(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(@event.ExplicitInterfaceImplementations);
return AddFormatterAndCodeGeneratorAnnotationsTo(SyntaxFactory.EventDeclaration(
attributeLists: AttributeGenerator.GenerateAttributeLists(@event.GetAttributes(), options),
modifiers: GenerateModifiers(@event, destination, options),
type: @event.Type.GenerateTypeSyntax(),
explicitInterfaceSpecifier: explicitInterfaceSpecifier,
identifier: @event.Name.ToIdentifierToken(),
accessorList: GenerateAccessorList(@event, destination, options)));
}
private static AccessorListSyntax GenerateAccessorList(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var accessors = new List<AccessorDeclarationSyntax>
{
GenerateAccessorDeclaration(@event, @event.AddMethod, SyntaxKind.AddAccessorDeclaration, destination, options),
GenerateAccessorDeclaration(@event, @event.RemoveMethod, SyntaxKind.RemoveAccessorDeclaration, destination, options),
};
return SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList());
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IEventSymbol @event,
IMethodSymbol accessor,
SyntaxKind kind,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var hasBody = options.GenerateMethodBodies && HasAccessorBodies(@event, destination, accessor);
return accessor == null
? null
: GenerateAccessorDeclaration(accessor, kind, hasBody);
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IMethodSymbol accessor,
SyntaxKind kind,
bool hasBody)
{
return AddAnnotationsTo(accessor, SyntaxFactory.AccessorDeclaration(kind)
.WithBody(hasBody ? GenerateBlock(accessor) : null)
.WithSemicolonToken(hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
private static BlockSyntax GenerateBlock(IMethodSymbol accessor)
{
return SyntaxFactory.Block(
StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor)));
}
private static bool HasAccessorBodies(
IEventSymbol @event,
CodeGenerationDestination destination,
IMethodSymbol accessor)
{
return destination != CodeGenerationDestination.InterfaceType &&
[email protected] &&
accessor != null &&
!accessor.IsAbstract;
}
private static SyntaxTokenList GenerateModifiers(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var tokens = ArrayBuilder<SyntaxToken>.GetInstance();
// Most modifiers not allowed if we're an explicit impl.
if ([email protected]())
{
if (destination != CodeGenerationDestination.InterfaceType)
{
AddAccessibilityModifiers(@event.DeclaredAccessibility, tokens, options, Accessibility.Private);
if (@event.IsStatic)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
// An event is readonly if its accessors are readonly.
// If one accessor is readonly and the other one is not,
// the event is malformed and cannot be properly displayed.
// See https://github.com/dotnet/roslyn/issues/34213
// Don't show the readonly modifier if the containing type is already readonly
if (@event.AddMethod?.IsReadOnly == true && [email protected])
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
if (@event.IsAbstract)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword));
}
if (@event.IsOverride)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword));
}
}
}
if (CodeGenerationEventInfo.GetIsUnsafe(@event))
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
return tokens.ToSyntaxTokenListAndFree();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class EventGenerator
{
private static MemberDeclarationSyntax AfterMember(
SyntaxList<MemberDeclarationSyntax> members,
MemberDeclarationSyntax eventDeclaration)
{
if (eventDeclaration.Kind() == SyntaxKind.EventFieldDeclaration)
{
// Field style events go after the last field event, or after the last field.
var lastEvent = members.LastOrDefault(m => m is EventFieldDeclarationSyntax);
return lastEvent ?? LastField(members);
}
if (eventDeclaration.Kind() == SyntaxKind.EventDeclaration)
{
// Property style events go after existing events, then after existing constructors.
var lastEvent = members.LastOrDefault(m => m is EventDeclarationSyntax);
return lastEvent ?? LastConstructor(members);
}
return null;
}
private static MemberDeclarationSyntax BeforeMember(
SyntaxList<MemberDeclarationSyntax> members,
MemberDeclarationSyntax eventDeclaration)
{
// If it's a field style event, then it goes before everything else if we don't have any
// existing fields/events.
if (eventDeclaration.Kind() == SyntaxKind.FieldDeclaration)
{
return members.FirstOrDefault();
}
// Otherwise just place it before the methods.
return FirstMethod(members);
}
internal static CompilationUnitSyntax AddEventTo(
CompilationUnitSyntax destination,
IEventSymbol @event,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateEventDeclaration(@event, CodeGenerationDestination.CompilationUnit, options);
// Place the event depending on its shape. Field style events go with fields, property
// style events go with properties. If there
var members = Insert(destination.Members, declaration, options, availableIndices,
after: list => AfterMember(list, declaration), before: list => BeforeMember(list, declaration));
return destination.WithMembers(members.ToSyntaxList());
}
internal static TypeDeclarationSyntax AddEventTo(
TypeDeclarationSyntax destination,
IEventSymbol @event,
CodeGenerationOptions options,
IList<bool> availableIndices)
{
var declaration = GenerateEventDeclaration(@event, GetDestination(destination), options);
var members = Insert(destination.Members, declaration, options, availableIndices,
after: list => AfterMember(list, declaration),
before: list => BeforeMember(list, declaration));
// Find the best place to put the field. It should go after the last field if we already
// have fields, or at the beginning of the file if we don't.
return AddMembersTo(destination, members);
}
public static MemberDeclarationSyntax GenerateEventDeclaration(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(@event, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
var declaration = !options.GenerateMethodBodies || @event.IsAbstract || @event.AddMethod == null || @event.RemoveMethod == null
? GenerateEventFieldDeclaration(@event, destination, options)
: GenerateEventDeclarationWorker(@event, destination, options);
return ConditionallyAddDocumentationCommentTo(declaration, @event, options);
}
private static MemberDeclarationSyntax GenerateEventFieldDeclaration(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
return AddFormatterAndCodeGeneratorAnnotationsTo(
AddAnnotationsTo(@event,
SyntaxFactory.EventFieldDeclaration(
AttributeGenerator.GenerateAttributeLists(@event.GetAttributes(), options),
GenerateModifiers(@event, destination, options),
SyntaxFactory.VariableDeclaration(
@event.Type.GenerateTypeSyntax(),
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(@event.Name.ToIdentifierToken()))))));
}
private static MemberDeclarationSyntax GenerateEventDeclarationWorker(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(@event.ExplicitInterfaceImplementations);
return AddFormatterAndCodeGeneratorAnnotationsTo(SyntaxFactory.EventDeclaration(
attributeLists: AttributeGenerator.GenerateAttributeLists(@event.GetAttributes(), options),
modifiers: GenerateModifiers(@event, destination, options),
type: @event.Type.GenerateTypeSyntax(),
explicitInterfaceSpecifier: explicitInterfaceSpecifier,
identifier: @event.Name.ToIdentifierToken(),
accessorList: GenerateAccessorList(@event, destination, options)));
}
private static AccessorListSyntax GenerateAccessorList(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var accessors = new List<AccessorDeclarationSyntax>
{
GenerateAccessorDeclaration(@event, @event.AddMethod, SyntaxKind.AddAccessorDeclaration, destination, options),
GenerateAccessorDeclaration(@event, @event.RemoveMethod, SyntaxKind.RemoveAccessorDeclaration, destination, options),
};
return SyntaxFactory.AccessorList(accessors.WhereNotNull().ToSyntaxList());
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IEventSymbol @event,
IMethodSymbol accessor,
SyntaxKind kind,
CodeGenerationDestination destination,
CodeGenerationOptions options)
{
var hasBody = options.GenerateMethodBodies && HasAccessorBodies(@event, destination, accessor);
return accessor == null
? null
: GenerateAccessorDeclaration(accessor, kind, hasBody);
}
private static AccessorDeclarationSyntax GenerateAccessorDeclaration(
IMethodSymbol accessor,
SyntaxKind kind,
bool hasBody)
{
return AddAnnotationsTo(accessor, SyntaxFactory.AccessorDeclaration(kind)
.WithBody(hasBody ? GenerateBlock(accessor) : null)
.WithSemicolonToken(hasBody ? default : SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
private static BlockSyntax GenerateBlock(IMethodSymbol accessor)
{
return SyntaxFactory.Block(
StatementGenerator.GenerateStatements(CodeGenerationMethodInfo.GetStatements(accessor)));
}
private static bool HasAccessorBodies(
IEventSymbol @event,
CodeGenerationDestination destination,
IMethodSymbol accessor)
{
return destination != CodeGenerationDestination.InterfaceType &&
[email protected] &&
accessor != null &&
!accessor.IsAbstract;
}
private static SyntaxTokenList GenerateModifiers(
IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options)
{
var tokens = ArrayBuilder<SyntaxToken>.GetInstance();
// Most modifiers not allowed if we're an explicit impl.
if ([email protected]())
{
if (destination != CodeGenerationDestination.InterfaceType)
{
AddAccessibilityModifiers(@event.DeclaredAccessibility, tokens, options, Accessibility.Private);
if (@event.IsStatic)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
}
// An event is readonly if its accessors are readonly.
// If one accessor is readonly and the other one is not,
// the event is malformed and cannot be properly displayed.
// See https://github.com/dotnet/roslyn/issues/34213
// Don't show the readonly modifier if the containing type is already readonly
if (@event.AddMethod?.IsReadOnly == true && [email protected])
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
}
if (@event.IsAbstract)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword));
}
if (@event.IsOverride)
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword));
}
}
}
if (CodeGenerationEventInfo.GetIsUnsafe(@event))
{
tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword));
}
return tokens.ToSyntaxTokenListAndFree();
}
}
}
| -1 |
dotnet/roslyn | 55,095 | Inline diagnostics and intellicode cohesion | Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | akhera99 | 2021-07-23T23:20:09Z | 2021-09-30T01:18:39Z | 978aa01311d58dd1c851a38fb7c5dbd79bedd2de | af66de2478e114033e25ade23f05d69968911236 | Inline diagnostics and intellicode cohesion. Hola
Here is the work to handle intersecting adornments on the editor. With the added IEndOfLineAdornmentTag, the editor team raises TagsChanged for that tag when intellicode (+ other features that show up on the editor) get added. I look for those tag changed events to remove/readd my adornments.
The IEndOfLineAdornmentTag has a lot of properties that are not currently being used, but can be used in the future if we want to have them lay together on the editor. | ./src/Features/LanguageServer/Protocol/Handler/FoldingRanges/FoldingRangesHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentFoldingRangeName)]
internal sealed class FoldingRangesHandler : AbstractStatelessRequestHandler<FoldingRangeParams, FoldingRange[]>
{
public override string Method => Methods.TextDocumentFoldingRangeName;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FoldingRangesHandler()
{
}
public override TextDocumentIdentifier? GetTextDocumentIdentifier(FoldingRangeParams request) => request.TextDocument;
public override async Task<FoldingRange[]> HandleRequestAsync(FoldingRangeParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
{
return Array.Empty<FoldingRange>();
}
var blockStructureService = document.Project.LanguageServices.GetService<BlockStructureService>();
if (blockStructureService == null)
{
return Array.Empty<FoldingRange>();
}
var blockStructure = await blockStructureService.GetBlockStructureAsync(document, cancellationToken).ConfigureAwait(false);
if (blockStructure == null)
{
return Array.Empty<FoldingRange>();
}
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
return GetFoldingRanges(blockStructure, text);
}
public static FoldingRange[] GetFoldingRanges(
SyntaxTree syntaxTree,
HostLanguageServices languageServices,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var blockStructureService = (BlockStructureServiceWithProviders)languageServices.GetRequiredService<BlockStructureService>();
var blockStructure = blockStructureService.GetBlockStructure(syntaxTree, options, isMetadataAsSource, cancellationToken);
if (blockStructure == null)
{
return Array.Empty<FoldingRange>();
}
var text = syntaxTree.GetText(cancellationToken);
return GetFoldingRanges(blockStructure, text);
}
private static FoldingRange[] GetFoldingRanges(BlockStructure blockStructure, SourceText text)
{
if (blockStructure.Spans.IsEmpty)
{
return Array.Empty<FoldingRange>();
}
using var _ = ArrayBuilder<FoldingRange>.GetInstance(out var foldingRanges);
foreach (var span in blockStructure.Spans)
{
if (!span.IsCollapsible)
{
continue;
}
var linePositionSpan = text.Lines.GetLinePositionSpan(span.TextSpan);
// Filter out single line spans.
if (linePositionSpan.Start.Line == linePositionSpan.End.Line)
{
continue;
}
// TODO - Figure out which blocks should be returned as a folding range (and what kind).
// https://github.com/dotnet/roslyn/projects/45#card-20049168
FoldingRangeKind? foldingRangeKind = span.Type switch
{
BlockTypes.Comment => FoldingRangeKind.Comment,
BlockTypes.Imports => FoldingRangeKind.Imports,
BlockTypes.PreprocessorRegion => FoldingRangeKind.Region,
_ => null,
};
foldingRanges.Add(new FoldingRange()
{
StartLine = linePositionSpan.Start.Line,
StartCharacter = linePositionSpan.Start.Character,
EndLine = linePositionSpan.End.Line,
EndCharacter = linePositionSpan.End.Character,
Kind = foldingRangeKind
});
}
return foldingRanges.ToArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[ExportRoslynLanguagesLspRequestHandlerProvider, Shared]
[ProvidesMethod(Methods.TextDocumentFoldingRangeName)]
internal sealed class FoldingRangesHandler : AbstractStatelessRequestHandler<FoldingRangeParams, FoldingRange[]>
{
public override string Method => Methods.TextDocumentFoldingRangeName;
public override bool MutatesSolutionState => false;
public override bool RequiresLSPSolution => true;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FoldingRangesHandler()
{
}
public override TextDocumentIdentifier? GetTextDocumentIdentifier(FoldingRangeParams request) => request.TextDocument;
public override async Task<FoldingRange[]> HandleRequestAsync(FoldingRangeParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
{
return Array.Empty<FoldingRange>();
}
var blockStructureService = document.Project.LanguageServices.GetService<BlockStructureService>();
if (blockStructureService == null)
{
return Array.Empty<FoldingRange>();
}
var blockStructure = await blockStructureService.GetBlockStructureAsync(document, cancellationToken).ConfigureAwait(false);
if (blockStructure == null)
{
return Array.Empty<FoldingRange>();
}
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
return GetFoldingRanges(blockStructure, text);
}
public static FoldingRange[] GetFoldingRanges(
SyntaxTree syntaxTree,
HostLanguageServices languageServices,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var blockStructureService = (BlockStructureServiceWithProviders)languageServices.GetRequiredService<BlockStructureService>();
var blockStructure = blockStructureService.GetBlockStructure(syntaxTree, options, isMetadataAsSource, cancellationToken);
if (blockStructure == null)
{
return Array.Empty<FoldingRange>();
}
var text = syntaxTree.GetText(cancellationToken);
return GetFoldingRanges(blockStructure, text);
}
private static FoldingRange[] GetFoldingRanges(BlockStructure blockStructure, SourceText text)
{
if (blockStructure.Spans.IsEmpty)
{
return Array.Empty<FoldingRange>();
}
using var _ = ArrayBuilder<FoldingRange>.GetInstance(out var foldingRanges);
foreach (var span in blockStructure.Spans)
{
if (!span.IsCollapsible)
{
continue;
}
var linePositionSpan = text.Lines.GetLinePositionSpan(span.TextSpan);
// Filter out single line spans.
if (linePositionSpan.Start.Line == linePositionSpan.End.Line)
{
continue;
}
// TODO - Figure out which blocks should be returned as a folding range (and what kind).
// https://github.com/dotnet/roslyn/projects/45#card-20049168
FoldingRangeKind? foldingRangeKind = span.Type switch
{
BlockTypes.Comment => FoldingRangeKind.Comment,
BlockTypes.Imports => FoldingRangeKind.Imports,
BlockTypes.PreprocessorRegion => FoldingRangeKind.Region,
_ => null,
};
foldingRanges.Add(new FoldingRange()
{
StartLine = linePositionSpan.Start.Line,
StartCharacter = linePositionSpan.Start.Character,
EndLine = linePositionSpan.End.Line,
EndCharacter = linePositionSpan.End.Character,
Kind = foldingRangeKind
});
}
return foldingRanges.ToArray();
}
}
}
| -1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/VisualStudio/CSharp/Impl/Progression/CSharpGraphProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.Progression;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Progression
{
[GraphProvider(Name = "CSharpRoslynProvider", ProjectCapability = "CSharp")]
internal sealed class CSharpGraphProvider : AbstractGraphProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpGraphProvider(
IThreadingContext threadingContext,
IGlyphService glyphService,
SVsServiceProvider serviceProvider,
IProgressionPrimaryWorkspaceProvider workspaceProvider,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, glyphService, serviceProvider, workspaceProvider.PrimaryWorkspace, listenerProvider)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.Progression;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Progression
{
[GraphProvider(Name = "CSharpRoslynProvider", ProjectCapability = "CSharp")]
internal sealed class CSharpGraphProvider : AbstractGraphProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpGraphProvider(
IThreadingContext threadingContext,
IGlyphService glyphService,
SVsServiceProvider serviceProvider,
VisualStudioWorkspace workspace,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, glyphService, serviceProvider, workspace, listenerProvider)
{
}
}
}
| 1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/VisualStudio/Core/Def/Guids.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices
{
internal static class Guids
{
public const string CSharpPackageIdString = "13c3bbb4-f18f-4111-9f54-a0fb010d9194";
public const string CSharpProjectIdString = "fae04ec0-301f-11d3-bf4b-00c04f79efbc";
public const string CSharpLanguageServiceIdString = "694dd9b6-b865-4c5b-ad85-86356e9c88dc";
public const string CSharpEditorFactoryIdString = "a6c744a8-0e4a-4fc6-886a-064283054674";
public const string CSharpCodePageEditorFactoryIdString = "08467b34-b90f-4d91-bdca-eb8c8cf3033a";
public const string CSharpCommandSetIdString = "d91af2f7-61f6-4d90-be23-d057d2ea961b";
public const string CSharpGroupIdString = "5d7e7f65-a63f-46ee-84f1-990b2cab23f9";
public const string CSharpRefactorIconIdString = "b293db8b-3c72-4720-9966-2083af84dd82";
public const string CSharpGenerateIconIdString = "ac9a0910-d9fd-4f2e-b9a1-acdc5d514437";
public const string CSharpOrganizeIconIdString = "9420a4b2-b48b-449d-a4c0-335d6e864b82";
public const string CSharpLibraryIdString = "58F1BAD0-2288-45b9-AC3A-D56398F7781D";
public const string CSharpReplPackageIdString = "c5edd1ee-c43b-4360-9ce4-6b993ca12897";
/// <summary>
/// <see cref="UIContext"/> that indicates <see cref="VisualStudioWorkspace"/> contains a project that supports Edit and Continue.
/// </summary>
public const string EncCapableProjectExistsInWorkspaceUIContextString = "0C89AE24-6D19-474C-A3AA-DC3B66FDBB5F";
/// <summary>
/// A <see cref="UIContext"/> that is set if there is a C# project in the <see cref="VisualStudioWorkspace"/>.
/// </summary>
public const string CSharpProjectExistsInWorkspaceUIContextString = "CA719A03-D55C-48F9-85DE-D934346E7F70";
public static readonly Guid CSharpProjectExistsInWorkspaceUIContext = new(CSharpProjectExistsInWorkspaceUIContextString);
public const string CSharpProjectRootIdString = "C7FEDB89-B36D-4a62-93F4-DC7A95999921";
// from debugger\idl\makeapi\guid.c
public const string CSharpDebuggerLanguageIdString = "3f5162f8-07c6-11d3-9053-00c04fa302a1";
public static readonly Guid CSharpPackageId = new(CSharpPackageIdString);
public static readonly Guid CSharpProjectId = new(CSharpProjectIdString);
public static readonly Guid CSharpLanguageServiceId = new(CSharpLanguageServiceIdString);
public static readonly Guid CSharpEditorFactoryId = new(CSharpEditorFactoryIdString);
public static readonly Guid CSharpCodePageEditorFactoryId = new(CSharpCodePageEditorFactoryIdString);
public static readonly Guid CSharpCommandSetId = new(CSharpCommandSetIdString); // guidCSharpCmdId
public static readonly Guid CSharpGroupId = new(CSharpGroupIdString); // guidCSharpGrpId
public static readonly Guid CSharpRefactorIconId = new(CSharpRefactorIconIdString); // guidCSharpRefactorIcon
public static readonly Guid CSharpGenerateIconId = new(CSharpGenerateIconIdString); // guidCSharpGenerateIcon
public static readonly Guid CSharpOrganizeIconId = new(CSharpOrganizeIconIdString); // guidCSharpOrganizeIcon
public static readonly Guid CSharpDebuggerLanguageId = new(CSharpDebuggerLanguageIdString);
public static readonly Guid CSharpLibraryId = new(CSharpLibraryIdString);
// option page guids from csharp\rad\pkg\guids.h
public const string CSharpOptionPageAdvancedIdString = "8FD0B177-B244-4A97-8E37-6FB7B27DE3AF";
public const string CSharpOptionPageNamingStyleIdString = "294FBC9C-EF70-4AA0-BD4F-EB0C6A5908D7";
public const string CSharpOptionPageIntelliSenseIdString = "EDE66829-7A36-4c5d-8E20-9290195DCF80";
public const string CSharpOptionPageCodeStyleIdString = "EAE577A7-ACB9-40F5-A7B1-D2878C3C7D6F";
public const string CSharpOptionPageFormattingGeneralIdString = "DA0446DD-55BA-401F-A364-7D3238412AE4";
public const string CSharpOptionPageFormattingIndentationIdString = "5E21D017-6D2A-4114-A1F1-C923F001CBBB";
public const string CSharpOptionPageFormattingNewLinesIdString = "EADC6AD3-91D4-3CC8-BE96-3CDE7D3080F0";
public const string CSharpOptionPageFormattingSpacingIdString = "234FB566-73DD-4612-8DE4-29031FF27052";
public const string CSharpOptionPageFormattingWrappingIdString = "8E334D9C-B7DC-4CF3-B7B7-014B831FE76B";
public const string VisualBasicPackageIdString = "574fc912-f74f-4b4e-92c3-f695c208a2bb";
public const string VisualBasicReplPackageIdString = "F5C61C13-7037-4C50-98E6-ACC313359A34";
public const string VbCompilerProjectIdString = "12C8A7D2-4681-11D2-B48A-0000F87572EB";
public const string VisualBasicProjectIdString = "F184B08F-C81C-45F6-A57F-5ABD9991F28F";
public const string VisualBasicCompilerServiceIdString = "019971d6-4685-11d2-b48a-0000f87572eb";
public const string VisualBasicLanguageServiceIdString = "e34acdc0-baae-11d0-88bf-00a0c9110049";
public const string VisualBasicEditorFactoryIdString = "2c015c70-c72c-11d0-88c3-00a0c9110049";
public const string VisualBasicCodePageEditorFactoryIdString = "6c33e1aa-1401-4536-ab67-0e21e6e569da";
public const string VisualBasicDebuggerLanguageIdString = "3a12d0b8-c26c-11d0-b442-00a0244a1dd2";
public const string VisualBasicLibraryIdString = "414AC972-9829-4b6a-A8D7-A08152FEB8AA";
public const string VisualBasicOptionPageCodeStyleIdString = "10C168E1-3470-448A-A1AC-73D6BC070750";
/// <summary>
/// A <see cref="UIContext"/> that is set if there is a Visual Basic project in the <see cref="VisualStudioWorkspace"/>.
/// </summary>
public const string VisualBasicProjectExistsInWorkspaceUIContextString = "EEC3DF0D-6D3F-4544-ABF9-8E26E6A90275";
public static readonly Guid VisualBasicProjectExistsInWorkspaceUIContext = new(VisualBasicProjectExistsInWorkspaceUIContextString);
public static readonly Guid VisualBasicPackageId = new(VisualBasicPackageIdString);
public static readonly Guid VisualBasicCompilerServiceId = new(VisualBasicCompilerServiceIdString);
public static readonly Guid VisualBasicLanguageServiceId = new(VisualBasicLanguageServiceIdString);
public static readonly Guid VisualBasicEditorFactoryId = new(VisualBasicEditorFactoryIdString);
public static readonly Guid VisualBasicCodePageEditorFactoryId = new(VisualBasicCodePageEditorFactoryIdString);
public static readonly Guid VisualBasicLibraryId = new(VisualBasicLibraryIdString);
public static readonly Guid VisualBasicProjectId = new(VisualBasicProjectIdString);
// from debugger\idl\makeapi\guid.c
public static readonly Guid VisualBasicDebuggerLanguageId = new(VisualBasicDebuggerLanguageIdString);
// option page guid from setupauthoring\vb\components\vblanguageservice.pkgdef
public const string VisualBasicOptionPageVBSpecificIdString = "F1E1021E-A781-4862-9F4B-88746A288A67";
public const string VisualBasicOptionPageNamingStyleIdString = "BCA454E0-95E4-4877-B4CB-B1D642B7BAFA";
public const string VisualBasicOptionPageIntelliSenseIdString = "04460A3B-1B5F-4402-BC6D-89A4F6F0A8D7";
public const string FSharpPackageIdString = "871D2A70-12A2-4e42-9440-425DD92A4116";
public static readonly Guid FSharpPackageId = new(FSharpPackageIdString);
// from vscommon\inc\textmgruuids.h
public const string TextManagerPackageString = "F5E7E720-1401-11D1-883B-0000F87579D2";
// Roslyn guids
public const string RoslynPackageIdString = "6cf2e545-6109-4730-8883-cf43d7aec3e1";
public const string RoslynCommandSetIdString = "9ed8fbd1-02d6-4223-a99c-a938f97e6dbe";
public const string RoslynGroupIdString = "b61e1a20-8c13-49a9-a727-a0ec091647dd";
public const string RoslynOptionPageFeatureManagerComponentsIdString = "6F738951-348C-4816-9BA4-F60D92D3E98E";
public const string RoslynOptionPageFeatureManagerFeaturesIdString = "67989704-F8D7-454A-9053-8E1D3CFF679C";
public const string RoslynOptionPagePerformanceFunctionIdIdString = "0C537218-3BDD-4CC8-AC4B-CEC152D4871A";
public const string RoslynOptionPagePerformanceLoggersIdString = "236AC96F-A60D-4BD6-A480-D315151EDC2B";
public const string RoslynOptionPageInternalDiagnosticsIdString = "48993C4C-C619-42AD-B1C8-79378AD8BEF2";
public const string RoslynOptionPageInternalSolutionCrawlerIdString = "9702D3BD-F06C-4A6A-974B-7D0C2BC89A72";
public const string RoslynOptionPageExperimentationIdString = "D5AA7ED7-85E2-42A0-9BF6-22AEF1C1ED8C";
public static readonly Guid RoslynPackageId = new(RoslynPackageIdString);
public static readonly Guid RoslynCommandSetId = new(RoslynCommandSetIdString);
public static readonly Guid RoslynGroupId = new(RoslynGroupIdString);
public const string ValueTrackingToolWindowIdString = "60a19d42-2dd7-43f3-be90-c7a9cb7d28f4";
public static readonly Guid ValueTrackingToolWindowId = new(ValueTrackingToolWindowIdString);
// TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 .
// Interactive guids
public const string InteractiveCommandSetIdString = "00B8868B-F9F5-4970-A048-410B05508506";
public static readonly Guid InteractiveCommandSetId = new(InteractiveCommandSetIdString);
/// <summary>
/// The package GUID for GlobalHubClientPackage, which proffers ServiceHub brokered services in Visual Studio.
/// </summary>
public static readonly Guid GlobalHubClientPackageGuid = new("11AD60FC-6D87-4674-8F88-9ABE79176CBE");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.LanguageServices
{
internal static class Guids
{
public const string CSharpPackageIdString = "13c3bbb4-f18f-4111-9f54-a0fb010d9194";
public const string CSharpProjectIdString = "fae04ec0-301f-11d3-bf4b-00c04f79efbc";
public const string CSharpLanguageServiceIdString = "694dd9b6-b865-4c5b-ad85-86356e9c88dc";
public const string CSharpEditorFactoryIdString = "a6c744a8-0e4a-4fc6-886a-064283054674";
public const string CSharpCodePageEditorFactoryIdString = "08467b34-b90f-4d91-bdca-eb8c8cf3033a";
public const string CSharpCommandSetIdString = "d91af2f7-61f6-4d90-be23-d057d2ea961b";
public const string CSharpGroupIdString = "5d7e7f65-a63f-46ee-84f1-990b2cab23f9";
public const string CSharpRefactorIconIdString = "b293db8b-3c72-4720-9966-2083af84dd82";
public const string CSharpGenerateIconIdString = "ac9a0910-d9fd-4f2e-b9a1-acdc5d514437";
public const string CSharpOrganizeIconIdString = "9420a4b2-b48b-449d-a4c0-335d6e864b82";
public const string CSharpLibraryIdString = "58F1BAD0-2288-45b9-AC3A-D56398F7781D";
public const string CSharpReplPackageIdString = "c5edd1ee-c43b-4360-9ce4-6b993ca12897";
/// <summary>
/// A <see cref="UIContext"/> that is set if there is a C# project in the <see cref="VisualStudioWorkspace"/>.
/// </summary>
public const string CSharpProjectExistsInWorkspaceUIContextString = "CA719A03-D55C-48F9-85DE-D934346E7F70";
public static readonly Guid CSharpProjectExistsInWorkspaceUIContext = new(CSharpProjectExistsInWorkspaceUIContextString);
public const string CSharpProjectRootIdString = "C7FEDB89-B36D-4a62-93F4-DC7A95999921";
// from debugger\idl\makeapi\guid.c
public const string CSharpDebuggerLanguageIdString = "3f5162f8-07c6-11d3-9053-00c04fa302a1";
public static readonly Guid CSharpPackageId = new(CSharpPackageIdString);
public static readonly Guid CSharpProjectId = new(CSharpProjectIdString);
public static readonly Guid CSharpLanguageServiceId = new(CSharpLanguageServiceIdString);
public static readonly Guid CSharpEditorFactoryId = new(CSharpEditorFactoryIdString);
public static readonly Guid CSharpCodePageEditorFactoryId = new(CSharpCodePageEditorFactoryIdString);
public static readonly Guid CSharpCommandSetId = new(CSharpCommandSetIdString); // guidCSharpCmdId
public static readonly Guid CSharpGroupId = new(CSharpGroupIdString); // guidCSharpGrpId
public static readonly Guid CSharpRefactorIconId = new(CSharpRefactorIconIdString); // guidCSharpRefactorIcon
public static readonly Guid CSharpGenerateIconId = new(CSharpGenerateIconIdString); // guidCSharpGenerateIcon
public static readonly Guid CSharpOrganizeIconId = new(CSharpOrganizeIconIdString); // guidCSharpOrganizeIcon
public static readonly Guid CSharpDebuggerLanguageId = new(CSharpDebuggerLanguageIdString);
public static readonly Guid CSharpLibraryId = new(CSharpLibraryIdString);
// option page guids from csharp\rad\pkg\guids.h
public const string CSharpOptionPageAdvancedIdString = "8FD0B177-B244-4A97-8E37-6FB7B27DE3AF";
public const string CSharpOptionPageNamingStyleIdString = "294FBC9C-EF70-4AA0-BD4F-EB0C6A5908D7";
public const string CSharpOptionPageIntelliSenseIdString = "EDE66829-7A36-4c5d-8E20-9290195DCF80";
public const string CSharpOptionPageCodeStyleIdString = "EAE577A7-ACB9-40F5-A7B1-D2878C3C7D6F";
public const string CSharpOptionPageFormattingGeneralIdString = "DA0446DD-55BA-401F-A364-7D3238412AE4";
public const string CSharpOptionPageFormattingIndentationIdString = "5E21D017-6D2A-4114-A1F1-C923F001CBBB";
public const string CSharpOptionPageFormattingNewLinesIdString = "EADC6AD3-91D4-3CC8-BE96-3CDE7D3080F0";
public const string CSharpOptionPageFormattingSpacingIdString = "234FB566-73DD-4612-8DE4-29031FF27052";
public const string CSharpOptionPageFormattingWrappingIdString = "8E334D9C-B7DC-4CF3-B7B7-014B831FE76B";
public const string VisualBasicPackageIdString = "574fc912-f74f-4b4e-92c3-f695c208a2bb";
public const string VisualBasicReplPackageIdString = "F5C61C13-7037-4C50-98E6-ACC313359A34";
public const string VbCompilerProjectIdString = "12C8A7D2-4681-11D2-B48A-0000F87572EB";
public const string VisualBasicProjectIdString = "F184B08F-C81C-45F6-A57F-5ABD9991F28F";
public const string VisualBasicCompilerServiceIdString = "019971d6-4685-11d2-b48a-0000f87572eb";
public const string VisualBasicLanguageServiceIdString = "e34acdc0-baae-11d0-88bf-00a0c9110049";
public const string VisualBasicEditorFactoryIdString = "2c015c70-c72c-11d0-88c3-00a0c9110049";
public const string VisualBasicCodePageEditorFactoryIdString = "6c33e1aa-1401-4536-ab67-0e21e6e569da";
public const string VisualBasicDebuggerLanguageIdString = "3a12d0b8-c26c-11d0-b442-00a0244a1dd2";
public const string VisualBasicLibraryIdString = "414AC972-9829-4b6a-A8D7-A08152FEB8AA";
public const string VisualBasicOptionPageCodeStyleIdString = "10C168E1-3470-448A-A1AC-73D6BC070750";
/// <summary>
/// A <see cref="UIContext"/> that is set if there is a Visual Basic project in the <see cref="VisualStudioWorkspace"/>.
/// </summary>
public const string VisualBasicProjectExistsInWorkspaceUIContextString = "EEC3DF0D-6D3F-4544-ABF9-8E26E6A90275";
public static readonly Guid VisualBasicProjectExistsInWorkspaceUIContext = new(VisualBasicProjectExistsInWorkspaceUIContextString);
public static readonly Guid VisualBasicPackageId = new(VisualBasicPackageIdString);
public static readonly Guid VisualBasicCompilerServiceId = new(VisualBasicCompilerServiceIdString);
public static readonly Guid VisualBasicLanguageServiceId = new(VisualBasicLanguageServiceIdString);
public static readonly Guid VisualBasicEditorFactoryId = new(VisualBasicEditorFactoryIdString);
public static readonly Guid VisualBasicCodePageEditorFactoryId = new(VisualBasicCodePageEditorFactoryIdString);
public static readonly Guid VisualBasicLibraryId = new(VisualBasicLibraryIdString);
public static readonly Guid VisualBasicProjectId = new(VisualBasicProjectIdString);
// from debugger\idl\makeapi\guid.c
public static readonly Guid VisualBasicDebuggerLanguageId = new(VisualBasicDebuggerLanguageIdString);
// option page guid from setupauthoring\vb\components\vblanguageservice.pkgdef
public const string VisualBasicOptionPageVBSpecificIdString = "F1E1021E-A781-4862-9F4B-88746A288A67";
public const string VisualBasicOptionPageNamingStyleIdString = "BCA454E0-95E4-4877-B4CB-B1D642B7BAFA";
public const string VisualBasicOptionPageIntelliSenseIdString = "04460A3B-1B5F-4402-BC6D-89A4F6F0A8D7";
public const string FSharpPackageIdString = "871D2A70-12A2-4e42-9440-425DD92A4116";
public static readonly Guid FSharpPackageId = new(FSharpPackageIdString);
// from vscommon\inc\textmgruuids.h
public const string TextManagerPackageString = "F5E7E720-1401-11D1-883B-0000F87579D2";
// Roslyn guids
public const string RoslynPackageIdString = "6cf2e545-6109-4730-8883-cf43d7aec3e1";
public const string RoslynCommandSetIdString = "9ed8fbd1-02d6-4223-a99c-a938f97e6dbe";
public const string RoslynGroupIdString = "b61e1a20-8c13-49a9-a727-a0ec091647dd";
public const string RoslynOptionPageFeatureManagerComponentsIdString = "6F738951-348C-4816-9BA4-F60D92D3E98E";
public const string RoslynOptionPageFeatureManagerFeaturesIdString = "67989704-F8D7-454A-9053-8E1D3CFF679C";
public const string RoslynOptionPagePerformanceFunctionIdIdString = "0C537218-3BDD-4CC8-AC4B-CEC152D4871A";
public const string RoslynOptionPagePerformanceLoggersIdString = "236AC96F-A60D-4BD6-A480-D315151EDC2B";
public const string RoslynOptionPageInternalDiagnosticsIdString = "48993C4C-C619-42AD-B1C8-79378AD8BEF2";
public const string RoslynOptionPageInternalSolutionCrawlerIdString = "9702D3BD-F06C-4A6A-974B-7D0C2BC89A72";
public const string RoslynOptionPageExperimentationIdString = "D5AA7ED7-85E2-42A0-9BF6-22AEF1C1ED8C";
public static readonly Guid RoslynPackageId = new(RoslynPackageIdString);
public static readonly Guid RoslynCommandSetId = new(RoslynCommandSetIdString);
public static readonly Guid RoslynGroupId = new(RoslynGroupIdString);
public const string ValueTrackingToolWindowIdString = "60a19d42-2dd7-43f3-be90-c7a9cb7d28f4";
public static readonly Guid ValueTrackingToolWindowId = new(ValueTrackingToolWindowIdString);
// TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 .
// Interactive guids
public const string InteractiveCommandSetIdString = "00B8868B-F9F5-4970-A048-410B05508506";
public static readonly Guid InteractiveCommandSetId = new(InteractiveCommandSetIdString);
/// <summary>
/// The package GUID for GlobalHubClientPackage, which proffers ServiceHub brokered services in Visual Studio.
/// </summary>
public static readonly Guid GlobalHubClientPackageGuid = new("11AD60FC-6D87-4674-8F88-9ABE79176CBE");
}
}
| 1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/VisualStudio/VisualBasic/Impl/Progression/VisualBasicGraphProvider.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 Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.Language.Intellisense
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Microsoft.VisualStudio.Shell
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression
<GraphProvider(Name:="VisualBasicRoslynProvider", ProjectCapability:="VB")>
Friend NotInheritable Class VisualBasicGraphProvider
Inherits AbstractGraphProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(threadingContext As IThreadingContext, glyphService As IGlyphService, serviceProvider As SVsServiceProvider, workspaceProvider As IProgressionPrimaryWorkspaceProvider, listenerProvider As IAsynchronousOperationListenerProvider)
MyBase.New(threadingContext, glyphService, serviceProvider, workspaceProvider.PrimaryWorkspace, listenerProvider)
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 Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Shared.TestHooks
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.Language.Intellisense
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Microsoft.VisualStudio.Shell
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression
<GraphProvider(Name:="VisualBasicRoslynProvider", ProjectCapability:="VB")>
Friend NotInheritable Class VisualBasicGraphProvider
Inherits AbstractGraphProvider
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New(threadingContext As IThreadingContext, glyphService As IGlyphService, serviceProvider As SVsServiceProvider, workspace As VisualStudioWorkspace, listenerProvider As IAsynchronousOperationListenerProvider)
MyBase.New(threadingContext, glyphService, serviceProvider, workspace, listenerProvider)
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelNavigationPointServiceFactory.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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel
<ExportLanguageServiceFactory(GetType(ICodeModelNavigationPointService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicCodeModelNavigationPointServiceFactory
Implements ILanguageServiceFactory
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
' This interface is implemented by the ICodeModelService as well, so just grab the other one and return it
Return provider.GetService(Of ICodeModelService)
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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.LanguageServices.Implementation
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel
<ExportLanguageServiceFactory(GetType(ICodeModelNavigationPointService), LanguageNames.VisualBasic), [Shared]>
Partial Friend Class VisualBasicCodeModelNavigationPointServiceFactory
Implements ILanguageServiceFactory
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function CreateLanguageService(provider As HostLanguageServices) As ILanguageService Implements ILanguageServiceFactory.CreateLanguageService
' This interface is implemented by the ICodeModelService as well, so just grab the other one and return it
Return provider.GetService(Of ICodeModelService)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/Workspaces/MSBuildTest/Resources/NetCoreApp2AndTwoLibraries/Program.cs | using System;
namespace NetCoreApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| using System;
namespace NetCoreApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
| -1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/EditorFeatures/Core/Shared/Tagging/EventSources/AbstractTaggerEventSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Editor.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal abstract class AbstractTaggerEventSource : ITaggerEventSource
{
protected AbstractTaggerEventSource()
{
}
public abstract void Connect();
public abstract void Disconnect();
public event EventHandler<TaggerEventArgs>? Changed;
protected virtual void RaiseChanged()
=> this.Changed?.Invoke(this, new TaggerEventArgs());
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Editor.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal abstract class AbstractTaggerEventSource : ITaggerEventSource
{
protected AbstractTaggerEventSource()
{
}
public abstract void Connect();
public abstract void Disconnect();
public event EventHandler<TaggerEventArgs>? Changed;
protected virtual void RaiseChanged()
=> this.Changed?.Invoke(this, new TaggerEventArgs());
}
}
| -1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 DynamicKeywordRecommenderTests : RecommenderTests
{
private readonly DynamicKeywordRecommender _recommender = new DynamicKeywordRecommender();
public DynamicKeywordRecommenderTests()
{
this.keywordText = "dynamic";
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 TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[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 TestAfterConstLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;"));
}
[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;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterRefExpression()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"ref int x = ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnumBaseTypes()
{
await VerifyAbsenceAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForeachVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFromVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInJoinVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInImplicitOperator()
{
await VerifyAbsenceAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInExplicitOperator()
{
await VerifyAbsenceAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInTypeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInSizeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(545303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545303")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreProcessor()
{
await VerifyAbsenceAsync(
@"class Program
{
#region $$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 DynamicKeywordRecommenderTests : RecommenderTests
{
private readonly DynamicKeywordRecommender _recommender = new DynamicKeywordRecommender();
public DynamicKeywordRecommenderTests()
{
this.keywordText = "dynamic";
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 TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[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 TestAfterConstLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;"));
}
[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;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterRefExpression()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"ref int x = ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnumBaseTypes()
{
await VerifyAbsenceAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForeachVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFromVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInJoinVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInImplicitOperator()
{
await VerifyAbsenceAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInExplicitOperator()
{
await VerifyAbsenceAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInTypeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInSizeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(545303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545303")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPreProcessor()
{
await VerifyAbsenceAsync(
@"class Program
{
#region $$
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
}
}
| -1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractTriviaDataFactory.ModifiedWhitespace.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract partial class AbstractTriviaDataFactory
{
protected class ModifiedWhitespace : Whitespace
{
private readonly Whitespace? _original;
public ModifiedWhitespace(AnalyzerConfigOptions options, int lineBreaks, int indentation, bool elastic, string language)
: base(options, lineBreaks, indentation, elastic, language)
{
_original = null;
}
public ModifiedWhitespace(AnalyzerConfigOptions options, Whitespace original, int lineBreaks, int indentation, bool elastic, string language)
: base(options, lineBreaks, indentation, elastic, language)
{
Contract.ThrowIfNull(original);
_original = original;
}
public override bool ContainsChanges => false;
public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules)
{
if (_original == null)
{
return base.WithSpace(space, context, formattingRules);
}
if (this.LineBreaks == _original.LineBreaks && _original.Spaces == space)
{
return _original;
}
return base.WithSpace(space, context, formattingRules);
}
public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken)
{
if (_original == null)
{
return base.WithLine(line, indentation, context, formattingRules, cancellationToken);
}
if (_original.LineBreaks == line && _original.Spaces == indentation)
{
return _original;
}
return base.WithLine(line, indentation, context, formattingRules, cancellationToken);
}
public override TriviaData WithIndentation(
int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken)
{
if (_original == null)
{
return base.WithIndentation(indentation, context, formattingRules, cancellationToken);
}
if (this.LineBreaks == _original.LineBreaks && _original.Spaces == indentation)
{
return _original;
}
return base.WithIndentation(indentation, context, formattingRules, cancellationToken);
}
public override void Format(
FormattingContext context,
ChainedFormattingRules formattingRules,
Action<int, TokenStream, TriviaData> formattingResultApplier,
CancellationToken cancellationToken,
int tokenPairIndex = TokenPairIndexNotNeeded)
{
formattingResultApplier(tokenPairIndex, context.TokenStream, new FormattedWhitespace(this.Options, this.LineBreaks, this.Spaces, this.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.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract partial class AbstractTriviaDataFactory
{
protected class ModifiedWhitespace : Whitespace
{
private readonly Whitespace? _original;
public ModifiedWhitespace(AnalyzerConfigOptions options, int lineBreaks, int indentation, bool elastic, string language)
: base(options, lineBreaks, indentation, elastic, language)
{
_original = null;
}
public ModifiedWhitespace(AnalyzerConfigOptions options, Whitespace original, int lineBreaks, int indentation, bool elastic, string language)
: base(options, lineBreaks, indentation, elastic, language)
{
Contract.ThrowIfNull(original);
_original = original;
}
public override bool ContainsChanges => false;
public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules)
{
if (_original == null)
{
return base.WithSpace(space, context, formattingRules);
}
if (this.LineBreaks == _original.LineBreaks && _original.Spaces == space)
{
return _original;
}
return base.WithSpace(space, context, formattingRules);
}
public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken)
{
if (_original == null)
{
return base.WithLine(line, indentation, context, formattingRules, cancellationToken);
}
if (_original.LineBreaks == line && _original.Spaces == indentation)
{
return _original;
}
return base.WithLine(line, indentation, context, formattingRules, cancellationToken);
}
public override TriviaData WithIndentation(
int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken)
{
if (_original == null)
{
return base.WithIndentation(indentation, context, formattingRules, cancellationToken);
}
if (this.LineBreaks == _original.LineBreaks && _original.Spaces == indentation)
{
return _original;
}
return base.WithIndentation(indentation, context, formattingRules, cancellationToken);
}
public override void Format(
FormattingContext context,
ChainedFormattingRules formattingRules,
Action<int, TokenStream, TriviaData> formattingResultApplier,
CancellationToken cancellationToken,
int tokenPairIndex = TokenPairIndexNotNeeded)
{
formattingResultApplier(tokenPairIndex, context.TokenStream, new FormattedWhitespace(this.Options, this.LineBreaks, this.Spaces, this.Language));
}
}
}
}
| -1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/TupleTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class TupleTests : ExpressionCompilerTestBase
{
[Fact]
public void Literal()
{
var source =
@"class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A", "B" }, tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
methodData.VerifyIL(
@"{
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void DuplicateValueTupleBetweenMscorlibAndLibrary()
{
var versionTemplate = @"[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]";
var corlib_cs = @"
namespace System
{
public class Object { }
public struct Int32 { }
public struct Boolean { }
public class String { }
public class ValueType { }
public struct Void { }
public class Attribute { }
}
namespace System.Reflection
{
public class AssemblyVersionAttribute : Attribute
{
public AssemblyVersionAttribute(String version) { }
}
}";
string valuetuple_cs = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}";
var corlibWithoutVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "1") + corlib_cs) }, assemblyName: "corlib");
corlibWithoutVT.VerifyDiagnostics();
var corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference();
var corlibWithVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "2") + corlib_cs + valuetuple_cs) }, assemblyName: "corlib");
corlibWithVT.VerifyDiagnostics();
var source =
@"class C
{
static (int, int) M()
{
(int, int) t = (1, 2);
return t;
}
}
";
var app = CreateEmptyCompilation(source + valuetuple_cs, references: new[] { corlibWithoutVTRef }, options: TestOptions.DebugDll);
app.VerifyDiagnostics();
// Create EE context with app assembly (including ValueTuple) and a more recent corlib (also including ValueTuple)
var runtime = CreateRuntimeInstance(new[] { app.ToModuleInstance(), corlibWithVT.ToModuleInstance() });
var evalContext = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var compileResult = evalContext.CompileExpression("(1, 2)", out error, testData);
Assert.Null(error);
using (ModuleMetadata block = ModuleMetadata.CreateFromStream(new MemoryStream(compileResult.Assembly)))
{
var reader = block.MetadataReader;
var appRef = app.Assembly.Identity.Name;
AssertEx.SetEqual(new[] { "corlib 2.0", appRef + " 0.0" }, reader.DumpAssemblyReferences());
AssertEx.SetEqual(new[] {
"Object, System, AssemblyReference:corlib",
"ValueTuple`2, System, AssemblyReference:" + appRef // ValueTuple comes from app, not corlib
},
reader.DumpTypeReferences());
}
}
[Fact]
public void TupleElementNamesAttribute_NotAvailable()
{
var source =
@"namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 _1, T2 _2)
{
Item1 = _1;
Item2 = _2;
}
}
}
class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
Assert.Null(customTypeInfo);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@" {
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void Local()
{
var source =
@"class C
{
static void M()
{
(int A\u1234, int \u1234B) o = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A\u1234", "\u1234B" }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
Assert.True(method.ReturnType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "o", expectedILOpt:
string.Format(@"{{
// Code size 2 (0x2)
.maxstack 1
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}}", '\u1234'));
locals.Free();
});
}
[Fact]
public void Constant()
{
var source =
@"class A<T>
{
internal class B<U>
{
}
}
class C
{
static (object, object) F;
static void M()
{
const A<(int, int A)>.B<(object B, object)>[] c = null;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { null, "A", "B", null }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(returnType.ContainsTuple());
VerifyLocal(testData, typeName, locals[0], "<>m0", "c", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
[Fact]
public void LongTupleLocalElement_NoNames()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, 3, 4, 5, 6, 7, 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item4 + x.Item8", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 19 (0x13)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item4""
IL_0006: ldloc.0
IL_0007: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_000c: ldfld ""int System.ValueTuple<int>.Item1""
IL_0011: add
IL_0012: ret
}");
});
}
[Fact]
public void LongTupleLocalElement_Names()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, Three: 3, Four: 4, 5, 6, 7, Eight: 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item8 + x.Eight", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0006: ldfld ""int System.ValueTuple<int>.Item1""
IL_000b: ldloc.0
IL_000c: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0011: ldfld ""int System.ValueTuple<int>.Item1""
IL_0016: add
IL_0017: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void DeclareLocal()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
"(int A, int B) y = x;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Null(tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@"{
// Code size 64 (0x40)
.maxstack 6
.locals init (System.ValueTuple<int, int> V_0) //x
IL_0000: ldtoken ""System.ValueTuple<int, int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""y""
IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1""
IL_0014: newobj ""System.Guid..ctor(string)""
IL_0019: ldc.i4.5
IL_001a: newarr ""byte""
IL_001f: dup
IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.845151BC3876B3B783409FD71AF3665D783D8036161B4A2D2ACD27E1A0FCEDF7""
IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_002f: ldstr ""y""
IL_0034: call ""System.ValueTuple<int, int> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<System.ValueTuple<int, int>>(string)""
IL_0039: ldloc.0
IL_003a: stobj ""System.ValueTuple<int, int>""
IL_003f: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")]
public void AliasElement()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(
runtime,
"C.M");
// (int A, (int, int D) B)[] t;
var aliasElementNames = new ReadOnlyCollection<string>(new[] { "A", "B", null, "D" });
var alias = new Alias(
DkmClrAliasKind.Variable,
"t",
"t",
"System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
CustomTypeInfo.PayloadTypeId,
CustomTypeInfo.Encode(null, aliasElementNames));
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var diagnostics = DiagnosticBag.GetInstance();
var testData = new CompilationTestData();
var assembly = context.CompileGetLocals(
locals,
argumentsOnly: false,
aliases: ImmutableArray.Create(alias),
diagnostics: diagnostics,
typeName: out typeName,
testData: testData);
diagnostics.Verify();
diagnostics.Free();
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(aliasElementNames, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = (TypeSymbol)method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(((ArrayTypeSymbol)returnType).ElementType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "t", expectedILOpt:
@"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""t""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""System.ValueTuple<int, System.ValueTuple<int, int>>[]""
IL_000f: ret
}");
locals.Free();
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
public void AliasElement_NoNames()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var alias = new Alias(
DkmClrAliasKind.Variable,
"x",
"x",
"System.ValueTuple`8[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.ValueTuple`2[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
Guid.Empty,
null);
ResultProperties resultProperties;
string error;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var testData = new CompilationTestData();
context.CompileExpression(
"x.Item4 + x.Item8",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(alias),
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
null,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldstr ""x""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_000f: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Item4""
IL_0014: ldstr ""x""
IL_0019: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_001e: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Rest""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_002d: add
IL_002e: ret
}");
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class TupleTests : ExpressionCompilerTestBase
{
[Fact]
public void Literal()
{
var source =
@"class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A", "B" }, tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
methodData.VerifyIL(
@"{
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void DuplicateValueTupleBetweenMscorlibAndLibrary()
{
var versionTemplate = @"[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]";
var corlib_cs = @"
namespace System
{
public class Object { }
public struct Int32 { }
public struct Boolean { }
public class String { }
public class ValueType { }
public struct Void { }
public class Attribute { }
}
namespace System.Reflection
{
public class AssemblyVersionAttribute : Attribute
{
public AssemblyVersionAttribute(String version) { }
}
}";
string valuetuple_cs = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}";
var corlibWithoutVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "1") + corlib_cs) }, assemblyName: "corlib");
corlibWithoutVT.VerifyDiagnostics();
var corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference();
var corlibWithVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "2") + corlib_cs + valuetuple_cs) }, assemblyName: "corlib");
corlibWithVT.VerifyDiagnostics();
var source =
@"class C
{
static (int, int) M()
{
(int, int) t = (1, 2);
return t;
}
}
";
var app = CreateEmptyCompilation(source + valuetuple_cs, references: new[] { corlibWithoutVTRef }, options: TestOptions.DebugDll);
app.VerifyDiagnostics();
// Create EE context with app assembly (including ValueTuple) and a more recent corlib (also including ValueTuple)
var runtime = CreateRuntimeInstance(new[] { app.ToModuleInstance(), corlibWithVT.ToModuleInstance() });
var evalContext = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var compileResult = evalContext.CompileExpression("(1, 2)", out error, testData);
Assert.Null(error);
using (ModuleMetadata block = ModuleMetadata.CreateFromStream(new MemoryStream(compileResult.Assembly)))
{
var reader = block.MetadataReader;
var appRef = app.Assembly.Identity.Name;
AssertEx.SetEqual(new[] { "corlib 2.0", appRef + " 0.0" }, reader.DumpAssemblyReferences());
AssertEx.SetEqual(new[] {
"Object, System, AssemblyReference:corlib",
"ValueTuple`2, System, AssemblyReference:" + appRef // ValueTuple comes from app, not corlib
},
reader.DumpTypeReferences());
}
}
[Fact]
public void TupleElementNamesAttribute_NotAvailable()
{
var source =
@"namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 _1, T2 _2)
{
Item1 = _1;
Item2 = _2;
}
}
}
class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
Assert.Null(customTypeInfo);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@" {
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void Local()
{
var source =
@"class C
{
static void M()
{
(int A\u1234, int \u1234B) o = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A\u1234", "\u1234B" }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
Assert.True(method.ReturnType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "o", expectedILOpt:
string.Format(@"{{
// Code size 2 (0x2)
.maxstack 1
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}}", '\u1234'));
locals.Free();
});
}
[Fact]
public void Constant()
{
var source =
@"class A<T>
{
internal class B<U>
{
}
}
class C
{
static (object, object) F;
static void M()
{
const A<(int, int A)>.B<(object B, object)>[] c = null;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { null, "A", "B", null }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(returnType.ContainsTuple());
VerifyLocal(testData, typeName, locals[0], "<>m0", "c", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
[Fact]
public void LongTupleLocalElement_NoNames()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, 3, 4, 5, 6, 7, 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item4 + x.Item8", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 19 (0x13)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item4""
IL_0006: ldloc.0
IL_0007: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_000c: ldfld ""int System.ValueTuple<int>.Item1""
IL_0011: add
IL_0012: ret
}");
});
}
[Fact]
public void LongTupleLocalElement_Names()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, Three: 3, Four: 4, 5, 6, 7, Eight: 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item8 + x.Eight", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0006: ldfld ""int System.ValueTuple<int>.Item1""
IL_000b: ldloc.0
IL_000c: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0011: ldfld ""int System.ValueTuple<int>.Item1""
IL_0016: add
IL_0017: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void DeclareLocal()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
"(int A, int B) y = x;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Null(tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@"{
// Code size 64 (0x40)
.maxstack 6
.locals init (System.ValueTuple<int, int> V_0) //x
IL_0000: ldtoken ""System.ValueTuple<int, int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""y""
IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1""
IL_0014: newobj ""System.Guid..ctor(string)""
IL_0019: ldc.i4.5
IL_001a: newarr ""byte""
IL_001f: dup
IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.845151BC3876B3B783409FD71AF3665D783D8036161B4A2D2ACD27E1A0FCEDF7""
IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_002f: ldstr ""y""
IL_0034: call ""System.ValueTuple<int, int> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<System.ValueTuple<int, int>>(string)""
IL_0039: ldloc.0
IL_003a: stobj ""System.ValueTuple<int, int>""
IL_003f: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")]
public void AliasElement()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(
runtime,
"C.M");
// (int A, (int, int D) B)[] t;
var aliasElementNames = new ReadOnlyCollection<string>(new[] { "A", "B", null, "D" });
var alias = new Alias(
DkmClrAliasKind.Variable,
"t",
"t",
"System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
CustomTypeInfo.PayloadTypeId,
CustomTypeInfo.Encode(null, aliasElementNames));
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var diagnostics = DiagnosticBag.GetInstance();
var testData = new CompilationTestData();
var assembly = context.CompileGetLocals(
locals,
argumentsOnly: false,
aliases: ImmutableArray.Create(alias),
diagnostics: diagnostics,
typeName: out typeName,
testData: testData);
diagnostics.Verify();
diagnostics.Free();
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(aliasElementNames, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = (TypeSymbol)method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(((ArrayTypeSymbol)returnType).ElementType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "t", expectedILOpt:
@"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""t""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""System.ValueTuple<int, System.ValueTuple<int, int>>[]""
IL_000f: ret
}");
locals.Free();
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
public void AliasElement_NoNames()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var alias = new Alias(
DkmClrAliasKind.Variable,
"x",
"x",
"System.ValueTuple`8[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.ValueTuple`2[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
Guid.Empty,
null);
ResultProperties resultProperties;
string error;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var testData = new CompilationTestData();
context.CompileExpression(
"x.Item4 + x.Item8",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(alias),
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
null,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldstr ""x""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_000f: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Item4""
IL_0014: ldstr ""x""
IL_0019: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_001e: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Rest""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_002d: add
IL_002e: ret
}");
});
}
}
}
| -1 |
dotnet/roslyn | 55,074 | Move EnC language service implementation down to EditorFeatures | Also removes old interfaces. | tmat | 2021-07-23T17:08:06Z | 2021-07-27T16:06:51Z | 4d107c3266686a06960046eadd299d3ac9b25d81 | 77e20f412539203837231ef2e31d7699b6cdffdc | Move EnC language service implementation down to EditorFeatures. Also removes old interfaces. | ./src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicAdditionalFormattingRuleLanguageService.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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus
<ExportLanguageService(GetType(IAdditionalFormattingRuleLanguageService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicAdditionalFormattingRuleLanguageService
Implements IAdditionalFormattingRuleLanguageService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function GetAdditionalCodeGenerationRule() As AbstractFormattingRule Implements IAdditionalFormattingRuleLanguageService.GetAdditionalCodeGenerationRule
Return LineAdjustmentFormattingRule.Instance
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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus
<ExportLanguageService(GetType(IAdditionalFormattingRuleLanguageService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicAdditionalFormattingRuleLanguageService
Implements IAdditionalFormattingRuleLanguageService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function GetAdditionalCodeGenerationRule() As AbstractFormattingRule Implements IAdditionalFormattingRuleLanguageService.GetAdditionalCodeGenerationRule
Return LineAdjustmentFormattingRule.Instance
End Function
End Class
End Namespace
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.